diff --git a/seaweed-block/.gitattributes b/seaweed-block/.gitattributes new file mode 100644 index 0000000000..22dc0a8d6c --- /dev/null +++ b/seaweed-block/.gitattributes @@ -0,0 +1,2 @@ +*.sh text eol=lf +core/chunkkernel/chunk-kernel-2.tsv text eol=lf diff --git a/seaweed-block/.github/model-code-trace.md b/seaweed-block/.github/model-code-trace.md new file mode 100644 index 0000000000..3c8b881d25 --- /dev/null +++ b/seaweed-block/.github/model-code-trace.md @@ -0,0 +1,47 @@ +# Model citations for mapped files + +The spec-trace workflow reads `model-code-trace.tsv` and the validator from +the target branch. A PR cannot replace its own mapping or checker. + +Each non-comment line has two tab-separated columns: an exact repository +path and `Module.Action`. Repeat a path to list alternative actions that +cover it. Paths are case-sensitive; directories and glob patterns are not +expanded. Missing, empty or malformed mappings refuse the check. + +The reviewed map uses the neutral public module names: `SnapshotRemoval`, +`RestoreTarget`, `HolderInterface`, `EngineAdapter`, `StopAndRestart`, +`MoveAdmission`, `Promotion`, `ProbeRound`, `FencingRound`, `VolumeCreate`, +`ReplicationPeer` and `RestoreCommand`. +Actions name top-level definitions used by the corresponding model's `Next`. +The mapping is the source of accepted citations; private model names and +storage locations do not belong in the public map or PR description. + +For every changed mapped path, including deletions, the PR's `Model:` line +must contain a listed action or `NONE (pure function of Module)` for that +module. Separate multiple citations with semicolons, for example: + +```text +Model: EngineAdapter.Begin; MoveAdmission.Revoke; NONE (pure function of RestoreTarget) +``` + +Unmapped paths keep the existing spec-trace policy. The pure-function +declaration is a review claim; CI checks its module, not its truth. + +## Adding a model or file + +1. Have the model owner confirm its neutral public module name and the + top-level action definitions used by `Next`. Use those names in public + code, mapping rows and PR descriptions. +2. Add an exact-path TSV row for each implementation and enforcement file + that the action covers. Split actions get separate rows. Include receiving + guards as well as senders; a reviewer checks that each file really enforces + the cited action. Environment actions without a Go site and mutant test + obligations are not implementation mappings. +3. Add controls for accepted and refused citations when extending the + checker. For mapping additions, check the real map against representative + affected paths. Run `python3 -B .github/scripts/model-trace-check-test.py` + and `bash .github/scripts/spec-trace-check-test.sh` on Linux. +4. Submit the map and its evidence for review with the model change or before + its callers land. The PR description cites the applicable public actions. + The new rows govern later PRs once they are on the target branch; changing + a PR's own map never changes the check that evaluates that PR. diff --git a/seaweed-block/.github/model-code-trace.tsv b/seaweed-block/.github/model-code-trace.tsv new file mode 100644 index 0000000000..15a49d44f8 --- /dev/null +++ b/seaweed-block/.github/model-code-trace.tsv @@ -0,0 +1,208 @@ +# Exact repository-relative pathModule.Action; repeat a path for alternatives. +cmd/sw-block/volume_backup.go RestoreCommand.Abort +cmd/sw-block/volume_backup.go RestoreCommand.AbortVerify +cmd/sw-block/volume_backup.go RestoreCommand.Run +cmd/sw-block/volume_backup.go RestoreCommand.Start +core/authority/workspace.go HolderInterface.ForcedMove +core/authority/workspace.go HolderInterface.PlannedMove +core/authority/workspace.go MoveAdmission.Ack +core/authority/workspace.go MoveAdmission.IssueClean +core/authority/workspace.go MoveAdmission.IssueForced +core/authority/workspace.go MoveAdmission.Lease2Ends +core/authority/workspace.go MoveAdmission.LeaseEnds +core/authority/workspace.go MoveAdmission.ReadForMove +core/authority/workspace.go MoveAdmission.Revoke +core/authority/workspace.go StopAndRestart.IssueClean +core/authority/workspace.go StopAndRestart.IssueForced +core/authority/workspace.go StopAndRestart.LeaseEnds +core/authority/workspace.go StopAndRestart.ReadForced +core/authority/workspace_delete_reservation.go MoveAdmission.DelCheck +core/authority/workspace_delete_reservation.go MoveAdmission.Reserve +core/authority/workspace_lease_view.go HolderInterface.Grant +core/authority/workspace_lease_view.go HolderInterface.Regrant +core/engine/apply.go ReplicationPeer.Reconcile +core/frontend/chunkstore/layout/claim.go EngineAdapter.Takeover +core/frontend/chunkstore/layout/claim.go MoveAdmission.ClaimB +core/frontend/chunkstore/layout/claim.go SnapshotRemoval.Claim +core/frontend/chunkstore/layout/claim.go StopAndRestart.ClaimB +core/frontend/chunkstore/layout/clean.go EngineAdapter.MaintBegin +core/frontend/chunkstore/layout/clean.go EngineAdapter.MaintEnd +core/frontend/chunkstore/layout/clean.go SnapshotRemoval.BeginClean +core/frontend/chunkstore/layout/clean.go SnapshotRemoval.EndClean +core/frontend/chunkstore/layout/commit.go EngineAdapter.Apply +core/frontend/chunkstore/layout/commit.go SnapshotRemoval.Commit +core/frontend/chunkstore/layout/commit.go VolumeCreate.Commit +core/frontend/chunkstore/layout/create.go RestoreTarget.CreateHead +core/frontend/chunkstore/layout/create.go RestoreTarget.CreateVol +core/frontend/chunkstore/layout/create.go VolumeCreate.Claim +core/frontend/chunkstore/layout/delete.go MoveAdmission.DelMark +core/frontend/chunkstore/layout/delete.go MoveAdmission.DelRead +core/frontend/chunkstore/layout/delete.go RestoreTarget.OpRelease +core/frontend/chunkstore/layout/delete.go RestoreTarget.OpTomb +core/frontend/chunkstore/layout/head.go SnapshotRemoval.Abort +core/frontend/chunkstore/layout/head.go SnapshotRemoval.Begin +core/frontend/chunkstore/layout/head.go StopAndRestart.Apply +core/frontend/chunkstore/layout/head.go StopAndRestart.Begin +core/frontend/chunkstore/layout/objects.go SnapshotRemoval.Upload +core/frontend/chunkstore/layout/remove.go SnapshotRemoval.Issue +core/frontend/chunkstore/layout/remove.go SnapshotRemoval.Stat +core/frontend/chunkstore/layout/remove.go SnapshotRemoval.Validate +core/frontend/chunkstore/layout/snapshots.go EngineAdapter.OpWrite +core/frontend/chunkstore/layout/snapshots.go MoveAdmission.OpWrite +core/frontend/chunkstore/layout/snapshots.go RestoreTarget.AddDep +core/frontend/chunkstore/layout/snapshots.go SnapshotRemoval.DeleteSnap +core/frontend/chunkstore/layout/start.go HolderInterface.Start +core/frontend/chunkstore/layout/start.go StopAndRestart.CrashRestart +core/frontend/chunkstore/layout/start.go VolumeCreate.Claim +core/frontend/chunkstore/layout_create.go VolumeCreate.IssueHead +core/frontend/chunkstore/layout_create.go VolumeCreate.IssueVol +core/frontend/chunkstore/layout_remote.go EngineAdapter.Begin +core/frontend/chunkstore/layout_remote.go EngineAdapter.ReadHead +core/frontend/chunkstore/layout_remote.go EngineAdapter.SendCommit +core/frontend/chunkstore/layout_remote.go EngineAdapter.SettleAbort +core/frontend/chunkstore/layout_remote.go EngineAdapter.TakeAbandon +core/frontend/chunkstore/layout_remote.go StopAndRestart.SendCommit +core/frontend/chunkstore/layout_remote.go StopAndRestart.SettleAbort +core/frontend/chunkstore/layout_store.go SnapshotRemoval.ApplyDelete +core/frontend/chunkstore/layout_store.go SnapshotRemoval.ApplyMark +core/frontend/chunkstore/swfs.go VolumeCreate.Land +core/frontend/durable/provider_chunk.go EngineAdapter.SettleResume +core/frontend/durable/provider_chunk.go EngineAdapter.StartStop +core/frontend/durable/provider_chunk.go HolderInterface.StopBegin +core/frontend/durable/provider_chunk.go StopAndRestart.SendDetach +core/frontend/durable/provider_chunk.go StopAndRestart.SettleResume +core/frontend/durable/provider_layout.go EngineAdapter.SettleDown +core/frontend/durable/provider_layout.go StopAndRestart.SettleDown +core/frontend/durable/storage_adapter.go EngineAdapter.GuestWrite +core/frontend/durable/storage_adapter.go HolderInterface.Write +core/host/master/layout_ready.go VolumeCreate.Place +core/host/master/probe_round.go FencingRound.Deliver +core/host/master/probe_round.go FencingRound.Open +core/host/master/product_loop.go FencingRound.Decide +core/host/master/product_loop.go Promotion.Decide +core/host/master/store_attestation.go ReplicationPeer.Attest +core/host/master/workspace_service.go MoveAdmission.ReadForMove +core/host/master/workspace_service.go StopAndRestart.ReadClean +core/host/volume/primary_evidence.go FencingRound.Adopt +core/host/volume/primary_evidence.go Promotion.Adopt +core/host/volume/primary_evidence.go Promotion.Refuse +core/host/volume/probe_round.go FencingRound.Answer +core/host/volume/workspace_lease.go HolderInterface.Expire +core/host/volume/workspace_lease.go MoveAdmission.StopOnExpiry +core/host/volume/workspace_lease.go MoveAdmission.Write +core/host/volume/workspace_lease.go SnapshotRemoval.Expire +core/host/volume/workspace_lease.go StopAndRestart.Write +core/lifecycle/store.go VolumeCreate.MarkReady +core/lifecycle/store.go VolumeCreate.Record +core/replication/peer.go Promotion.Ship1 +core/replication/peer.go Promotion.Ship2 +core/replication/peer.go ReplicationPeer.Barrier +core/replication/peer.go ReplicationPeer.Fail +core/replication/peer.go ReplicationPeer.Heal +core/replication/peer.go ReplicationPeer.Ship +core/replication/volume.go FencingRound.Ack +core/replication/volume.go Promotion.Ack1 +core/replication/volume.go Promotion.Rejoin +core/replication/volume.go Promotion.Write1 +core/replication/volume.go Promotion.Write2 +core/replication/volume.go ReplicationPeer.Ack +core/replication/volume.go ReplicationPeer.Write +core/storage/chunk_head_belt.go HolderInterface.Fence +core/storage/chunk_layer.go EngineAdapter.EngineReRead +core/storage/chunk_layer.go EngineAdapter.NoOpCut +core/storage/chunk_layer.go HolderInterface.Commit +core/storage/chunk_layer.go HolderInterface.StopCommit +core/storage/chunk_layer.go MoveAdmission.Detach +core/storage/chunk_layer.go MoveAdmission.Publish +core/storage/chunk_layer.go SnapshotRemoval.Write +core/storage/chunk_state_upgrade.go SlotFence.Publish +core/storage/chunk_state_upgrade.go SlotFence.Sync +core/transport/catchup_sender.go ReplicationPeer.CatchUp +core/transport/rebuild_sender.go ReplicationPeer.Rebuild +core/transport/replica.go FencingRound.Recv +core/transport/replica.go ReplicationPeer.CatchUp +core/transport/replica.go ReplicationPeer.Rebuild +core/transport/replica.go ReplicationPeer.Ship +core/storage/chunk_coverage.go SlotFence.Publish +core/storage/chunk_coverage_map.go MoveWide2.Write +core/storage/walstore_v3.go SlotFence2.OpenNew + +core/frontend/chunkstore/snapshot_operation.go SnapOps.Send +core/frontend/chunkstore/snapshot_operation.go SnapOps.TornAdmit +core/frontend/chunkstore/snapshot_operation.go SnapOps.Retire +core/frontend/chunkstore/snapshot_operation_index.go SnapOps.TermFlag +core/frontend/chunkstore/snapshot_operation_index.go SnapOps.GC +core/frontend/chunkstore/snapshot_operation_index.go SnapOps.Poll +core/frontend/chunkstore/snapshot_operation_guard.go SnapOps.Publish +core/frontend/chunkstore/snapshot_operation_guard.go SnapOps.Delete +core/host/volume/chunk_control.go SnapOps.Start +cmd/sw-block/snapshot_operation.go SnapOps.Send +core/host/volume/snapshot_operation.go SnapOps.Start +cmd/blockvolume/snapshot_operation_shutdown.go SnapOps.Stall +core/frontend/chunkstore/snapshot_delete_operation.go SnapDelete.Send +core/storage/wal_admission_fast.go WALHold.FastArrive +core/storage/wal_admission_fast.go WALHold.FastReEnter +core/storage/wal_admission_fast.go WALHold.FastResubmit +core/storage/wal_admission.go WALHold.Arrive +core/storage/wal_admission_fifo.go WALHold.Arrive +core/storage/wal_admission_fifo.go WALHold.ReEnter +core/storage/wal_admission_fifo.go WALHold.Admit +core/storage/walstore.go WALHold.Admit +core/frontend/durable/storage_adapter.go WALHold.Resubmit +core/storage/flusher.go WALHold.Reclaim +core/storage/wal_hold_window.go WALHold.Stall +core/storage/wal_write_hold.go WALHold.Stall +core/storage/wal_hold_window.go WALHold.CapAnswer +core/storage/wal_write_hold.go WALHold.CapAnswer +core/frontend/nvme/io.go WALHold.Stall +core/frontend/iscsi/scsi.go WALHold.Stall +core/host/master/format_gate.go FormatGate.Finalize +core/host/master/format_gate.go FormatGate.Place +core/host/master/workspace_service.go FormatGate.Place +core/host/master/format_gate.go FormatGate.Grant +core/host/master/workspace_binding.go FormatGate.Grant +core/host/master/format_gate.go FormatGate.Report +core/host/master/services.go FormatGate.Report +core/host/master/format_gate.go FormatGate.Retire +core/host/volume/host.go FormatGate.Upgrade +core/host/volume/host.go FormatGate.Downgrade +core/frontend/chunkstore/layout/format_level.go FormatGate.Upgrade1 +core/frontend/chunkstore/layout/format_level.go FormatGate.PublishOp +core/frontend/chunkstore/snapshot_delete_target.go FormatGate.AdmitOp +core/frontend/chunkstore/snapshot_delete_operation.go FormatGate.AdmitOp +core/storage/recovery_progress.go RecoveryProgress.Replay +core/host/volume/recovery_watchdog.go RecoveryProgress.Replay +core/storage/walstore_v3.go RecoveryProgress.Fence +core/host/volume/recovery_watchdog.go RecoveryProgress.Fence +core/host/volume/recovery_watchdog.go RecoveryProgress.ToFence +core/host/volume/recovery_watchdog.go RecoveryProgress.Authority +core/host/volume/recovery_watchdog.go RecoveryProgress.Stall +core/frontend/chunkstore/layout/delete_intent.go PageChain.WritePage +core/frontend/chunkstore/layout/list_chain.go PageChain.WritePage +core/frontend/chunkstore/layout/delete_intent.go PageChain.Send +core/frontend/chunkstore/layout/list_chain.go PageChain.Send +core/frontend/chunkstore/layout/delete_intent.go PageChain.Resend +core/frontend/chunkstore/layout/list_chain.go PageChain.Resend +core/frontend/chunkstore/layout/delete_intent.go PageChain.CRead +core/frontend/chunkstore/layout/list_chain.go PageChain.CRead +core/frontend/chunkstore/layout/delete_intent.go PageChain.CApply +core/frontend/chunkstore/layout/delete_intent.go PageChain.CAdvance +core/frontend/chunkstore/layout/list_chain.go PageChain.CAdvance +core/frontend/chunkstore/layout/delete_intent.go PageChain.CResolve +core/frontend/chunkstore/layout/list_chain.go PageChain.CResolve +core/frontend/chunkstore/clean_intent_b.go PageChain.CRead +core/frontend/chunkstore/layout_remote.go PageChain.CRead +core/frontend/chunkstore/layout/remove.go PageChain.Sweep +core/frontend/chunkstore/clean_b.go PageChain.Sweep +core/frontend/chunkstore/layout/remove.go StaleClean.Stat +core/frontend/chunkstore/layout/remove.go StaleClean.HeadRead +core/frontend/chunkstore/layout/remove.go StaleClean.MarkIt +core/frontend/chunkstore/layout/remove.go StaleClean.DeleteIt +core/frontend/chunkstore/layout_store.go StaleClean.Adopt +core/frontend/chunkstore/layout/commit.go StaleClean.HeadCommit +core/frontend/chunkstore/layout/commit.go StaleClean.CommitCheck +core/frontend/chunkstore/layout/delete_intent.go QueueCap.Produce +core/frontend/chunkstore/layout/list_chain.go QueueCap.Produce +core/frontend/chunkstore/layout/delete_intent.go QueueCap.Consume +core/frontend/chunkstore/clean_intent_b.go QueueCap.Consume +core/frontend/chunkstore/layout/commit.go QueueCap.TakeBack diff --git a/seaweed-block/.github/post-merge-review-allow.txt b/seaweed-block/.github/post-merge-review-allow.txt new file mode 100644 index 0000000000..7aa3a5325a --- /dev/null +++ b/seaweed-block/.github/post-merge-review-allow.txt @@ -0,0 +1,94 @@ +# What a PR labelled "post-merge-review" may touch. +# +# A labelled PR passes the "post-merge-review paths" check only if EVERY +# changed file (both names of a rename) matches an allow line and no "!" +# line. Anything not allowed is denied: new files start denied. A PR that +# fails keeps the full review before merge. Without the label the check +# passes and nothing changes. +# +# One bash glob per line, matched against the repo-relative path; "*" also +# matches "/". A line starting with "!" denies, and wins over any allow line. +# Blank lines and text after "#" are ignored. The check reads this file from +# the base branch, so a PR cannot loosen its own check; a missing or empty +# file fails the check. + +# ---- Allowed ---- + +# Docs. +docs/* +*.md + +# Tests: added or modified, never deleted or moved (the check enforces +# that); a test file in a denied directory stays denied. +*_test.go + +# Status, metrics and observation files, by name. +core/host/master/observation_service.go +core/host/master/observation_snapshot.go +core/host/volume/memory_status.go +core/ops/observation.go +core/ops/observation_bundle.go +core/ops/observation_dashboard.go +core/ops/observation_report.go +core/ops/volume_status_artifacts.go +core/ops/volume_status_report.go +core/ops/volume_status_report_collector.go +core/ops/volume_status_summary.go + +# ---- Denied even if allowed above ---- + +# The check itself and CI. +!.github/* + +# The test gates: the testops engine, its CLI and the gate definitions +# (their docs stay allowed). +!internal/testops/*.go +!internal/testops/*.json +!cmd/sw-testops/* + +# Data path and replication. +!core/storage/* +!core/frontend/* +!core/transport/* +!core/replication/* +!core/recovery/* +!core/engine/* +!core/adapter/* + +# Authority: lease, epoch, fencing, move. +!core/authority/* +!core/host/master/workspace_* +!core/host/volume/workspace_* +!cmd/blockvolume/workspace_lease* + +# Wire and persisted formats. +!*.proto +!*.pb.go +!core/host/master/journal_isolation* +!core/lifecycle/store* +!cmd/sparrow/persist* + +# GC and delete paths. +!cmd/sw-block/chunk_gc* +!cmd/sw-block/chunk_volume_delete* +!core/lifecycle/deletion_reservations* +!core/ops/delete_safety_contract* +!*/gc[_.]* +!*_gc[_.]* + +# Lease, epoch, claim, admission, GC, delete or format code (tests included) +# wherever it lives, by file name. +!*/lease*.go +!*_lease*.go +!*epoch*.go +!*fenc*.go +!*claim*.go +!*admission*.go +!*/gc_*.go +!*_gc.go +!*_gc_*.go +!*delet*.go +!*purge*.go +!*persist*.go +!*journal*.go +!*format*.go diff --git a/seaweed-block/.github/process-level-seconds.txt b/seaweed-block/.github/process-level-seconds.txt new file mode 100644 index 0000000000..d4bed17ae1 --- /dev/null +++ b/seaweed-block/.github/process-level-seconds.txt @@ -0,0 +1,47 @@ +# Seconds each process-level test took on the CI runner (main 032eb197, run 45972669823), +# used only to balance the parallel shards (.github/scripts/shard-named-tests.py). A test +# missing here counts as 60 s; a stale time unbalances the shards but never skips a test. +TestAVolumeThatServedBeforeItsFirstGateTickFailsOver 31.4 +TestClaimedTargetAfterAMasterRestartIsNotNeverStarted 18.7 +TestCutoverCreateFromSnapshot 25.4 +TestCutoverWriteSnapshotKillRestartRestore 34.1 +TestDoubleFailoverReadsBackEveryAckedWrite 10.2 +TestFencingRoundHealContinuesThePrimary 13.4 +TestFencingRoundSurvivorRejoins 17.0 +TestKnownZeroAcceptance 27.1 +TestKnownZeroTargetReservesBeforeHarness 0.0 +TestNeverAttachedRestoreTargetIsDeletable 16.5 +TestNeverStartedDeleteAfterAMasterRestart 166.8 +TestNeverStartedDeleteFencesALateStart 53.6 +TestNeverStartedDeleteRacesAStart 42.4 +TestNeverStartedLineDeleteFencesALateStart 240.3 +TestNeverStartedLineDeleteRacesAStart 458.9 +TestNeverStartedLineIsDeletableWithoutARevoke 335.1 +TestProcedureDeleteAVolume 79.1 +TestProcedureDeleteAfterASignalStop 116.1 +TestProcedureForcedMoveWithTheOldHostReturning 100.2 +TestProcedureMasterKilledAfterMoveBeforeTargetStarts 23.2 +TestProcedureMasterUnreachableFencesBeforeForcedMove 159.4 +TestProcedurePlannedHandoffToAnotherHost 16.8 +TestProcedureReturnAfterALapsedLease 81.4 +TestProcedureRevokeWithoutACKThenForcedMove 79.6 +TestProcedureSameHostCrashRestartInsideTheLease 17.5 +TestProcedureSameHostRestartInsideTheLease 17.5 +TestProcedureStartInsideTheBarrierWaitIsReGranted 80.0 +TestSnapshotLadderA1OneBlockOneSnapshot 18.8 +TestSnapshotLadderA2IncrementalSnapshot 20.9 +TestSnapshotLadderA3WritesDuringASnapshot 26.1 +TestSnapshotLadderA4ContentReturnsToAnOldValue 23.6 +TestSnapshotLadderB1SnapshotQuery 19.1 +TestSnapshotLadderC1FullRestore 18.8 +TestSnapshotLadderC2IncrementalRestore 21.3 +TestSnapshotLadderC3KilledHydrating 35.6 +TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt 21.3 +TestSnapshotLadderD1DeleteTheNewest 21.4 +TestSnapshotLadderD2DeleteAMiddleOne 23.9 +TestSnapshotLadderD3DeleteWhenContentRecurs 21.3 +TestSnapshotLadderD4DeleteAllButOneThenCollect 19.4 +TestSnapshotLadderE1CrashDuringASnapshot 31.1 +TestSnapshotLadderF1VolumesOneHost 528.4 +TestStandaloneCleanMoveWithoutTheACKIsRefused 16.6 +TestStandalonePlannedHandoffToTheSameHost 17.7 diff --git a/seaweed-block/.github/process-level-tests.txt b/seaweed-block/.github/process-level-tests.txt new file mode 100644 index 0000000000..6960f23b0e --- /dev/null +++ b/seaweed-block/.github/process-level-tests.txt @@ -0,0 +1,91 @@ +# Process-level tests (cmd/blockvolume with build tags subprocess and +# chunkstore_integration, linux) named as release evidence. CI runs them +# against real blockmaster, blockvolume and sw-block binaries and the pinned +# SeaweedFS release. Every name here must PASS: a skip, a failure or a test +# that never ran fails the job (.github/scripts/required-tests-check.py). +# +# Not here, and why: the three headroom tests (TestHeadroom*), the power-loss +# replay (TestPowerLossReplayChunkVolume, a dm-log-writes harness) and the +# tests tagged systemd_integration need root, a loop or mapped device, or +# systemd; the CI runners have none of these. They run as root outside CI, +# and their counts are recorded there. + +# Known-zero acceptance, small shape in CI (KZ_RUN=1 KZ_SIZE=1G, user-space +# client, no device); the 1 TiB run is lab only. +TestKnownZeroAcceptance +TestKnownZeroTargetReservesBeforeHarness + +# The procedure gate, delete and master loss. +TestProcedurePlannedHandoffToAnotherHost +TestProcedureSameHostRestartInsideTheLease +TestProcedureSameHostCrashRestartInsideTheLease +TestProcedureReturnAfterALapsedLease +TestProcedureForcedMoveWithTheOldHostReturning +TestProcedureRevokeWithoutACKThenForcedMove +TestProcedureStartInsideTheBarrierWaitIsReGranted +TestProcedureDeleteAVolume +TestANewClustersRealHolderReportsLevel1AndIsGranted +TestProcedureDeleteAfterASignalStop +TestProcedureMasterKilledAfterMoveBeforeTargetStarts +TestProcedureMasterUnreachableFencesBeforeForcedMove +TestStandalonePlannedHandoffToTheSameHost +TestStandaloneCleanMoveWithoutTheACKIsRefused + +# Failover and the fencing round. +TestDoubleFailoverReadsBackEveryAckedWrite +# The replicated preview's fencing round runs and is reported on every job but +# does not gate it (#920: a sync-quorum flush under shared-runner load); it +# gates the nightly run on a quiet lab box. +TestFencingRoundHealContinuesThePrimary # nongating=#920 +TestFencingRoundSurvivorRejoins # nongating=#920 +TestAVolumeThatServedBeforeItsFirstGateTickFailsOver + +# Many volumes on one host (F1_RUN=1). +TestSnapshotLadderF1VolumesOneHost + +# Never-started delete. +TestNeverAttachedRestoreTargetIsDeletable +TestNeverStartedDeleteFencesALateStart +TestNeverStartedDeleteRacesAStart +TestNeverStartedLineIsDeletableWithoutARevoke +TestNeverStartedLineDeleteFencesALateStart +TestNeverStartedLineDeleteRacesAStart +TestNeverStartedDeleteAfterAMasterRestart +TestClaimedTargetAfterAMasterRestartIsNotNeverStarted + +# Snapshot ladders and cutover. +TestSnapshotLadderA1OneBlockOneSnapshot +TestSnapshotLadderA2IncrementalSnapshot +TestSnapshotLadderA3WritesDuringASnapshot +TestSnapshotLadderA4ContentReturnsToAnOldValue +TestSnapshotLadderB1SnapshotQuery +TestSnapshotLadderC1FullRestore +TestSnapshotLadderC2IncrementalRestore +TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt +# A first write after the holder reports its frontend ready can be answered +# namespace-not-ready for longer than a host retries (#905, a v1.1 release +# gate); it runs and is reported on every job until the fix removes this. +TestSnapshotLadderC3KilledHydrating # nongating=#905 +TestSnapshotLadderD1DeleteTheNewest +TestSnapshotLadderD2DeleteAMiddleOne +TestSnapshotLadderD3DeleteWhenContentRecurs +TestSnapshotLadderD4DeleteAllButOneThenCollect +TestSnapshotLadderE1CrashDuringASnapshot +TestCutoverCreateFromSnapshot +TestCutoverWriteSnapshotKillRestartRestore + +# CSI real-binary seams: dispatched to blockcsi.test in the same process job. +# package=blockcsi is routing metadata; the required-test checker needs all names. +TestBlockCSI_BinaryStartsAndServesIdentity # package=blockcsi +TestG15a_BlockCSIControllerPublishUsesMasterFrontendFact # package=blockcsi +TestG15c_BlockCSICreateVolumeWritesMasterLifecycleIntent # package=blockcsi + +# Typed delete stdout remains separate from HEAD diagnostics. +TestDeleteNoRevokeKeepsTheTypedStdoutSeparate + +# Procedure ordering compares the UTC log instant including its fraction. +TestProcedureLogTimesUseTheUTCInstant + +# Snapshot operation intent and publication receipts survive real holder kills. +TestSnapshotOperationIntentAndPublicationCrashBoundaries +TestSnapshotOperationKillReceiptRejectsOrdinaryExit diff --git a/seaweed-block/.github/pull_request_template.md b/seaweed-block/.github/pull_request_template.md new file mode 100644 index 0000000000..61589136cc --- /dev/null +++ b/seaweed-block/.github/pull_request_template.md @@ -0,0 +1,43 @@ +Feature: +Machine/INV: / +Model: +Red-first: +Simplest: + +Five questions, answered in plain words before review: +Serves: +Decided by: +Layer use: +Deviation buys: +Weakens: +Facts: + + diff --git a/seaweed-block/.github/scripts/changed-go-blobs-test.sh b/seaweed-block/.github/scripts/changed-go-blobs-test.sh new file mode 100644 index 0000000000..38b11ea064 --- /dev/null +++ b/seaweed-block/.github/scripts/changed-go-blobs-test.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Self-test of changed-go-blobs.sh and of the fetch setting the PR checks use: +# a PR tree that names a '..' entry must neither write outside the output +# directory nor be fetched at all. +set -euo pipefail +script=$(cd "$(dirname "$0")" && pwd)/changed-go-blobs.sh +t=$(mktemp -d) +trap 'rm -rf "$t"' EXIT +fail() { echo "changed-go-blobs-test: FAIL: $*" >&2; exit 1; } + +git init -q "$t/r" +cd "$t/r" +git config user.email t@example.com +git config user.name t +mkdir -p a +printf 'package a\n' >a/a.go +printf 'package a\n' >a/a_test.go +git add . && git commit -q -m base +base=$(git rev-parse HEAD) + +# 1. An ordinary change: the old and new blobs land under the output directory. +printf 'package a\n\nvar X = 1\n' >a/a.go +printf 'package b\n' >b.go +git add . && git commit -q -m change +bash "$script" "$base" HEAD "$t/out1" +grep -q 'var X' "$t/out1/new/a/a.go" || fail "new blob of a/a.go missing" +[ -f "$t/out1/old/a/a.go" ] || fail "old blob of a/a.go missing" +[ -f "$t/out1/new/b.go" ] && [ ! -e "$t/out1/old/b.go" ] || fail "added file b.go not new-only" +[ ! -e "$t/out1/new/a/a_test.go" ] || fail "a test file was written" + +# 2. A crafted tree: '..' nested three times, holding x.go. git writes such +# a tree only with --literally; the diff still lists '../../../x.go', and +# writing blobs by that path would create new/../../../x.go, outside the +# output directory (the inline loop this script replaced did exactly that). +blob=$(printf 'package evil\n' | git hash-object -w --stdin) +entry() { perl -e 'print $ARGV[0], "\0", pack("H*", $ARGV[1])' "$1" "$2"; } +tr=$(entry "100644 x.go" "$blob" | git hash-object -t tree --literally -w --stdin) +for _ in 1 2 3; do tr=$(entry "40000 .." "$tr" | git hash-object -t tree --literally -w --stdin); done +evil=$(git commit-tree "$tr" -p "$base" -m evil) +mkdir -p "$t/deep/ws/out2" +if bash "$script" "$base" "$evil" "$t/deep/ws/out2" 2>"$t/err"; then fail "a '..' path was accepted"; fi +grep -q 'refusing path' "$t/err" || fail "refusal not reported: $(cat "$t/err")" +[ -z "$(find "$t/deep" -name x.go)" ] || fail "a file was written outside the output directory" + +# 3. The checks fetch the PR head with fetch.fsckObjects=true: the crafted +# tree is refused at the fetch. +git update-ref refs/pull/1/head "$evil" +git init -q "$t/c" +cd "$t/c" +if git -c fetch.fsckObjects=true fetch -q --no-tags "$t/r" "+refs/pull/1/head:refs/remotes/pr/head" 2>"$t/err2"; then + fail "fetch with fsckObjects accepted a '..' tree" +fi +echo "changed-go-blobs-test: PASS (3 cases)" diff --git a/seaweed-block/.github/scripts/changed-go-blobs.sh b/seaweed-block/.github/scripts/changed-go-blobs.sh new file mode 100644 index 0000000000..1884a50b89 --- /dev/null +++ b/seaweed-block/.github/scripts/changed-go-blobs.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Writes the old and new blob of each changed non-test Go file between two +# commits under /old/ and /new/, for the spec trace's +# kind DOCS (objects only; nothing from the PR is built or run). +# +# usage: changed-go-blobs.sh +# +# The paths come from the PR's tree objects, which git does not check when it +# prints a diff. A path that is absolute or has an empty, '.' or '..' +# component would write outside , so it is refused before anything is +# written (exit 1). +set -euo pipefail +mb=$1 head=$2 out=$3 +mkdir -p "$out" +git diff --name-only --no-renames -z "$mb" "$head" -- "*.go" ":(exclude)*_test.go" >"$out/.paths" +while IFS= read -r -d "" p; do + case "/$p/" in + *//* | */./* | */../*) + printf 'changed-go-blobs: refusing path %q\n' "$p" >&2 + exit 1 + ;; + esac +done <"$out/.paths" +while IFS= read -r -d "" p; do + mkdir -p "$out/old/$(dirname "$p")" "$out/new/$(dirname "$p")" + git show "$mb:$p" >"$out/old/$p" 2>/dev/null || rm -f "$out/old/$p" + git show "$head:$p" >"$out/new/$p" 2>/dev/null || rm -f "$out/new/$p" +done <"$out/.paths" +rm -f "$out/.paths" diff --git a/seaweed-block/.github/scripts/chunkstore-scope-test.sh b/seaweed-block/.github/scripts/chunkstore-scope-test.sh new file mode 100644 index 0000000000..b1d5a1c3ad --- /dev/null +++ b/seaweed-block/.github/scripts/chunkstore-scope-test.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Tests chunkstore-scope.sh against real commits. Any failure exits nonzero. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +scope="$here/chunkstore-scope.sh" +fail=0 +check() { # name want got + if [ "$2" = "$3" ]; then echo "ok $1"; else echo "FAIL $1: want [$2], got [$3]"; fail=1; fi +} +repo=$(mktemp -d) +trap 'rm -rf "$repo"' EXIT +cd "$repo" +git init -q +git config user.email t@example.invalid +git config user.name t +git config core.autocrlf false +mkdir -p core/frontend/chunkstore core/frontend/durable core/storage core/other docs +echo c >core/frontend/chunkstore/c.go +echo p >core/frontend/durable/p.go +echo s >core/storage/s.go +echo o >core/other/o.go +echo d >docs/d.md +git add -A +git commit -qm base +base=$(git rev-parse HEAD) +case_of() { # name want: commit the current tree, classify against base, reset + git add -A + git commit -qm "$1" --allow-empty + check "$1" "$2" "$(bash "$scope" "$base" HEAD)" + git reset -q --hard "$base" +} +echo c2 >core/frontend/chunkstore/c.go +case_of "a chunkstore file" "run 1 core/frontend/chunkstore/c.go" +echo p2 >core/frontend/durable/p.go +case_of "a durable provider file only" "run 1 core/frontend/durable/p.go" +echo s2 >core/storage/s.go; echo o2 >core/other/o.go +case_of "storage and another package" "run 2 core/storage/s.go" +echo o2 >core/other/o.go; echo d2 >docs/d.md +case_of "neither path" "skip 2" +case_of "no file changed" "skip 0" +mkdir -p core/storage-old; echo x >core/storage-old/x.go +case_of "a storage-like prefix" "skip 1" +git rm -q core/storage/s.go +case_of "a storage deletion" "run 1 core/storage/s.go" +for i in $(seq 1 20000); do printf 'x\n' >"docs/f$i.md"; done +echo late >core/storage/zz_late.go +case_of "20000 other files and one storage file, listed last" "run 20001 core/storage/zz_late.go" +if out=$(bash "$scope" "$base" no-such-revision 2>/dev/null); then + check "an unknown revision is an error" "nonzero exit" "exit 0: $out" +else + check "an unknown revision is an error" "nonzero exit" "nonzero exit" +fi +exit "$fail" diff --git a/seaweed-block/.github/scripts/chunkstore-scope.sh b/seaweed-block/.github/scripts/chunkstore-scope.sh new file mode 100644 index 0000000000..5b1364ab7d --- /dev/null +++ b/seaweed-block/.github/scripts/chunkstore-scope.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# chunkstore-scope.sh BASE HEAD: decides whether a pull request runs the +# real-filer integration tests. It prints one line: +# "run N FIRST" at least one of the N changed files is under +# core/frontend/chunkstore/, core/storage/ or +# core/frontend/durable/ (FIRST is one) +# "skip N" none of the N changed files is +# and exits 0. Any error (git fails, the list cannot be read) exits nonzero, +# and the caller then runs the tests: an error never selects skip. +# +# The NUL-delimited list is written to a file first and read to its end, so +# no pipe can stop early and leave a writer's error looking like an answer. +set -euo pipefail +[ "$#" -eq 2 ] || { echo "usage: chunkstore-scope.sh BASE HEAD" >&2; exit 2; } +list=$(mktemp) +trap 'rm -f "$list"' EXIT +if ! git diff --name-only --no-renames -z "$1" "$2" >"$list"; then + echo "chunkstore-scope: git diff $1 $2 failed" >&2 + exit 2 +fi +n=0 +hit="" +while IFS= read -r -d '' f; do + n=$((n + 1)) + case $f in + core/frontend/chunkstore/* | core/storage/* | core/frontend/durable/*) [ -n "$hit" ] || hit=$f ;; + esac +done <"$list" +if [ -n "$hit" ]; then + echo "run $n $hit" +else + echo "skip $n" +fi diff --git a/seaweed-block/.github/scripts/ci-evidence.md b/seaweed-block/.github/scripts/ci-evidence.md new file mode 100644 index 0000000000..ab9f09edd9 --- /dev/null +++ b/seaweed-block/.github/scripts/ci-evidence.md @@ -0,0 +1,41 @@ +# Failed-job evidence + +Both test suites keep one `ci---` artifact on failure for +14 days. `go-test.json` contains Go's timestamped events and per-test `Elapsed` +values; process shards also keep their original JSON, logs and exit receipts. +`go-test.stderr` keeps build/tool errors outside Go's JSON event stream. The +console still shows the original test output. Recording/rendering errors are +best effort: they report the missing evidence and keep draining Go, whose own +exit code alone decides the wrapper's result. Test arguments, scope, timeouts, +exit-code handling and the required-tests gate are unchanged. + +`load.tsv` begins immediately after checkout and samples once per second until +the final collection step. It covers setup, builds and tests; the checkout +itself and the artifact upload are outside the sampling interval. The sampler +has the job's maximum lifetime if cancellation prevents its stop step. The +stop receipt includes the process start time, so a recycled PID is not killed. + +Columns: + +- `ts_utc`: UTC timestamp with milliseconds. Scheduling gaps remain visible; + delayed sampling does not invent backfilled one-second rows. +- `load1`: machine load average. +- `steal_pct`, `iowait_pct`: interval percentages from `/proc/stat` (the first + row has no baseline and is null). Guest counters are not counted twice. +- `psi_cpu`, `psi_io`, `psi_mem`: JSON objects containing the kernel's `some` + and, when available, `full` pressure averages and cumulative microseconds. +- `disk_await_ms`: JSON map by device, calculated as the interval's read/write + milliseconds divided by completed reads/writes from `/proc/diskstats`. + Devices are kept separate, including partitions and device-mapper layers; + do not sum them. No completed IO, reset counters or a new device yields null. + Discard and flush-only operations are not included in this read/write mean. +- `cgroup_cpu_max`: JSON map of `cpu.max` for the sampler's current cgroup and + every visible ancestor. The sampler inherits the job's cgroup. Parent quotas + matter even when the leaf says `max`. Cgroup v1/unavailable data is null. +- `errors`: read/parse errors; missing or inaccessible counters are null, + never fabricated zero load. Consult `load.sampler.log` for sampler errors. + +No package installation, sudo, or `iostat` executable is required. `/proc` +CPU/PSI/disk observations are machine-wide; these are correlation evidence, +not proof that the job itself caused contention. Sampling is diagnostic and +does not revoke, retry or change a test's result. diff --git a/seaweed-block/.github/scripts/ci-load-test.py b/seaweed-block/.github/scripts/ci-load-test.py new file mode 100644 index 0000000000..90ff55d3af --- /dev/null +++ b/seaweed-block/.github/scripts/ci-load-test.py @@ -0,0 +1,129 @@ +"""Fixed Linux counter fixtures; no host load or privileged runner needed.""" +import importlib.util +import json +import pathlib +import subprocess +import sys +import tempfile +import time +import unittest + +spec = importlib.util.spec_from_file_location('ci_load', pathlib.Path(__file__).with_name('ci-load.py')) +load = importlib.util.module_from_spec(spec) +spec.loader.exec_module(load) + + +class LoadTest(unittest.TestCase): + @unittest.skipUnless(sys.platform == 'linux', 'real /proc lifecycle is Linux-only') + def test_cli_samples_and_stops_its_own_process(self): + with tempfile.TemporaryDirectory() as name: + output = pathlib.Path(name)/'load.tsv' + command = [sys.executable, '-I', str(pathlib.Path(__file__).with_name('ci-load.py'))] + try: + subprocess.run(command+['start', str(output), '--duration', '30'], check=True, timeout=10) + deadline = time.monotonic()+10 + while time.monotonic() < deadline: + if output.exists() and len(output.read_text().splitlines()) >= 3: + break + time.sleep(0.05) + finally: + subprocess.run(command+['stop', str(output)], check=True, timeout=5) + lines = output.read_text().splitlines() + self.assertGreaterEqual(len(lines), 3) + self.assertTrue(lines[0].startswith('ts_utc\tload1\tsteal_pct')) + for line in lines[1:]: + fields = line.split('\t') + self.assertEqual(len(fields), 10) + self.assertTrue(fields[0].endswith('+00:00')) + for field in fields[1:]: + json.loads(field) + # The sampler exited: its pid is gone, and no incomplete note. + pid = json.loads(output.with_suffix('.pid.json').read_text())['pid'] + self.assertFalse(pathlib.Path(f'/proc/{pid}').exists() and + pathlib.Path(f'/proc/{pid}/stat').read_text().split(')')[1].split()[0] != 'Z') + self.assertFalse(output.with_suffix('.incomplete').exists()) + + @unittest.skipUnless(sys.platform == 'linux', 'real /proc lifecycle is Linux-only') + def test_stop_records_a_sampler_that_does_not_exit(self): + with tempfile.TemporaryDirectory() as name: + output = pathlib.Path(name)/'load.tsv' + ready = pathlib.Path(name)/'ready' + stubborn = subprocess.Popen([sys.executable, '-c', + 'import pathlib,signal,sys,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); ' + 'pathlib.Path(sys.argv[1]).touch(); time.sleep(30)', str(ready)]) + try: + deadline = time.monotonic()+10 + while not ready.exists(): + self.assertIsNone(stubborn.poll(), 'the stand-in exited before it was ready') + self.assertLess(time.monotonic(), deadline, 'the stand-in never became ready') + time.sleep(0.01) + output.with_suffix('.pid.json').write_text(json.dumps(dict(pid=stubborn.pid, start=load.identity(stubborn.pid)))) + began = time.monotonic() + done = subprocess.run([sys.executable, '-I', str(pathlib.Path(__file__).with_name('ci-load.py')), 'stop', str(output)], + capture_output=True, text=True, timeout=10) + self.assertEqual(done.returncode, 0) + self.assertLess(time.monotonic()-began, 5) + self.assertIn('did not exit', output.with_suffix('.incomplete').read_text()) + self.assertIn('load evidence incomplete', done.stderr) + finally: + stubborn.kill() + stubborn.wait() + + def test_cpu_and_disk_interval_not_since_boot(self): + # CPU: 100 ticks, 10 iowait, 5 stolen. guest ticks are already in user. + before = {'cpu': [100, 0, 20, 800, 20, 0, 0, 10, 3, 0], + 'disks': {'nvme0n1': [10, 30]}} + after = {'cpu': [130, 0, 25, 850, 30, 0, 0, 15, 7, 0], + 'disks': {'nvme0n1': [14, 50], 'new': [1000, 9000]}} + cpu, disks = load.interval(before, after) + self.assertEqual(cpu, {'steal_pct': 5.0, 'iowait_pct': 10.0}) + self.assertEqual(disks, {'nvme0n1': 5.0, 'new': None}) + + def test_reset_or_no_io_is_unknown_not_zero_latency(self): + before = {'cpu': [10]*8, 'disks': {'sda': [10, 100], 'sdb': [20, 200]}} + after = {'cpu': [1]*8, 'disks': {'sda': [10, 100], 'sdb': [1, 3]}} + cpu, disks = load.interval(before, after) + self.assertEqual(cpu, {'steal_pct': None, 'iowait_pct': None}) + self.assertEqual(disks, {'sda': None, 'sdb': None}) + + def test_proc_fields_and_cgroup_ancestor_quota(self): + with tempfile.TemporaryDirectory() as name: + root = pathlib.Path(name) + (root/'pressure').mkdir() + (root/'self').mkdir() + mount = root/'cg' + (mount/'runner/job').mkdir(parents=True) + (mount/'cpu.max').write_text('max 100000\n') + (mount/'runner/cpu.max').write_text('200000 100000\n') + (mount/'runner/job/cpu.max').write_text('max 100000\n') + (root/'self/cgroup').write_text('0::/slice/runner/job\n') + (root/'self/mountinfo').write_text(f'1 0 0:1 /slice {mount.as_posix()} rw - cgroup2 cgroup rw\n') + (root/'loadavg').write_text('3.25 2.00 1.00 1/1 1\n') + (root/'stat').write_text('cpu 100 0 20 800 20 0 0 10 3 0\n') + (root/'diskstats').write_text('259 0 nvme0n1 2 0 0 6 3 0 0 9 0 0 0\n') + for kind in ('cpu', 'io', 'memory'): + (root/'pressure'/kind).write_text('some avg10=1.25 avg60=0.50 avg300=0.20 total=12345\n') + snapshot = load.read_snapshot(root) + self.assertEqual(snapshot['load1'], 3.25) + self.assertEqual(snapshot['disks'], {'nvme0n1': [5, 15]}) + self.assertEqual(snapshot['psi']['cpu']['some']['total'], 12345) + self.assertEqual(snapshot['cpu_max'][str(mount/'runner/cpu.max')], '200000 100000') + self.assertEqual(snapshot['errors'], []) + (mount/'cpu.max').unlink() + snapshot = load.read_snapshot(root) + self.assertEqual(snapshot['cpu_max'][str(mount/'runner/cpu.max')], '200000 100000') + self.assertIsNone(snapshot['cpu_max'][str(mount/'cpu.max')]) + self.assertTrue(snapshot['errors']) + + def test_missing_inputs_explicitly_reported(self): + with tempfile.TemporaryDirectory() as name: + snapshot = load.read_snapshot(pathlib.Path(name)) + self.assertIsNone(snapshot['load1']) + self.assertIsNone(snapshot['cpu']) + self.assertTrue(snapshot['errors']) + self.assertIsNone(snapshot['psi']['cpu']) + self.assertIsNone(snapshot['cpu_max']) + + +if __name__ == '__main__': + unittest.main() diff --git a/seaweed-block/.github/scripts/ci-load.py b/seaweed-block/.github/scripts/ci-load.py new file mode 100644 index 0000000000..c0fcd56407 --- /dev/null +++ b/seaweed-block/.github/scripts/ci-load.py @@ -0,0 +1,176 @@ +"""One-second Linux job-load evidence. Missing counters are null, never zero. + +Disk await is delta(read_ms + write_ms) / delta(completed reads + writes), +per device from diskstats (the r_await/w_await weighted mean, not a sum across +stacked devices). PSI retains the kernel's avg10/60/300 and total microseconds. +cpu.max includes every visible ancestor, since a parent may impose the quota. +The sampler is diagnostic only; it has a job-sized lifetime even if stop is lost. +""" +import argparse +import datetime +import json +import os +import pathlib +import re +import select +import signal +import subprocess +import sys +import threading +import time + + +def read_snapshot(proc=pathlib.Path('/proc')): + errors = [] + + def read(path, parse): + try: + return parse(path.read_text()) + except (OSError, ValueError, IndexError, StopIteration) as error: + errors.append(str(path)+': '+str(error)) + return None + + def pressure(text): + return {parts[0]: {k: (int(v) if k == 'total' else float(v)) + for k, v in (item.split('=') for item in parts[1:])} + for parts in (line.split() for line in text.splitlines()) if parts} + + def diskstats(text): + result = {} + for line in text.splitlines(): + fields = line.split() + # fields after the device name: reads, merges, sectors, ms, + # writes, merges, sectors, ms (present on all supported kernels). + result[fields[2]] = [int(fields[3])+int(fields[7]), int(fields[6])+int(fields[10])] + return result + + def quotas(_): + group = next(line.split('::', 1)[1] for line in (proc/'self/cgroup').read_text().splitlines() + if line.startswith('0::')) + for line in (proc/'self/mountinfo').read_text().splitlines(): + fields, filesystem = line.split(' - ', 1) + if filesystem.split()[0] != 'cgroup2': + continue + # mountinfo escapes whitespace and backslash with octal codes. + unescape = lambda value: re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), value) + fields = fields.split() + base, mount = unescape(fields[3]), pathlib.Path(unescape(fields[4])) + if base != '/' and (group == base or group.startswith(base+'/')): + relative = group[len(base):].lstrip('/') + else: + # cgroup namespace: membership is relative to its visible root. + relative = group.lstrip('/') + current = mount / relative + current.relative_to(mount) + result = {} + while True: + path = current/'cpu.max' + # The real hierarchy root need not expose cpu.max. Preserve + # readable leaf/parent quotas even if another level is absent. + result[str(path)] = read(path, str.strip) + if current == mount: + return result + current = current.parent + raise ValueError('no visible cgroup v2 mount (v1 or unavailable)') + + return dict(load1=read(proc/'loadavg', lambda text: float(text.split()[0])), + cpu=read(proc/'stat', lambda text: [int(v) for v in next( + line for line in text.splitlines() if line.startswith('cpu ')).split()[1:]]), + disks=read(proc/'diskstats', diskstats), + psi={kind: read(proc/'pressure'/filename, pressure) for kind, filename in + [('cpu', 'cpu'), ('io', 'io'), ('mem', 'memory')]}, + cpu_max=read(proc/'self/cgroup', quotas), errors=errors) + + +def interval(before, after): + cpu = dict(steal_pct=None, iowait_pct=None) + old, new = before['cpu'], after['cpu'] + if old is not None and new is not None and len(old) >= 8 and len(new) >= 8: + deltas = [new[i]-old[i] for i in range(8)] # guest already included in user/nice + total = sum(deltas) + if min(deltas) >= 0 and total > 0: + cpu = dict(steal_pct=100*deltas[7]/total, iowait_pct=100*deltas[4]/total) + disks = None + if after['disks'] is not None: + disks = {} + for name, values in after['disks'].items(): + previous = (before['disks'] or {}).get(name) + disks[name] = None + if previous and values[0] > previous[0] and values[1] >= previous[1]: + disks[name] = (values[1]-previous[1])/(values[0]-previous[0]) + return cpu, disks + + +def sample(output, duration): + output.parent.mkdir(parents=True, exist_ok=True) + previous = dict(cpu=None, disks=None) + end, due = time.monotonic()+duration, time.monotonic() + stopped = threading.Event() + signal.signal(signal.SIGTERM, lambda *_: stopped.set()) + with output.open('w', buffering=1) as stream: + stream.write('ts_utc\tload1\tsteal_pct\tiowait_pct\tpsi_cpu\tpsi_io\tpsi_mem\tdisk_await_ms\tcgroup_cpu_max\terrors\n') + while not stopped.is_set() and time.monotonic() < end: + timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='milliseconds') + current = read_snapshot() + cpu, disks = interval(previous, current) + fields = [timestamp, current['load1'], cpu['steal_pct'], cpu['iowait_pct'], + current['psi']['cpu'], current['psi']['io'], current['psi']['mem'], + disks, current['cpu_max'], current['errors']] + stream.write('\t'.join(json.dumps(v, separators=(',', ':')) if not isinstance(v, str) else v + for v in fields)+'\n') + previous = current + due += 1 + stopped.wait(max(0, min(due, end)-time.monotonic())) + # Do not emit a burst of fictitious one-second samples after a stall. + due = max(due, time.monotonic()) + + +def identity(pid): + # comm may contain spaces or parentheses; starttime is field 22. + return pathlib.Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()[19] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=['start', 'sample', 'stop']) + parser.add_argument('output', type=pathlib.Path) + parser.add_argument('--duration', type=int, default=5400) + args = parser.parse_args() + receipt = args.output.with_suffix('.pid.json') + if args.action == 'sample': + sample(args.output, args.duration) + elif args.action == 'start': + args.output.parent.mkdir(parents=True, exist_ok=True) + with args.output.with_suffix('.sampler.log').open('w') as log: + child = subprocess.Popen([sys.executable, '-I', str(pathlib.Path(__file__).resolve()), + 'sample', str(args.output), '--duration', str(args.duration)], + stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True) + receipt.write_text(json.dumps(dict(pid=child.pid, start=identity(child.pid)))) + elif receipt.exists(): + owner = json.loads(receipt.read_text()) + handle = None + try: + # A pidfd makes the identity-check/signal pair safe even if the + # process exits and its numeric PID is recycled between the two. + handle = os.pidfd_open(owner['pid']) + if identity(owner['pid']) == owner['start']: + signal.pidfd_send_signal(handle, signal.SIGTERM) + # Flush the last row before the uploader reads the file. Never + # signal a reused PID and never wait indefinitely for evidence. + # The pidfd turns readable when the sampler exits; one still + # alive after 2 s leaves load.incomplete beside its rows. + if not select.select([handle], [], [], 2)[0]: + note = args.output.with_suffix('.incomplete') + note.write_text('the sampler did not exit within 2 s of SIGTERM; its last rows may be missing\n') + print('load evidence incomplete: '+str(note), file=sys.stderr) + except ProcessLookupError: + pass + except FileNotFoundError: + pass + finally: + if handle is not None: + os.close(handle) + + +if __name__ == '__main__': + main() diff --git a/seaweed-block/.github/scripts/docs-only-scope-test.sh b/seaweed-block/.github/scripts/docs-only-scope-test.sh new file mode 100644 index 0000000000..18079f05c9 --- /dev/null +++ b/seaweed-block/.github/scripts/docs-only-scope-test.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Tests docs-only-scope.sh against real commits, and that test.yml applies it +# only to the process suite of a pull request. Any failure exits nonzero. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +scope="$here/docs-only-scope.sh" +workflow="$here/../workflows/test.yml" +fail=0 +check() { # name want got + if [ "$2" = "$3" ]; then echo "ok $1"; else echo "FAIL $1: want [$2], got [$3]"; fail=1; fi +} +repo=$(mktemp -d) +trap 'rm -rf "$repo"' EXIT +cd "$repo" +git init -q +git config user.email t@example.invalid +git config user.name t +git config core.autocrlf false +mkdir -p docs cmd +echo a >docs/a.md +echo r >README.md +echo g >cmd/main.go +git add -A +git commit -qm base +base=$(git rev-parse HEAD) +case_of() { # name want: commit the current tree, classify against base, reset + git add -A + git commit -qm "$1" --allow-empty + check "$1" "$2" "$(bash "$scope" "$base" HEAD)" + git reset -q --hard "$base" +} +echo b >docs/b.md; echo a2 >docs/a.md +case_of "two docs files" "docs_only 2" +echo b >docs/b.md; echo t >cmd/x_test.go +case_of "docs and a test file" "run 2 cmd/x_test.go" +case_of "no file changed" "run 0" +mkdir -p docs-old; echo x >docs-old/x.md +case_of "a docs-like prefix" "run 1 docs-old/x.md" +echo r2 >README.md +case_of "README outside docs" "run 1 README.md" +git mv docs/a.md cmd/a.md +case_of "a move out of docs" "run 2 cmd/a.md" +git rm -q docs/a.md +case_of "a docs deletion" "docs_only 1" +for i in $(seq 1 20000); do printf 'x\n' >"docs/f$i.md"; done +echo late >zz-late.go +case_of "20000 docs files and one other, listed last" "run 20001 zz-late.go" +if out=$(bash "$scope" "$base" no-such-revision 2>/dev/null); then + check "an unknown revision is an error" "nonzero exit" "exit 0: $out" +else + check "an unknown revision is an error" "nonzero exit" "nonzero exit" +fi +# test.yml: the scope step runs only for a pull request's process suite, and +# every process step it can skip names its output. +step=$(grep -n -A3 'name: Docs-only pull request' "$workflow" | grep "if:" || true) +check "scope step condition" "1" "$(printf '%s' "$step" | grep -c "matrix.suite == 'process' && github.event_name == 'pull_request'" || true)" +check "process steps gated" "5" "$(grep -c "if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'" "$workflow" || true)" +check "no ungated process step" "0" "$(grep -c "if: matrix.suite == 'process'$" "$workflow" || true)" +exit "$fail" diff --git a/seaweed-block/.github/scripts/docs-only-scope.sh b/seaweed-block/.github/scripts/docs-only-scope.sh new file mode 100644 index 0000000000..fc6787279e --- /dev/null +++ b/seaweed-block/.github/scripts/docs-only-scope.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# docs-only-scope.sh BASE HEAD: classifies the files changed between BASE and +# HEAD for the process-level suite. It prints one line: +# "docs_only N" every one of the N changed files is under docs/ +# "run N [FIRST-OTHER]" no file changed, or at least one is elsewhere +# and exits 0. Any error (git fails, the list cannot be read) exits nonzero, +# and the caller then runs the tests: an error never selects docs_only. +# +# The NUL-delimited list is written to a file first and read to its end, so +# no pipe can stop early and leave a writer's error looking like an answer. +set -euo pipefail +[ "$#" -eq 2 ] || { echo "usage: docs-only-scope.sh BASE HEAD" >&2; exit 2; } +list=$(mktemp) +trap 'rm -f "$list"' EXIT +if ! git diff --name-only --no-renames -z "$1" "$2" >"$list"; then + echo "docs-only-scope: git diff $1 $2 failed" >&2 + exit 2 +fi +n=0 +other="" +while IFS= read -r -d '' f; do + n=$((n + 1)) + case $f in + docs/*) ;; + *) [ -n "$other" ] || other=$f ;; + esac +done <"$list" +if [ "$n" -gt 0 ] && [ -z "$other" ]; then + echo "docs_only $n" +else + echo "run $n${other:+ $other}" +fi diff --git a/seaweed-block/.github/scripts/go-test-output.py b/seaweed-block/.github/scripts/go-test-output.py new file mode 100644 index 0000000000..264e316b14 --- /dev/null +++ b/seaweed-block/.github/scripts/go-test-output.py @@ -0,0 +1,58 @@ +"""Drain a Go stream even when recording/rendering fails; never judge tests.""" +import json +import os +import sys + +sys.stdin.reconfigure(encoding='utf-8', errors='replace') + + +def warn(error): + try: + print('test evidence unavailable: '+str(error), file=sys.stderr) + except OSError: + pass + + +archive = None +try: + archive = open(sys.argv[1], 'a', encoding='utf-8', buffering=1) +except OSError as error: + warn(error) +raw = len(sys.argv) > 2 and sys.argv[2] == '--raw' +console = True +for line in sys.stdin: + if archive is not None: + try: + archive.write(line) + except OSError as error: + warn(error) + try: + archive.close() + except OSError: + pass + archive = None + output = line + if not raw: + try: + output = json.loads(line).get('Output', '') + except (ValueError, AttributeError) as error: + # Keep and display unexpected text, but keep draining the producer. + warn(error) + if console: + try: + sys.stdout.write(output) + sys.stdout.flush() + except OSError: + console = False + # Avoid an interpreter-exit BrokenPipe flush; the stream still + # drains Go to EOF so a dead console cannot send SIGPIPE upstream. + try: + with open(os.devnull, 'w') as sink: + os.dup2(sink.fileno(), sys.stdout.fileno()) + except OSError: + pass +if archive is not None: + try: + archive.close() + except OSError as error: + warn(error) diff --git a/seaweed-block/.github/scripts/lab-tag-check-test.sh b/seaweed-block/.github/scripts/lab-tag-check-test.sh new file mode 100644 index 0000000000..e153192057 --- /dev/null +++ b/seaweed-block/.github/scripts/lab-tag-check-test.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +# Controls for lab-tag-check.sh and scripts/refuse-lab-binary.sh. Each case +# builds a small git repository from the real image recipes and publish +# workflow with one contamination, and expects a refusal; the unchanged copy +# passes. The refusal script is driven with stand-in binaries. Exit 0 when +# every control holds. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +src=$(cd "$here/../.." && pwd) +check="$here/lab-tag-check.sh" +refuse="$src/scripts/refuse-lab-binary.sh" +t=$(mktemp -d); trap 'rm -rf -- "${t:?}"' EXIT +tag=swblock_lab_bigvol +sw=deploy/k8s/g15b/Dockerfile.sw-block +csi=deploy/k8s/g15b/Dockerfile.blockcsi +pub=.github/workflows/publish-alpha-images.yml +n=0 +gadd() { git -C "$r" -c core.autocrlf=false -c core.safecrlf=false add -A; } +repo() { # the real recipes and publish workflow, plus one allowed file, in $t/r + n=$((n+1)); r="$t/r$n" + mkdir -p "$r/deploy/k8s/g15b" "$r/.github/workflows" "$r/core/geometry" "$r/core/x" + tr -d '\r' < "$src/$sw" > "$r/$sw" + tr -d '\r' < "$src/$csi" > "$r/$csi" + tr -d '\r' < "$src/$pub" > "$r/$pub" + printf '//go:build %s\npackage geometry\n' "$tag" > "$r/core/geometry/volume_size_lab.go" + printf 'package x\n' > "$r/core/x/x.go" + git -C "$r" init -q && gadd +} +edit() { # edit FILE SED: change one file of the current repository + sed -i "$2" "$r/$1" && gadd +} +expect() { # expect pass|fail name + local want=$1 name=$2 rc=0 + bash "$check" "$r" >/dev/null 2>&1 || rc=$? + if [ "$want" = pass ] && [ $rc -ne 0 ]; then echo "FAIL: $name: refused"; bash "$check" "$r" || true; exit 1; fi + if [ "$want" = fail ] && [ $rc -eq 0 ]; then echo "FAIL: $name: passed"; exit 1; fi +} +repo; expect pass "the real recipes, unchanged" +repo; printf '// %s\npackage x\n' "$tag" > "$r/core/x/x.go"; gadd; expect fail "the tag outside the allowlist" +repo; printf '// swblock_v11_format +package x +' > "$r/core/x/x.go"; gadd; expect fail "the format tag outside the allowlist" +repo; edit "$sw" "s#go build -o /out/blockvolume#go build -tags swblock_v11_format -o /out/blockvolume#"; expect fail "the format tag in a real recipe's build" +repo; edit "$sw" "s#go build -o /out/blockvolume#go build -tags $tag -o /out/blockvolume#"; expect fail "the tag in a real recipe's build" +repo; edit "$sw" '/^RUN bash scripts\/refuse-lab-binary.sh/d'; expect fail "the real recipe's RUN guard deleted, its comment kept" +repo; edit "$csi" '/^RUN bash scripts\/refuse-lab-binary.sh/d'; expect fail "the CSI recipe's RUN guard deleted, its comment kept" +repo; edit "$sw" 's#^RUN bash scripts/refuse-lab-binary.sh#\# RUN bash scripts/refuse-lab-binary.sh#'; expect fail "the RUN guard commented out" +repo; edit "$sw" 's#^\(RUN bash scripts/refuse-lab-binary.sh.*\) /out/sw-block#\1#'; expect fail "a built binary left out of the refusal" +repo; edit "$sw" 's#/out/blockvolume ./cmd/blockvolume#/out/blockvolume ./cmd/blockvolume \&\& \\n CGO_ENABLED=0 go build -o /out/extra ./cmd/extra#'; expect fail "a new binary built and not refused" +repo; guard=$(grep '^RUN bash scripts/refuse-lab-binary.sh' "$r/$sw"); edit "$sw" '/^RUN bash scripts\/refuse-lab-binary.sh/d'; sed -i "s#^RUN CGO_ENABLED=0 go build#$guard\nRUN CGO_ENABLED=0 go build#" "$r/$sw"; gadd; expect fail "the refusal before the build" +repo; printf ' - run: go build ./...\n' >> "$r/$pub"; gadd; expect fail "a go build in the publish workflow" +repo; edit "$pub" "s#file: $csi#file: Dockerfile.root#"; printf 'RUN go build -o /out/b ./cmd/b\n' > "$r/Dockerfile.root"; gadd; expect fail "publishing from a Dockerfile outside deploy/" +repo; rm -f "$r/$pub"; gadd; expect fail "no readable publish workflow" +repo; ln -s missing-target "$r/deploy/k8s/g15b/Dockerfile.dangling" 2>/dev/null || true +if [ -L "$r/deploy/k8s/g15b/Dockerfile.dangling" ]; then gadd; expect fail "an image Dockerfile that cannot be read"; else echo "note: no symlinks here; the unreadable-recipe control runs on Linux"; fi +r="$t/missing"; expect fail "a missing repository" +r="$t/notgit"; mkdir -p "$r"; expect fail "a directory the scan cannot read as a repository" + +b="$t/bin"; mkdir -p "$b" +printf '#!/bin/sh\necho "b revision=1 modified=false"\n' > "$b/release" +printf '#!/bin/sh\necho "b revision=1 modified=false LAB BUILD(%s)"\n' "$tag" > "$b/lab" +printf '#!/bin/sh +echo "b revision=1 modified=false LAB BUILD(swblock_v11_format)" +' > "$b/draft" +printf '#!/bin/sh\nexit 3\n' > "$b/broken" +printf '#!/bin/sh\nexit 0\n' > "$b/silent" +chmod +x "$b"/* +bash "$refuse" "$b/release" >/dev/null || { echo "FAIL: refuse-lab-binary refused a release binary"; exit 1; } +for x in lab draft broken silent; do + if bash "$refuse" "$b/release" "$b/$x" >/dev/null 2>&1; then echo "FAIL: refuse-lab-binary passed a $x binary"; exit 1; fi +done +if bash "$refuse" >/dev/null 2>&1; then echo "FAIL: refuse-lab-binary passed with no binary"; exit 1; fi +echo "lab-tag-check controls: OK ($n repositories, 5 binaries)" diff --git a/seaweed-block/.github/scripts/lab-tag-check.sh b/seaweed-block/.github/scripts/lab-tag-check.sh new file mode 100644 index 0000000000..8c0b76d927 --- /dev/null +++ b/seaweed-block/.github/scripts/lab-tag-check.sh @@ -0,0 +1,90 @@ +#!/usr/bin/env bash +# The lab-only build tags must never reach an image or a release build: +# swblock_lab_bigvol lifts the 256 GiB create cap and the local headroom +# refusal for scale rehearsals; swblock_v11_format turns on the draft v1.1 +# store format. Two checks, both failing closed: +# 1. Allowlist: only the files below may name either tag (git grep over the +# tracked tree; a scan that cannot run is a failure, never "clean"). +# 2. Wiring: every image Dockerfile under deploy/ that runs go build also runs +# scripts/refuse-lab-binary.sh after its last go build, and the publish +# workflow builds images only from such Dockerfiles, with no go build of +# its own. +# Usage: lab-tag-check.sh [REPO_ROOT] Exit 0: clean. Exit 1: a finding or an +# unreadable input (printed). +set -euo pipefail +root=${1:-.} +tags='swblock_lab_bigvol swblock_v11_format' +allowed='.github/scripts/lab-tag-check-test.sh +.github/scripts/lab-tag-check.sh +.github/workflows/test.yml +core/host/volume/status_heap_lab.go +core/host/volume/status_heap_lab_test.go +core/host/volume/status_heap_release.go +core/host/volume/status_heap_release_test.go +core/storage/chunk_v11_format_draft.go +core/storage/chunk_v11_format_release.go +core/storage/chunk_v11_format_tag_test.go +core/frontend/durable/headroom.go +core/frontend/durable/headroom_lab_test.go +core/geometry/volume_size.go +core/geometry/volume_size_lab.go +core/geometry/volume_size_lab_test.go +core/geometry/volume_size_release.go +core/geometry/volume_size_release_test.go +docs/design/invariants.md +docs/lab-heap-profiles.md +internal/buildinfo/buildinfo.go +internal/buildinfo/v11_format_draft.go +internal/buildinfo/v11_format_release.go +scripts/refuse-lab-binary.sh' +fail() { echo "lab-tag: $*" >&2; exit 1; } +[ -d "$root" ] || fail "no repository at $root" +for tag in $tags; do + set +e + hits=$(git -C "$root" grep -l -- "$tag") + rc=$? + set -e + case $rc in + 0) ;; + 1) hits="" ;; + *) fail "git grep failed (rc=$rc): the scan did not run" ;; + esac + bad="" + while IFS= read -r f; do + [ -n "$f" ] || continue + printf '%s\n' "$allowed" | grep -qxF -- "$f" || bad="$bad $f" + done <<< "$hits" + [ -z "$bad" ] || fail "$tag named outside the allowlist:$bad" +done + +# read FILE: its whole content, once; a read that fails is a failure, never +# "no match". +read_file() { local c; c=$(cat -- "$root/$1") || fail "cannot read $1"; printf '%s\n' "$c"; } +dockerfiles=$(cd "$root" && find deploy \( -type f -o -type l \) -name 'Dockerfile*' | sort) || fail "cannot list deploy/" +[ -n "$dockerfiles" ] || fail "no image Dockerfile under deploy/" +for d in $dockerfiles; do + body=$(read_file "$d") || exit 1 + # The binaries it builds (go build ... -o /out/NAME), and the line of its + # last build. A recipe that builds nothing needs no refusal. + built=$(printf '%s\n' "$body" | grep -oE 'go build[^&\]*-o /out/[A-Za-z0-9_.-]+' | grep -oE '/out/[A-Za-z0-9_.-]+$' | sort -u) || true + [ -n "$built" ] || continue + last=$(printf '%s\n' "$body" | grep -nE 'go build' | tail -1 | cut -d: -f1) + # The refusal must be an executed RUN line (not a comment) after the last + # build, naming every binary the recipe builds. + refuse=$(printf '%s\n' "$body" | grep -nE '^RUN bash scripts/refuse-lab-binary\.sh( |$)' | tail -1) || fail "$d builds ${built//$'\n'/ } without a RUN of scripts/refuse-lab-binary.sh" + at=${refuse%%:*} + [ "$at" -gt "$last" ] || fail "$d runs the refusal before its last build" + for b in $built; do + case " ${refuse#*:} " in *" $b "*) ;; *) fail "$d does not refuse $b, which it builds" ;; esac + done +done +pub=.github/workflows/publish-alpha-images.yml +pubbody=$(read_file "$pub") || exit 1 +case "$pubbody" in *"go build"*) fail "the publish workflow runs its own go build" ;; esac +files=$(printf '%s\n' "$pubbody" | grep -E '^[[:space:]]*file:' | sed -E 's/^[[:space:]]*file:[[:space:]]*//') || fail "the publish workflow names no Dockerfile" +for f in $files; do + printf '%s\n' "$dockerfiles" | grep -qxF -- "$f" || fail "the publish workflow builds from $f, not an image Dockerfile under deploy/" + fbody=$(read_file "$f") || exit 1 + printf '%s\n' "$fbody" | grep -qE '^RUN bash scripts/refuse-lab-binary\.sh ' || fail "the publish workflow builds from $f, which does not run the refusal" +done +echo "lab-tag: clean" diff --git a/seaweed-block/.github/scripts/ledger_check.py b/seaweed-block/.github/scripts/ledger_check.py new file mode 100644 index 0000000000..afb31ae2e1 --- /dev/null +++ b/seaweed-block/.github/scripts/ledger_check.py @@ -0,0 +1,120 @@ +"""Check that every code and test anchor of the invariants ledger exists at a git ref. + +usage: python -I ledger_check.py [] + +A ledger row is a table line whose first cell holds `INV-...`. In its cells, a +backticked token that ends in .go is a FILE; a backticked identifier (or +Type.Method) is a SYMBOL of the nearest file named before it in the same cell, +or, in the test cell, of any file named in that cell. A file must exist at the +ref; a symbol must occur in its file as a whole word (for a test: `func Name(`). +A symbol with no file in its cell is looked up in the whole tree. A file may +be a glob (`volume_lock*.go`). A lower-case token with an underscore (a build +tag, a JSON key, a reason string) is not a Go symbol and is not checked. +Prints one line per missing anchor and a summary. It reads; it changes nothing. +Exit: 0 when every anchor exists; 1 when one is missing; 2 when git fails or no +row or anchor was found (an error is never read as a pass). +""" +import re +import subprocess +import sys + + +def git(repo, *args): + """git's output. A git failure ends the check with exit 2: an error must + never read as "no anchors". `git grep` finding nothing (exit 1) is not one.""" + r = subprocess.run(["git", "-C", repo] + list(args), capture_output=True, text=True, + encoding="utf-8", errors="replace") + if r.returncode != 0 and not (args and args[0] == "grep" and r.returncode == 1): + print("ledger_check: git %s failed (exit %d): %s" % (" ".join(args[:2]), r.returncode, r.stderr.strip()[:300]), + file=sys.stderr) + sys.exit(2) + return r.stdout + + +def main(): + repo, ref = sys.argv[1], sys.argv[2] + ledger = sys.argv[3] if len(sys.argv) > 3 else "docs/design/invariants.md" + text = git(repo, "show", "%s:%s" % (ref, ledger)) + files = set(git(repo, "ls-tree", "-r", "--name-only", ref).split("\n")) + cache = {} + + def body(path): + if path not in cache: + cache[path] = git(repo, "show", "%s:%s" % (ref, path)) + return cache[path] + + def resolve(tok): + """A file token may be a full path or a bare file name.""" + if tok in files: + return [tok] + if "*" in tok: + rx = re.compile("^(.*/)?" + "[^/]*".join(re.escape(x) for x in tok.split("*")) + "$") + return [f for f in files if rx.match(f)] + if "/" not in tok: + return [f for f in files if f.endswith("/" + tok)] + # a path with a directory matches whole path components only + return [f for f in files if f.endswith("/" + tok)] + + ident = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?(\(\))?$") + go_all = None + rows = missing = anchors = 0 + for n, line in enumerate(text.split("\n"), 1): + if not line.startswith("|"): + continue + cells = [c.strip() for c in line.strip().strip("|").split("|")] + m = re.match(r"`(INV-[A-Z0-9-]+)`", cells[0]) if cells else None + if not m or len(cells) < 6: + continue + rows += 1 + inv, status = m.group(1), cells[-1] + if "ARCHIVED" in status: + continue + for ci, kind in ((3, "code"), (4, "test")): + toks = re.findall(r"`([^`]+)`", cells[ci]) + cell_files = [] + for t in toks: + if t.endswith(".go"): + cell_files.append(t) + cur = None + for t in toks: + if t.endswith(".go"): + cur = t + anchors += 1 + if not resolve(t): + missing += 1 + print("%s (line %d, %s, %s): file %s does not exist" % (inv, n, kind, status, t)) + continue + if not ident.match(t): + continue + sym = t.rstrip("()").split(".")[-1] + if sym in ("nil", "true", "false") or sym.isupper() or len(sym) < 3: + continue + if "_" in sym and sym == sym.lower(): + # a build tag, a JSON key or a reason string: not a Go symbol + continue + scope = [cur] if (cur and kind == "code") else cell_files + paths = [p for f in scope for p in resolve(f)] + anchors += 1 + if kind == "test" and sym.startswith(("Test", "Fuzz", "Benchmark")): + pat = re.compile(r"func %s\(" % re.escape(sym)) + else: + pat = re.compile(r"\b%s\b" % re.escape(sym)) + if paths: + ok = any(pat.search(body(p)) for p in paths) + else: + if go_all is None: + go_all = git(repo, "grep", "-h", "-E", r"^(func|type|var|const|\s+[A-Za-z_]+\s)", ref, "--", "*.go") + ok = bool(pat.search(go_all)) + if not ok: + missing += 1 + where = ", ".join(scope) if scope else "the tree" + print("%s (line %d, %s, %s): %s not found in %s" % (inv, n, kind, status, t, where)) + print("%d rows, %d anchors, %d missing at %s" % (rows, anchors, missing, ref)) + if rows == 0 or anchors == 0: + print("ledger_check: no ledger rows or anchors found: refusing to pass", file=sys.stderr) + sys.exit(2) + sys.exit(1 if missing else 0) + + +if __name__ == "__main__": + main() diff --git a/seaweed-block/.github/scripts/model-trace-check-test.py b/seaweed-block/.github/scripts/model-trace-check-test.py new file mode 100644 index 0000000000..cb6d35f58f --- /dev/null +++ b/seaweed-block/.github/scripts/model-trace-check-test.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +import importlib.util +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +SCRIPT = Path(__file__).with_name("model-trace-check.py") +spec = importlib.util.spec_from_file_location("model_trace", SCRIPT) +checker = importlib.util.module_from_spec(spec) +spec.loader.exec_module(checker) + + +class ModelTraceTests(unittest.TestCase): + mapping = {"core/a.go": {"EngineAdapter.Begin", "EngineAdapter.NoOpCut"}, "core/b.go": {"MoveAdmission.Revoke"}} + + def test_each_mapped_file_needs_its_own_citation(self): + problems = checker.check("EngineAdapter.Begin", ["core/a.go", "core/b.go"], self.mapping) + self.assertEqual(len(problems), 1) + self.assertIn("core/b.go", problems[0]) + self.assertEqual(checker.check("EngineAdapter.Begin; MoveAdmission.Revoke", list(self.mapping), self.mapping), []) + + def test_mapped_file_refuses_free_text_wrong_actions_and_lookalikes(self): + for model in ("exhausted", "EngineAdapter.Unknown", "Other.Begin", "EngineAdapter.BeginExtra", + "docs/EngineAdapter.Begin", "example: EngineAdapter.Begin", "NONE: no state changes", + "NONE (pure function of Other)", "NONE (pure function of EngineAdapter) extra"): + with self.subTest(model=model): + self.assertEqual(len(checker.check(model, ["core/a.go"], self.mapping)), 1) + + def test_pure_function_exception_is_module_specific(self): + self.assertEqual(checker.check("NONE (pure function of EngineAdapter)", ["core/a.go"], self.mapping), []) + self.assertEqual(len(checker.check("NONE (pure function of EngineAdapter)", ["core/b.go"], self.mapping)), 1) + + def test_unmapped_files_keep_existing_policy(self): + self.assertEqual(checker.check("existing prose", ["docs/a.md", "core/a.go.bak"], self.mapping), []) + + def test_repository_map_covers_claimed_head_create(self): + mapping = checker.read_mapping(SCRIPT.parent.parent / "model-code-trace.tsv") + paths = ["core/frontend/chunkstore/layout/create.go"] + self.assertEqual(checker.check("VolumeCreate.Claim", paths, mapping), []) + self.assertEqual(len(checker.check("VolumeCreate.Unknown", paths, mapping)), 1) + + def test_repository_map_covers_the_replica_receiver(self): + mapping = checker.read_mapping(SCRIPT.parent.parent / "model-code-trace.tsv") + paths = ["core/transport/replica.go"] + self.assertEqual(checker.check("ReplicationPeer.Ship", paths, mapping), []) + self.assertEqual(len(checker.check("VolumeCreate.Claim", paths, mapping)), 1) + + def test_cli_checks_nul_paths_and_model_citations(self): + with tempfile.TemporaryDirectory() as tmp: + mapping = Path(tmp) / "map.tsv" + mapping.write_text("# exact paths\ncore/a.go\tEngineAdapter.Begin\n", encoding="utf-8") + def run(model, paths): + return subprocess.run([sys.executable, str(SCRIPT), str(mapping), model], + input=paths, capture_output=True).returncode + self.assertEqual(run("EngineAdapter.Begin", b"core/a.go\0"), 0) + self.assertEqual(run("unstructured prose", b"core/a.go\0"), 1) + self.assertEqual(run("EngineAdapter.Begin", b"core/a.go"), 2) + self.assertEqual(run("EngineAdapter.Begin", b"\0"), 2) + + def test_mapping_refuses_missing_empty_and_malformed_data(self): + with tempfile.TemporaryDirectory() as tmp: + mapping = Path(tmp) / "map.tsv" + with self.assertRaises(OSError): + checker.read_mapping(mapping) + for content in ("# not populated\n", "core/a.go EngineAdapter.Begin\n", + "../core/a.go\tEngineAdapter.Begin\n", "core//a.go\tEngineAdapter.Begin\n", + "core/a.go\tKernel\n", "core/a.go\tEngineAdapter.Begin extra\n"): + with self.subTest(content=content): + mapping.write_text(content, encoding="utf-8") + with self.assertRaises(ValueError): + checker.read_mapping(mapping) + + +if __name__ == "__main__": + unittest.main() diff --git a/seaweed-block/.github/scripts/model-trace-check.py b/seaweed-block/.github/scripts/model-trace-check.py new file mode 100644 index 0000000000..cec3ecc1a4 --- /dev/null +++ b/seaweed-block/.github/scripts/model-trace-check.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Check Model citations against a base-owned, exact-path TSV mapping.""" +import re +import sys +from pathlib import Path, PurePosixPath + +IDENT = r"[A-Za-z_][A-Za-z0-9_]*" +ACTION = re.compile(rf"{IDENT}\.{IDENT}") +PURE = re.compile(rf"NONE \(pure function of ({IDENT})\)") + + +def read_mapping(path): + mapping = {} + for number, line in enumerate(Path(path).read_text(encoding="utf-8").splitlines(), 1): + if not line.strip() or line.startswith("#"): + continue + columns = line.split("\t") + if len(columns) != 2: + raise ValueError(f"mapping line {number}: expected PATHModule.Action") + file, action = columns + parts = PurePosixPath(file).parts + if (not file or file.startswith("/") or "\\" in file or ":" in file + or any(part in (".", "..") for part in file.split("/")) + or str(PurePosixPath(file)) != file or not parts): + raise ValueError(f"mapping line {number}: expected a repository-relative exact path") + if not ACTION.fullmatch(action): + raise ValueError(f"mapping line {number}: invalid Module.Action") + mapping.setdefault(file, set()).add(action) + if not mapping: + raise ValueError("model mapping is empty; populate it before enabling this gate") + return mapping + + +def check(model, paths, mapping): + # A list permits one citation for each mapped file in a multi-module PR. + # Full matches prevent prose, quoted examples, or a prefixed NONE excuse + # from accidentally satisfying a mapped-file obligation. + citations = {part.strip() for part in model.split(";")} + actions = {part for part in citations if ACTION.fullmatch(part)} + pure = {match.group(1) for part in citations if (match := PURE.fullmatch(part))} + problems = [] + for file in sorted(set(paths)): + expected = mapping.get(file) + if expected and not (actions & expected or any(a.split(".")[0] in pure for a in expected)): + names = "; ".join(sorted(expected)) + problems.append(f"{file}: Model must cite {names} or NONE (pure function of its module)") + return problems + + +def main(): + if len(sys.argv) != 3: + print("usage: model-trace-check.py MAPPING MODEL < nul-separated-paths", file=sys.stderr) + return 2 + try: + mapping = read_mapping(sys.argv[1]) + raw = sys.stdin.buffer.read() + if raw and not raw.endswith(b"\0"): + raise ValueError("unterminated changed path") + paths = [p.decode("utf-8") for p in raw.split(b"\0")[:-1]] + if any(not p for p in paths): + raise ValueError("empty changed path") + problems = check(sys.argv[2], paths, mapping) + except (OSError, UnicodeError, ValueError) as error: + print(f"spec-trace: {error}", file=sys.stderr) + return 2 + for problem in problems: + print(f"spec-trace: {problem}") + return int(bool(problems)) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/seaweed-block/.github/scripts/post-merge-review-changed.sh b/seaweed-block/.github/scripts/post-merge-review-changed.sh new file mode 100644 index 0000000000..1e23f0d63b --- /dev/null +++ b/seaweed-block/.github/scripts/post-merge-review-changed.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Usage: post-merge-review-changed.sh BASE HEAD +# +# Writes what a PR changes (BASE...HEAD) as NUL-separated STATUS, PATH pairs, +# unquoted, so any byte in a name reaches the check as itself. --no-renames +# reports a move as a delete of the old name and an add of the new one. +set -euo pipefail +base=${1:?usage: post-merge-review-changed.sh BASE HEAD} +head=${2:?usage: post-merge-review-changed.sh BASE HEAD} +exec git diff -z --name-status --no-renames "$base...$head" diff --git a/seaweed-block/.github/scripts/post-merge-review-check-test.sh b/seaweed-block/.github/scripts/post-merge-review-check-test.sh new file mode 100644 index 0000000000..04e52b6287 --- /dev/null +++ b/seaweed-block/.github/scripts/post-merge-review-check-test.sh @@ -0,0 +1,197 @@ +#!/usr/bin/env bash +# Self-test of the post-merge-review check: the matcher against the checked-in +# allow list, the real Git diff it consumes, and the workflow's triggers. +set -euo pipefail +shopt -s inherit_errexit +here=$(cd "$(dirname "$0")" && pwd) +check=$here/post-merge-review-check.sh +changed=$here/post-merge-review-changed.sh +allow=$here/../post-merge-review-allow.txt +workflow=$here/../workflows/post-merge-review.yml +fail=0 + +expect_changes() { # expect_changes WANT_EXIT NAME [STATUS PATH]... + local want=$1 name=$2 + shift 2 + local got=0 + if (($#)); then printf '%s\0' "$@"; fi | bash "$check" "$allow" >/dev/null || got=$? + if [[ $got != "$want" ]]; then + echo "FAIL $name: exit $got, want $want" + fail=1 + fi +} +expect() { # expect WANT_EXIT NAME PATH... : each path modified + local want=$1 name=$2 p + shift 2 + local args=() + for p in "$@"; do args+=(M "$p"); done + expect_changes "$want" "$name" ${args[@]+"${args[@]}"} +} + +# Allowed. +expect 0 "docs" docs/README.md README.md cmd/sw-block/NOTES.md +expect 0 "testops docs" internal/testops/registry-overview.md +expect 0 "test outside denied dirs" core/ops/cleanup_projection_test.go cmd/blockmaster/topology_test.go +expect 0 "named status files" core/host/master/observation_service.go core/host/volume/memory_status.go +expect 0 "release is not lease" cmd/sw-block/release_test.go +expect 0 "names with a space, tab or newline" "docs/a b.md" $'docs/a\tb.md' $'docs/a\nb.md' +expect 0 "no paths" +expect_changes 0 "test added" A cmd/foo/new_test.go +expect_changes 0 "doc deleted" D docs/old.md + +# Denied by default: not on the allow list. +expect 1 "new file anywhere" core/newpkg/decide.go +expect 1 "decision code by name" core/host/master/product_loop.go core/lifecycle/planner.go +expect 1 "go.mod" go.mod +expect 1 "go.sum" go.sum +expect 1 "status-like but not named" core/ops/operator_status_controller.go +expect 1 "status server: registers a mutating endpoint" core/host/volume/status_server.go + +# Denied explicitly, even where an allow line matches. +expect 1 "storage" core/storage/walstore.go +expect 1 "unicode name in storage" $'core/storage/\xc3\xa9_test.go' +expect 1 "durable test file" core/frontend/durable/provider_chunk_detach_abort_test.go +expect 1 "doc inside a denied dir" core/storage/NOTES.md +expect 1 "authority test" core/authority/lease_stats_test.go +expect 1 "master workspace test" core/host/master/workspace_binding_review_test.go +expect 1 "volume workspace runtime" core/host/volume/workspace_runtime.go +expect 1 "volume workspace runtime test" core/host/volume/workspace_runtime_test.go +expect 1 "proto" core/rpc/proto/control.proto +expect 1 "lease test by name" cmd/foo/lease_table_test.go +expect 1 "gc test by name" cmd/sw-block/chunk_gc_test.go +expect 1 "the check itself" .github/post-merge-review-allow.txt +expect 1 "a workflow" .github/workflows/test.yml +expect 1 "PR template under .github" .github/pull_request_template.md +expect 1 "mixed: allowed plus denied" docs/README.md core/storage/walstore.go +expect 1 "mixed: allowed plus unlisted" docs/README.md go.mod + +# Persisted-format, GC and delete paths stay denied, tests included. +expect 1 "lifecycle store test" core/lifecycle/store_test.go +expect 1 "journal isolation test" core/host/master/journal_isolation_test.go +expect 1 "sparrow persist test" cmd/sparrow/persist_sidecar_test.go +expect 1 "chunk volume delete test" cmd/sw-block/chunk_volume_delete_test.go +expect 1 "deletion reservations test" core/lifecycle/deletion_reservations_test.go +expect 1 "delete safety contract test" core/ops/delete_safety_contract_test.go +expect 1 "gc doc" docs/spec/cfg/RED_gc_ageonly.cfg + +# The test gates: engine, CLI and gate definitions (and their tests). +expect 1 "testops engine" internal/testops/control.go +expect 1 "testops engine test" internal/testops/control_test.go +expect 1 "testops gate definition" internal/testops/registry/iscsi-p2-os-smoke.json +expect 1 "testops CLI" cmd/sw-testops/main.go + +# A test may be added or modified, never deleted or replaced. +expect_changes 1 "test deleted" D cmd/foo/guard_test.go +expect_changes 1 "test type changed" T cmd/foo/guard_test.go +expect_changes 1 "test moved (delete plus add)" D cmd/foo/guard_test.go A cmd/foo/renamed_test.go + +# A malformed change list or a missing or empty allow list fails closed. +malformed() { # malformed NAME PRINTF-FORMAT + local got=0 + printf "$2" | bash "$check" "$allow" >/dev/null 2>&1 || got=$? + [[ $got == 2 ]] || { echo "FAIL malformed list, $1: exit $got, want 2"; fail=1; } +} +malformed "status without a path" 'M\0' +malformed "bare unterminated status" 'M' +malformed "trailing partial status after a valid pair" 'M\0docs/x.md\0D' +malformed "unterminated path" 'M\0docs/x.md' +malformed "unknown status" 'BOGUS\0docs/x.md\0' +malformed "rename status (renames are off)" 'R100\0docs/x.md\0' +malformed "empty status" '\0docs/x.md\0' +malformed "empty path" 'M\0\0' +empty=$(mktemp) +for bad in "$empty" "/nonexistent/post-merge-review-allow.txt"; do + got=0 + printf 'M\0docs/README.md\0' | bash "$check" "$bad" >/dev/null 2>&1 || got=$? + [[ $got == 2 ]] || { echo "FAIL allow list $bad: exit $got, want 2"; fail=1; } +done +rm -f "$empty" + +# A list whose last line has no newline keeps that line (here a denial). +unterminated=$(mktemp) +printf '*_test.go\n!core/workspace/*' >"$unterminated" +got=0 +printf 'M\0core/workspace/orch_test.go\0' | bash "$check" "$unterminated" >/dev/null 2>&1 || got=$? +[[ $got == 1 ]] || { echo "FAIL allow list with an unterminated last line: exit $got, want 1"; fail=1; } +got=0 +printf 'M\0cmd/foo/a_test.go\0' | bash "$check" "$unterminated" >/dev/null 2>&1 || got=$? +[[ $got == 0 ]] || { echo "FAIL allow list with an unterminated last line, allowed path: exit $got, want 0"; fail=1; } +rm -f "$unterminated" + +# Real Git: names that git quotes in its default output, a rename out of a +# denied directory, a retarget onto a base that differs, and test deletes. +repo=$(mktemp -d) +trap 'rm -rf "$repo" "${changes:-}"' EXIT +g() { git -C "$repo" -c user.name=t -c user.email=t@t -c core.quotePath=true -c core.protectNTFS=false "$@"; } +blob= +commit() { # commit PARENT PATH... : PARENT's tree plus PATHs (-PATH removes) + local parent=$1 + shift + g read-tree "$parent" + local p + for p in "$@"; do + if [[ $p == -* ]]; then + g update-index --force-remove -- "${p#-}" + else + g update-index --add --cacheinfo "100644,$blob,$p" + fi + done + g commit-tree "$(g write-tree)" -p "$parent" -m c +} +changes=$(mktemp) +expect_diff() { # expect_diff WANT_EXIT NAME BASE HEAD + local got=0 + if ! (cd "$repo" && bash "$changed" "$3" "$4") >"$changes"; then + echo "FAIL $2: listing the changes failed" + fail=1 + return + fi + bash "$check" "$allow" <"$changes" >/dev/null || got=$? + if [[ $got != "$1" ]]; then + echo "FAIL $2: exit $got, want $1" + fail=1 + fi +} +g init -q +blob=$(printf x | g hash-object -w --stdin) +g read-tree --empty +root=$(g commit-tree "$(g write-tree)" -m root) +main=$(commit "$root" core/storage/old.go docs/x.md cmd/foo/guard_test.go) +unicode=$(commit "$main" $'core/storage/\xc3\xa9_test.go') +oddnames=$(commit "$main" $'docs/tab\there.md' $'docs/new\nline.md' $'docs/\xc3\xa9.md') +moved=$(commit "$main" -core/storage/old.go docs/moved.md) +parent=$(commit "$main" core/storage/parent.go) +stacked=$(commit "$parent" docs/child.md) +later=$(commit "$main" core/storage/later.go) +testadd=$(commit "$main" cmd/foo/extra_test.go) +testdel=$(commit "$main" -cmd/foo/guard_test.go) +testmove=$(commit "$main" -cmd/foo/guard_test.go cmd/foo/renamed_test.go) +n=$( (cd "$repo" && bash "$changed" "$main" "$oddnames") | tr -cd '\000' | wc -c | tr -d ' ') +[[ $n == 6 ]] || { echo "FAIL fixture: $n NULs for 3 odd names, want 6"; fail=1; } +if ! (cd "$repo" && git diff --name-only "$main...$unicode") | grep -q '^"'; then + echo "FAIL fixture: expected git to quote the unicode name in its default output" + fail=1 +fi +expect_diff 1 "git: unicode test file in storage" "$main" "$unicode" +expect_diff 0 "git: tab, newline and unicode names in docs" "$main" "$oddnames" +expect_diff 1 "git: moved out of storage into docs" "$main" "$moved" +expect_diff 0 "git: stacked PR against its parent" "$parent" "$stacked" +expect_diff 1 "git: the same PR retargeted to main" "$main" "$stacked" +expect_diff 0 "git: the base moved on with denied changes; the PR did not" "$later" "$oddnames" +expect_diff 0 "git: a test added" "$main" "$testadd" +expect_diff 1 "git: a test deleted" "$main" "$testdel" +expect_diff 1 "git: a test moved" "$main" "$testmove" +if (cd "$repo" && bash "$changed" 0000000000000000000000000000000000000001 "$main") >/dev/null 2>&1; then + echo "FAIL git: listing against an unknown base succeeded" + fail=1 +fi + +# The workflow reruns on every change that can change the verdict, including +# a retarget (edited). +types=$(sed -n 's/^ *types: *\[\(.*\)\].*/\1/p' "$workflow" | tr -d ' ') +for want in opened synchronize reopened labeled unlabeled edited; do + [[ ",$types," == *",$want,"* ]] || { echo "FAIL workflow does not run on $want"; fail=1; } +done + +if ((fail)); then exit 1; fi +echo "post-merge-review check: self-test ok" diff --git a/seaweed-block/.github/scripts/post-merge-review-check.sh b/seaweed-block/.github/scripts/post-merge-review-check.sh new file mode 100644 index 0000000000..918ee3f4bf --- /dev/null +++ b/seaweed-block/.github/scripts/post-merge-review-check.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Usage: post-merge-review-check.sh ALLOW_FILE < changes +# +# changes are NUL-separated STATUS, PATH pairs (post-merge-review-changed.sh). +# A path passes only if it matches an allow pattern and no "!" pattern, and +# a test file may be added or modified but not deleted (a move deletes its +# old name). Prints every change that does not pass and exits 1 if there is +# one; exits 0 if all pass, 2 on a usage error, a malformed change or a +# missing or empty allow list. +set -euo pipefail + +allow_file=${1:?usage: post-merge-review-check.sh ALLOW_FILE < changes} +if [[ ! -f $allow_file ]]; then + echo "post-merge-review: allow list $allow_file missing" >&2 + exit 2 +fi +allow=() +deny=() +# A last line without a newline is read too: dropping it could drop a "!". +while IFS= read -r line || [[ -n $line ]]; do + line=${line%%#*} + line=${line%"${line##*[![:space:]]}"} + line=${line#"${line%%[![:space:]]*}"} + [[ -n $line ]] || continue + if [[ $line == '!'* ]]; then + deny+=("${line#!}") + else + allow+=("$line") + fi +done <"$allow_file" +if ((${#allow[@]} == 0)); then + echo "post-merge-review: empty allow list $allow_file" >&2 + exit 2 +fi + +denied=0 +checked=0 +malformed() { + echo "post-merge-review: malformed change list: $1" >&2 + exit 2 +} +while :; do + # Every field ends in NUL: a field cut off at the end is malformed, not + # skipped, and only the statuses git diff --no-renames writes are known. + if ! IFS= read -r -d '' status; then + [[ -z $status ]] || malformed "unterminated status ${status@Q}" + break + fi + [[ $status == [ADMT] ]] || malformed "unknown status ${status@Q}" + IFS= read -r -d '' path || malformed "status $status without a terminated path" + [[ -n $path ]] || malformed "status $status with an empty path" + checked=$((checked + 1)) + why="not on the allow list" + for p in "${allow[@]}"; do + # Unquoted on the right: a glob, where * also matches /. + if [[ $path == $p ]]; then + why="" + break + fi + done + for p in ${deny[@]+"${deny[@]}"}; do + if [[ $path == $p ]]; then + why="matches !$p" + break + fi + done + # A labelled PR may not delete a test (or turn it into something else). + if [[ -z $why && $path == *_test.go && $status != [AM] ]]; then + why="test file status $status: only adding or modifying a test is allowed" + fi + if [[ -n $why ]]; then + printf 'DENY %s %q (%s)\n' "$status" "$path" "$why" + denied=1 + fi +done +echo "post-merge-review: $checked changed path(s) checked against ${#allow[@]} allow and ${#deny[@]} deny pattern(s)" +exit "$denied" diff --git a/seaweed-block/.github/scripts/public-text-check-test.sh b/seaweed-block/.github/scripts/public-text-check-test.sh new file mode 100755 index 0000000000..a59dc7e096 --- /dev/null +++ b/seaweed-block/.github/scripts/public-text-check-test.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Self-test of public-text-check.sh in a throwaway repository. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +t=$(mktemp -d); trap 'rm -rf "$t"' EXIT +cd "$t"; git init -q .; git config user.email t@example.invalid; git config user.name t +echo base > a.txt; git add a.txt; git commit -q -m "base" +mb=$(git rev-parse HEAD) +: > title; : > body +run() { bash "$here/public-text-check.sh" "$@" >out 2>&1; } +expect() { # expect RC NAME + local want=$1 name=$2 rc=0 + shift 2 + run "$@" || rc=$? + [ "$rc" = "$want" ] || { echo "public-text-check-test: $name: exit $rc, want $want"; cat out; exit 1; } +} +echo "plain line" >> a.txt; git commit -q -am "add a plain line" +expect 0 "clean change" "$mb" HEAD title body +seat="clau""de06"; path="V:/sha""re/x"; nas="share/rd""ma/y" +echo "// asked by $seat" >> a.txt; git commit -q -am "comment" +expect 1 "seat name in an added line" "$mb" HEAD title body +grep -q "a.txt:3" out || { echo "public-text-check-test: hit does not name file and line"; cat out; exit 1; } +git reset -q --hard HEAD~1 +echo "ok" >> a.txt; git commit -q -am "review by $seat" +expect 1 "seat name in a commit subject" "$mb" HEAD title body +git reset -q --hard HEAD~1 +echo "see $path" > title; expect 1 "share path in the title" "$mb" HEAD title body; : > title +echo "results under $nas" > body; expect 1 "share path in the description" "$mb" HEAD title body; : > body +echo "an old line with $seat" >> a.txt; git commit -q -am "old"; mb2=$(git rev-parse HEAD) +echo "new clean line" >> a.txt; git commit -q -am "new" +expect 0 "an existing line is not this change's" "$mb2" HEAD title body +# A file line that begins with "++ " shows in the diff as "+++ ...": an added line, not a header. +printf '%s +' "++ $seat" >> a.txt; git commit -q -am "plus line" +expect 1 "an added line that looks like a diff header" "$mb2" HEAD title body +git reset -q --hard HEAD~1 +bs=$(printf '\') +printf '%s +' "${bs}${bs}nas${bs}sha""re${bs}rd""ma${bs}z" > title +expect 1 "backslash form of the share path in the title" "$mb2" HEAD title body; : > title +expect 2 "a missing title file is an error, not clean" "$mb2" HEAD no-such-title body +expect 2 "a missing description file is an error, not clean" "$mb2" HEAD title no-such-body +expect 2 "an unknown commit is an error, not clean" 0000000000000000000000000000000000000000 HEAD title body +# A grep that fails (exit 2) is an error: the check must refuse and never print "clean". +mkdir -p fakebin; printf '#!/bin/sh +exit 2 +' > fakebin/grep; chmod +x fakebin/grep +rc=0; PATH="$PWD/fakebin:$PATH" bash "$here/public-text-check.sh" "$mb2" HEAD title body >out 2>&1 || rc=$? +[ "$rc" = 2 ] || { echo "public-text-check-test: failing grep: exit $rc, want 2"; cat out; exit 1; } +if PATH=/usr/bin:/bin grep -q "clean" out; then echo "public-text-check-test: failing grep printed clean"; cat out; exit 1; fi +echo "public-text-check-test: ok" diff --git a/seaweed-block/.github/scripts/public-text-check.sh b/seaweed-block/.github/scripts/public-text-check.sh new file mode 100755 index 0000000000..3146d095c5 --- /dev/null +++ b/seaweed-block/.github/scripts/public-text-check.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Refuses internal names in what a pull request makes public: the lines it +# adds, its commit messages, its title and its description. This repository is +# public; internal seat names and internal file-share paths do not belong in it. +# +# Usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE +# Exit 0: clean. Exit 1: at least one hit (each printed). Exit 2: usage. +# +# The patterns live only here and in this check's own test; both files are +# excluded from the scan of added lines. +set -euo pipefail +[ "$#" -eq 4 ] || { echo "usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE" >&2; exit 2; } +mb=$1; head=$2; title=$3; body=$4 +for f in "$title" "$body"; do + [ -f "$f" ] && [ -r "$f" ] || { echo "public-text: cannot read $f" >&2; exit 2; } +done +git rev-parse -q --verify "$mb^{commit}" >/dev/null && git rev-parse -q --verify "$head^{commit}" >/dev/null || + { echo "public-text: unknown commit $mb or $head" >&2; exit 2; } +# match: a grep error fails the check instead of reading as "no hit". +match() { local rc=0; grep -E -i -- "$pat" "$@" || rc=$?; [ "$rc" -le 1 ] || { echo "public-text: grep failed ($rc)" >&2; exit 2; }; } +pat='(claude|codex)0[0-9]|share[/\]rdma|V:[/\]share|diskstation' +out=$(mktemp); trap 'rm -f "$out"' EXIT +report() { # report WHERE < matching lines + local where=$1 line + while IFS= read -r line; do + printf 'public-text: %s: %s +' "$where" "${line:0:160}" >>"$out" + done +} +# Added lines of the diff, with file and line number. +git diff --no-color --no-renames -U0 "$mb" "$head" -- . \ + ':(exclude).github/scripts/public-text-check.sh' ':(exclude).github/scripts/public-text-check-test.sh' | + awk ' + /^diff --git / { hdr = 1; next } + hdr && /^\+\+\+ / { f = substr($0, 7); next } + /^@@ / { hdr = 0; split($3, a, ","); n = substr(a[1], 2) + 0; next } + !hdr && /^\+/ { print f ":" n ": " substr($0, 2); n++ } + ' | match | report "added line" +# Commit messages (subjects and bodies) of the pull request. +git log --format='%h %s%n%b' "$mb..$head" | match | report "commit message" +match "$title" | report "title" +match "$body" | report "description" +hits=$(wc -l <"$out" | tr -d ' ') +if [ "$hits" -gt 0 ]; then + cat "$out" + echo "public-text: $hits hit(s). Say what the code or test does instead of who asked for it; keep internal paths out." >&2 + exit 1 +fi +echo "public-text: clean" diff --git a/seaweed-block/.github/scripts/record-go-test-test.sh b/seaweed-block/.github/scripts/record-go-test-test.sh new file mode 100644 index 0000000000..54bd092d34 --- /dev/null +++ b/seaweed-block/.github/scripts/record-go-test-test.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +root=$(mktemp -d) +trap 'rm -rf "$root"' EXIT +mkdir -p "$root/bin" +cat >"$root/bin/go" <<'EOF' +#!/usr/bin/env bash +set -e +test "$1" = test && test "$2" = -json || exit 99 +printf '%s\n' '{"Time":"2026-12-02T00:00:01Z","Action":"run","Test":"TestX"}' +printf '%s\n' '{"Time":"2026-12-02T00:00:02Z","Action":"output","Test":"TestX","Output":"fixture output\n"}' +printf '%s\n' '{"Time":"2026-12-02T00:00:02Z","Action":"fail","Test":"TestX","Elapsed":1}' +if [ "${FAKE_GO_LARGE:-0}" = 1 ]; then + for ((i=0; i<10000; i++)); do printf '%s\n' '{"Action":"output","Output":"draining after recorder failure\n"}'; done +fi +echo 'fixture stderr' >&2 +if [ "${FAKE_GO_LARGE_STDERR:-0}" = 1 ]; then + for ((i=0; i<10000; i++)); do echo 'stderr draining after recorder failure' >&2; done +fi +exit "${FAKE_GO_EXIT:-0}" +EOF +chmod +x "$root/bin/go" +export PATH="$root/bin:$PATH" +code=0 +FAKE_GO_EXIT=7 bash "$here/record-go-test.sh" "$root/go-test.json" -run TestX >"$root/console" 2>"$root/stderr" || code=$? +test "$code" = 7 +grep -q 'fixture output' "$root/console" +grep -q 'fixture stderr' "$root/go-test.stderr" +"${PYTHON:-python3}" -c 'import json,sys; events=[json.loads(s) for s in open(sys.argv[1])]; assert len(events)==3; assert events[-1]["Elapsed"]==1; assert events[-1]["Time"]=="2026-12-02T00:00:02Z"' "$root/go-test.json" +FAKE_GO_EXIT=0 bash "$here/record-go-test.sh" "$root/go-test.json" -run TestX >"$root/console" 2>"$root/stderr" +test "$(wc -l <"$root/go-test.json")" = 6 +# The evidence destination cannot be opened (a file where its parent belongs). +# The original Go success/failure must still be the command's answer. +echo occupied >"$root/not-a-directory" +code=0 +FAKE_GO_EXIT=0 bash "$here/record-go-test.sh" "$root/not-a-directory/go-test.json" >"$root/console" 2>"$root/stderr" || code=$? +test "$code" = 0 +grep -q 'fixture output' "$root/console" +code=0 +FAKE_GO_EXIT=7 bash "$here/record-go-test.sh" "$root/not-a-directory/go-test.json" >"$root/console" 2>"$root/stderr" || code=$? +test "$code" = 7 +if [ "$(uname -s)" = Linux ] && [ -c /dev/full ]; then + ln -s /dev/full "$root/full.json" + FAKE_GO_LARGE=1 FAKE_GO_EXIT=0 bash "$here/record-go-test.sh" "$root/full.json" >"$root/console" 2>"$root/stderr" + grep -q 'draining after recorder failure' "$root/console" + grep -q 'test evidence unavailable' "$root/stderr" +fi +# The recorder itself dies after its first bytes (a crash, an OOM kill): the +# rest of a large stream still drains and Go's own status is the answer. +cat >"$root/bin/dead-recorder" <<'EOF2' +#!/usr/bin/env bash +head -c 100 >/dev/null +exit 3 +EOF2 +chmod +x "$root/bin/dead-recorder" +for want in 0 7; do + code=0 + PYTHON="$root/bin/dead-recorder" FAKE_GO_LARGE=1 FAKE_GO_EXIT=$want bash "$here/record-go-test.sh" "$root/dead.json" >"$root/console" 2>"$root/stderr" || code=$? + test "$code" = "$want" + grep -q 'draining after recorder failure' "$root/console" + grep -q 'the recorder exited' "$root/stderr" + # The stderr reader dies with a large stderr still to come. + code=0 + PYTHON="$root/bin/dead-recorder" FAKE_GO_LARGE_STDERR=1 FAKE_GO_EXIT=$want bash "$here/record-go-test.sh" "$root/dead.json" >"$root/console" 2>"$root/stderr" || code=$? + test "$code" = "$want" + grep -q 'stderr draining after recorder failure' "$root/stderr" + # The recorder cannot start at all (no such interpreter). + code=0 + PYTHON="$root/bin/no-such-python" FAKE_GO_LARGE=1 FAKE_GO_LARGE_STDERR=1 FAKE_GO_EXIT=$want bash "$here/record-go-test.sh" "$root/dead.json" >"$root/console" 2>"$root/stderr" || code=$? + test "$code" = "$want" + grep -q 'draining after recorder failure' "$root/console" + grep -q 'stderr draining after recorder failure' "$root/stderr" +done +echo 'record-go-test: output, timestamp, elapsed, append, dead-recorder and exit-status controls PASS' diff --git a/seaweed-block/.github/scripts/record-go-test.sh b/seaweed-block/.github/scripts/record-go-test.sh new file mode 100644 index 0000000000..d227a8bb14 --- /dev/null +++ b/seaweed-block/.github/scripts/record-go-test.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Keep timestamped Go events, while preserving the existing human output and +# nonzero pipeline status. One caller at a time appends to a job's event file. +set -euo pipefail +out=$1 +shift +mkdir -p "$(dirname "$out")" || true +capture="$(dirname "$0")/go-test-output.py" +# A recorder that dies (or cannot start) hands the rest of its stream to cat, +# so Go never writes into a closed pipe. +exec 3> >({ "${PYTHON:-python3}" -u "$capture" "${out%.json}.stderr" --raw || cat; } >&2) +stderr_pid=$! +# Only Go judges the test. The readers keep draining after evidence IO errors, +# so a disk-full recorder cannot turn Go's PASS into a pipeline/SIGPIPE failure. +set +e +go test -json "$@" 2>&3 | + { "${PYTHON:-python3}" -u "$capture" "$out" || { echo "test evidence unavailable: the recorder exited" >&2; cat; }; } +status=${PIPESTATUS[0]} +set -e +exec 3>&- +wait "$stderr_pid" || true +exit "$status" diff --git a/seaweed-block/.github/scripts/require-nvme-test.sh b/seaweed-block/.github/scripts/require-nvme-test.sh new file mode 100755 index 0000000000..6c239536ea --- /dev/null +++ b/seaweed-block/.github/scripts/require-nvme-test.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Tests require-nvme.sh with df and lsblk replaced by stubs on PATH. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +t=$(mktemp -d) +trap 'rm -rf "$t"' EXIT +mkdir -p "$t/bin" "$t/nvme" "$t/sata" "$t/mem" "$t/raid" "$t/share" "$t/half" +# df --output=source,fstype DIR: the stub answers by the directory's name. +cat >"$t/bin/df" <"$t/bin/lsblk" <<'STUB' +#!/usr/bin/env bash +case "$3" in +/dev/nvme0n1p1) printf 'part \ndisk nvme\n' ;; +/dev/sda2) printf 'part \ndisk sata\n' ;; +/dev/md0) printf 'raid1 \npart \ndisk nvme\npart \ndisk sata\n' ;; +/dev/nvme1n1p1) printf 'part \ndisk nvme\n'; echo "lsblk: read error" >&2; exit 32 ;; +*) echo "lsblk: $3: not a block device" >&2; exit 32 ;; +esac +STUB +chmod +x "$t/bin/df" "$t/bin/lsblk" +run() { PATH="$t/bin:$PATH" RUNNER_NAME=r1 bash "$here/require-nvme.sh" "$@" >"$t/out" 2>&1; } +fail() { echo "FAIL: $*"; cat "$t/out"; exit 1; } + +run "$t/nvme" "$t/mem" "" || fail "nvme + tmpfs (any source name) + empty arg must pass" +run "$t/nvme/not/made/yet" || fail "a missing dir is judged by its nearest existing parent" +! run "$t/nvme" "$t/sata" || fail "a SATA dir must fail" +grep -q "runner r1" "$t/out" || fail "the failure must name the runner" +grep -q "FAIL $t/sata" "$t/out" || fail "the failure must name the directory" +! run "$t/raid" || fail "an array with a SATA member must fail" +! run "$t/share" || fail "a network share must fail" +grep -q "not a block device" "$t/out" || fail "a network share must say why" +! run "$t/half" || fail "an lsblk error after partial NVMe output must fail" +echo "require-nvme tests: ok" diff --git a/seaweed-block/.github/scripts/require-nvme.sh b/seaweed-block/.github/scripts/require-nvme.sh new file mode 100755 index 0000000000..5f4cab7a8d --- /dev/null +++ b/seaweed-block/.github/scripts/require-nvme.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Fails a self-hosted job whose workspace, temp or Go cache directory is not +# on an NVMe disk. The process-level tests write and fsync real files; on a +# box whose system disk is SATA, a default runner install puts _work there and +# the tests time out under the disk load instead of failing on a real bug. +# A tmpfs directory is accepted (memory, not a slow disk). +# Usage: require-nvme.sh DIR... +set -euo pipefail +bad=0 +for p in "$@"; do + [ -n "$p" ] || continue + d=$p + while [ ! -e "$d" ]; do d=$(dirname "$d"); done + read -r src fstype < <(df --output=source,fstype "$d" | tail -n 1) + if [ "$fstype" = tmpfs ]; then + echo "ok $p: $src (tmpfs)" + continue + fi + # Every disk under the source (all members of an array) must be NVMe; an + # lsblk error voids whatever it printed. + disks= + if tree=$(lsblk -nrso TYPE,TRAN "$src" 2>/dev/null); then + disks=$(printf '%s\n' "$tree" | + awk '$1 == "disk" { print ($2 == "" ? "unknown" : $2) }' | sort -u | tr '\n' ' ') + fi + if [ "$disks" = "nvme " ]; then + echo "ok $p: $src (nvme)" + else + echo "FAIL $p: $src (disk: ${disks:-not a block device})" + bad=1 + fi +done +if [ "$bad" -ne 0 ]; then + echo "runner ${RUNNER_NAME:-?}: work, temp and Go cache directories must be on NVMe; move them before this runner takes jobs" >&2 + exit 1 +fi diff --git a/seaweed-block/.github/scripts/required-tests-check-test.py b/seaweed-block/.github/scripts/required-tests-check-test.py new file mode 100644 index 0000000000..94385dc8ba --- /dev/null +++ b/seaweed-block/.github/scripts/required-tests-check-test.py @@ -0,0 +1,128 @@ +"""Self-test of required-tests-check.py: event streams against the exit code +they must give. A gate that cannot fail is the defect this check exists to +prevent, so every way a named test can fail to pass is here.""" +import json +import os +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +CHECK = os.path.join(HERE, 'required-tests-check.py') + + +def ev(action, test=None, elapsed=None): + e = {'Action': action, 'Package': 'example/cmd/blockvolume'} + if test: + e['Test'] = test + if elapsed is not None: + e['Elapsed'] = elapsed + return json.dumps(e) + + +def ran(test, end='pass', secs=1.5): + return [ev('run', test), ev('output', test), ev(end, test, secs)] + + +def run(names, *streams, status=None): + with tempfile.TemporaryDirectory() as d: + nf = os.path.join(d, 'names') + with open(nf, 'w', encoding='utf-8') as f: + f.write(names) + files = [] + for i, lines in enumerate(streams): + p = os.path.join(d, 'events%d' % i) + with open(p, 'w', encoding='utf-8') as f: + f.write('\n'.join(lines) + '\n') + files.append(p) + extra = [] + if status is not None: + sf = os.path.join(d, 'status') + with open(sf, 'w', encoding='utf-8') as f: + f.write(status) + extra = ['--status', sf] + r = subprocess.run([sys.executable, '-I', CHECK] + extra + [nf] + files, capture_output=True, text=True) + return r.returncode, r.stdout + r.stderr + + +NG = 'TestA\nTestB # nongating=#920\n' + +CASES = [ + # (name, want exit, names file, streams) + ('a non-gating test that passed', 0, NG, [ran('TestA') + ran('TestB')]), + ('a non-gating test that failed does not fail the run', 0, NG, [ran('TestA') + ran('TestB', 'fail')]), + ('a non-gating failure, then its process failed: still its own', 0, NG, + [ran('TestA'), ran('TestB', 'fail') + [ev('fail')]]), + ('a gating test still fails the run beside a non-gating one', 1, NG, [ran('TestA', 'fail') + ran('TestB')]), + ('a process failure after a gating test still fails the run', 1, NG, [ran('TestA') + [ev('fail')], ran('TestB')]), + ('a non-gating test that never ran fails (not run is not reported)', 1, NG, [ran('TestA')]), + ('nongating without an issue is refused', 2, 'TestA\nTestB # nongating\n', [ran('TestA') + ran('TestB')]), + ('every named test passed', 0, 'TestA\nTestB # a comment\n', [ran('TestA') + ran('TestB')]), + ('passes spread over two streams', 0, 'TestA\nTestB\n', [ran('TestA'), ran('TestB')]), + ('an unnamed test may fail', 0, 'TestA\n', [ran('TestA') + ran('TestOther', 'fail')]), + ('a passing subtest does not stand for a skipped parent', 1, 'TestA\n', + [[ev('run', 'TestA'), ev('pass', 'TestA/sub', 1), ev('skip', 'TestA', 0)]]), + ('a skip is a failure', 1, 'TestA\nTestB\n', [ran('TestA') + ran('TestB', 'skip', 0)]), + ('a failed test', 1, 'TestA\n', [ran('TestA', 'fail')]), + ('a test that never ran', 1, 'TestA\nTestB\n', [ran('TestA')]), + ('a test that started and never ended (killed by the timeout)', 1, 'TestA\n', [[ev('run', 'TestA'), ev('output', 'TestA')]]), + ('passed in one stream, failed in another', 1, 'TestA\n', [ran('TestA'), ran('TestA', 'fail')]), + ('no events at all (the build failed)', 1, 'TestA\n', [['# example/cmd/blockvolume', 'build failed']]), + ('a package-level failure after every named test passed', 1, 'TestA\n', [ran('TestA') + [ev('fail', None, 3)]]), + ('a name listed twice', 2, 'TestA\nTestA\n', [ran('TestA')]), + ('a subtest name in the list', 2, 'TestA/sub\n', [ran('TestA')]), + ('an empty names file', 2, '# nothing\n', [ran('TestA')]), +] + + +def main(): + fail = 0 + for name, want, names, streams in CASES: + got, out = run(names, *streams) + if got != want: + print('FAIL %s: exit %d, want %d\n%s' % (name, got, want, out)) + fail = 1 + STATUS = [ + ('PASS events and every process exited 0', 0, 'TestA 0\nTestB 0\n'), + ('PASS, then the process exited 1', 1, 'TestA 0\nTestB 1\n'), + ('PASS, then the process was killed by the timeout', 1, 'TestA 0\nTestB 124\n'), + ('a named test with no exit status', 1, 'TestA 0\n'), + ('a named test ran twice', 1, 'TestA 0\nTestB 0\nTestB 0\n'), + ('a malformed status line', 2, 'TestA 0\nTestB\n'), + ] + for name, want, status in STATUS: + got, out = run('TestA\nTestB\n', ran('TestA') + ran('TestB'), status=status) + if got != want: + print('FAIL %s: exit %d, want %d\n%s' % (name, got, want, out)) + fail = 1 + got, out = run('TestA\n', [ev('run', 'TestA'), json.dumps({'Action': 'output', 'Test': 'TestA', 'Output': ' x_test.go:7: the reason\n'})] + [json.dumps({'Action': 'output', 'Test': 'TestA', 'Output': ' h_test.go:578: blockvolume-r%d log:\n' % i}) for i in range(20)] + [json.dumps({'Action': 'output', 'Test': 'TestA', 'Output': ' w_test.go:128: ---- master log tail ----\n'})] + [json.dumps({'Action': 'output', 'Test': 'TestA', 'Output': ' I1126 harness log line %d\n' % i}) for i in range(60)] + [ev('fail', 'TestA', 1)]) + if got != 1 or 'x_test.go:7: the reason' not in out: + print('FAIL a failed test''s output is shown: %s' % out) + fail = 1 + # A message whose reason is on its continuation lines (a holder's log + # tail after "its log ends:"), followed by a harness dump: the message's + # last continuation lines are shown, the dump is not. + o = lambda s: json.dumps({'Action': 'output', 'Test': 'TestA', 'Output': s + '\n'}) + got, out = run('TestA\n', [ev('run', 'TestA'), + o(' f1_test.go:178: blockvolume-v5r2 exited (exit status 1) before logging "adopted"; its log ends:')] + + [o(' holder line %d' % i) for i in range(40)] + + [o(' holder: fatal: the reason it exited')] + + [o(' w_test.go:128: ---- master log tail ----')] + + [o(' I1201 harness log line %d' % i) for i in range(60)] + [ev('fail', 'TestA', 1)]) + if got != 1 or 'holder: fatal: the reason it exited' not in out or 'holder line 39' not in out: + print('FAIL a failed message\'s continuation lines are shown: %s' % out) + fail = 1 + if 'holder line 0\n' in out or 'harness log line 0\n' in out: + print('FAIL continuation lines are bounded and a dump\'s are not kept: %s' % out) + fail = 1 + got, out = run('TestA\n', ran('TestA', secs=2.25)) + if got != 0 or '2.2s' not in out and '2.3s' not in out: + print('FAIL the elapsed time is reported: %s' % out) + fail = 1 + if not fail: + print('required-tests-check: %d cases ok' % (len(CASES) + len(STATUS) + 3)) + return fail + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/seaweed-block/.github/scripts/required-tests-check.py b/seaweed-block/.github/scripts/required-tests-check.py new file mode 100644 index 0000000000..59569ea1ef --- /dev/null +++ b/seaweed-block/.github/scripts/required-tests-check.py @@ -0,0 +1,214 @@ +"""Every named test must have run and passed. + +Usage: required-tests-check.py [--status STATUS_FILE] NAMES_FILE EVENTS_FILE... + +NAMES_FILE holds one top-level test name per line (# starts a comment). A +name whose comment says `nongating=#N` (an open issue) is non-gating: it runs +and is reported like every other, but its failure does not fail the run; its +line says NON-GATING and names the issue, and a failure-process exit after it +is its own, not the binary's. A non-gating test that never ran still fails: +a test that is not run is not reported. +EVENTS_FILE is `go test -json` (or `go tool test2json`) output. A named test +that skipped, failed, never started or never ended is a failure: a test that +cannot start proves nothing, so it is not allowed to read as a pass. A name +listed twice, or a test that passed in one stream and failed in another, is a +failure too. A package-level failure event fails the run. + +STATUS_FILE (run-named-tests.sh) holds one line per named test, NAME and the +exit status of the process that ran it. With it, a named test passes only if it +also has exactly one line and that status is 0: a test that reports PASS and +then fails, panics or hangs on its way out is not a pass. Prints one line per named test with its outcome and elapsed +seconds, then the total. + +For every named test that did not pass, its own reported lines (the test's +file:line messages with the last lines of each one's continuation, not the +harness's log dumps) and its last lines follow the table, so a run's log +carries its own reasons. + +Exit 0: every named test passed. 1: at least one did not. 2: usage or an +unreadable input. +""" +import json +import re +import sys + +OWN = 12 # a failed test's own file:line messages shown (the last ones) +TAIL = 5 # and its last output lines +OWN_LINE = re.compile(r'^ [^ \t]+\.go:\d+: ') # the test's own t.Log/t.Error lines +# Not reasons: the harness's cleanup headers (" log:", "---- log +# tail ----") and the echo of a command that succeeded ("...: exit 0"). +NOISE = re.compile(r' log:\s*$|---- .* ----\s*$|: exit 0\s*$') + + +CONT = 20 # the last continuation lines shown of each own message +CONT_LINE = re.compile(r'^ ') # a message's next line, as go test indents it + + +def own_messages(text): + """The test's own messages, each its file:line line and the last CONT of + the continuation lines after it (a reason, such as a process's log tail, + is often on those). A harness header's lines are not kept, nor its dump.""" + msgs, cur = [], None + for line in text: + if OWN_LINE.match(line): + cur = None + if not NOISE.search(line): + cur = [line, []] + msgs.append(cur) + elif cur is not None and CONT_LINE.match(line): + cur[1].append(line) + else: + cur = None + return [[head] + cont[-CONT:] for head, cont in msgs] + + +NONGATING = re.compile(r'\bnongating=(#\d+)') + + +def names_of(path): + """The named tests, in order, and the non-gating ones with their issue.""" + names, seen, nongating = [], set(), {} + with open(path, encoding='utf-8') as f: + for n, raw in enumerate(f, 1): + line, _, comment = raw.partition('#') + line = line.strip() + if not line: + continue + m = NONGATING.search('#' + comment) + if m: + nongating[line] = m.group(1) + elif 'nongating' in comment: + raise ValueError('%s:%d: %r: nongating needs an issue, nongating=#N' % (path, n, raw.strip())) + if not line.startswith('Test') or '/' in line or ' ' in line: + raise ValueError('%s:%d: %r is not a top-level test name' % (path, n, line)) + if line in seen: + raise ValueError('%s:%d: %s is listed twice' % (path, n, line)) + seen.add(line) + names.append(line) + if not names: + raise ValueError('%s: no test names' % path) + return names, nongating + + +def statuses_of(path): + """Test name -> list of exit statuses.""" + out = {} + with open(path, encoding='utf-8') as f: + for n, raw in enumerate(f, 1): + parts = raw.split() + if not parts: + continue + if len(parts) != 2 or not parts[1].lstrip('-').isdigit(): + raise ValueError('%s:%d: %r is not NAME EXIT_STATUS' % (path, n, raw.strip())) + out.setdefault(parts[0], []).append(int(parts[1])) + return out + + +def outcomes(paths): + """Test name -> list of (action, elapsed) for its terminal events, the + names that started (action run), the package-level failure events (each + with the test last started in its stream before it, or None), and each + test's output.""" + ends, started, pkg_fail, output = {}, set(), [], {} + for path in paths: + last = None + with open(path, encoding='utf-8', errors='replace') as f: + for raw in f: + raw = raw.strip() + if not raw.startswith('{'): + continue # build output or a panic line between events + try: + ev = json.loads(raw) + except ValueError: + continue + test = ev.get('Test') + if not test: + if ev.get('Action') == 'fail': + pkg_fail.append(last) # the binary failed outside any test (or after one) + continue # other package events; a subtest's name never matches a top-level one + action = ev.get('Action') + if action == 'output': + output.setdefault(test.split('/')[0], []).append(ev.get('Output', '')) + continue + if action == 'run': + started.add(test) + if '/' not in test: + last = test + elif action in ('pass', 'fail', 'skip'): + ends.setdefault(test, []).append((action, ev.get('Elapsed'))) + return ends, started, pkg_fail, output + + +def main(argv): + args = argv[1:] + status_file = None + if args[:1] == ['--status']: + if len(args) < 2: + print(__doc__.strip().splitlines()[2], file=sys.stderr) + return 2 + status_file, args = args[1], args[2:] + if len(args) < 2: + print(__doc__.strip().splitlines()[2], file=sys.stderr) + return 2 + try: + names, nongating = names_of(args[0]) + ends, started, pkg_fail, output = outcomes(args[1:]) + statuses = statuses_of(status_file) if status_file else None + except (OSError, ValueError) as e: + print('required-tests: %s' % e, file=sys.stderr) + return 2 + # A package-level failure right after a non-gating test is that test's + # (each named test runs in its own process); any other fails the run. + pkg_own = {} + for after in pkg_fail: + if after in nongating: + pkg_own[after] = pkg_own.get(after, 0) + 1 + pkg_fail = [a for a in pkg_fail if a not in nongating] + bad, total, failed, ng_failed = 0, 0.0, [], 0 + for name in names: + got = ends.get(name, []) + actions = {a for a, _ in got} + secs = sum(e for _, e in got if isinstance(e, (int, float))) + total += secs + rcs = statuses.get(name, []) if statuses is not None else [0] + if actions == {'pass'} and len(got) == 1 and rcs == [0] and not pkg_own.get(name): + print('PASS %-70s %7.1fs' % (name, secs)) + continue + failed.append(name) + issue = nongating.get(name) + ran_at_all = bool(got) or name in started + if issue and ran_at_all: + ng_failed += 1 + else: + bad += 1 + if actions == {'pass'} and len(got) == 1: + why = ('NO EXIT STATUS' if not rcs else + 'PASSED, THEN EXIT %s' % ','.join(str(r) for r in rcs)) + elif not got: + why = 'STARTED, NEVER ENDED' if name in started else 'NEVER RAN' + elif len(got) > 1: + why = 'RAN %d TIMES (%s)' % (len(got), ', '.join(a for a, _ in got)) + else: + why = got[0][0].upper() + if pkg_own.get(name): + why += ', THEN THE PROCESS FAILED' + if issue and ran_at_all: + print('%-8s %-70s %7.1fs' % ('FAIL', name, secs) + ' ' + why + ' NON-GATING (%s): reported, does not fail the run' % issue) + else: + print('%-8s %-70s %7.1fs' % ('FAIL', name, secs) + ' ' + why) + for name in failed: + text = ''.join(output.get(name, [])).splitlines() + own = own_messages(text)[-OWN:] + print('---- %s: its own messages (%d), then its last %d lines' % (name, len(own), min(TAIL, len(text)))) + for line in [l for m in own for l in m] + [' ...'] + text[-TAIL:]: + print(' ' + line[:300]) + if pkg_fail: + print('FAIL the test binary reported %d package-level failure(s)' % len(pkg_fail)) + print('required-tests: %d named, %d not passed, %.1fs in named tests' % (len(names), bad, total)) + if nongating: + print('required-tests: %d non-gating (%s), %d of them failed' % (len(nongating), ', '.join('%s %s' % (n, nongating[n]) for n in names if n in nongating), ng_failed)) + return 1 if bad or pkg_fail else 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/seaweed-block/.github/scripts/run-named-tests-test.sh b/seaweed-block/.github/scripts/run-named-tests-test.sh new file mode 100644 index 0000000000..fbf50608c6 --- /dev/null +++ b/seaweed-block/.github/scripts/run-named-tests-test.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Self-test of run-named-tests.sh with the gate (required-tests-check.py +# --status), through a real shell and test2json, with fake test binaries: +# a test that reports PASS and then exits nonzero, or hangs until the +# timeout, must fail the gate; an honest pass must not. Needs go (test2json). +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +fail=0 + +# fake NAME BEHAVIOUR: a test binary that prints a passing verbose run of +# whatever -test.run names, then behaves as told. +fake() { + local f=$tmp/$1 + cat >"$f" <"$tmp/names" + TEST_PKG=example/fake bash "$here/run-named-tests.sh" "$bin" "$tmp/names" "$tmp/events" "$tmp/status" 3s "$tmp" >/dev/null + "${PYTHON:-python3}" -I "$here/required-tests-check.py" --status "$tmp/status" "$tmp/names" "$tmp/events" >"$tmp/out" || got=$? + if [[ $got != "$want" ]]; then + echo "FAIL $name: exit $got, want $want" + cat "$tmp/out" + fail=1 + fi +} + +expect 0 "PASS and exit 0" "$(fake ok 'exit 0')" +expect 1 "PASS, then exit 1" "$(fake exit1 'exit 1')" +expect 1 "PASS, then a hang until the timeout" "$(fake hang 'sleep 30')" + +if ((fail == 0)); then echo "run-named-tests: 3 cases ok"; fi +exit "$fail" diff --git a/seaweed-block/.github/scripts/run-named-tests.sh b/seaweed-block/.github/scripts/run-named-tests.sh new file mode 100644 index 0000000000..b5f7226026 --- /dev/null +++ b/seaweed-block/.github/scripts/run-named-tests.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Runs each test named in NAMES_FILE in its own process of TEST_BINARY, in +# sequence, so a panic or a hang in one cannot hide the others. Each process +# is bounded by TIMEOUT (the test binary's own timeout, then killed). Every +# process's exit status is kept: a test that reports PASS and then fails or +# hangs on its way out is not a pass (required-tests-check.py --status). +# +# Usage: run-named-tests.sh TEST_BINARY NAMES_FILE EVENTS_OUT STATUS_OUT TIMEOUT [DIR] +# TEST_BINARY absolute path of a binary built with go test -c +# EVENTS_OUT go test -json events of every process, appended in order +# STATUS_OUT one line per named test: NAME EXIT_STATUS +# DIR the directory each process runs in (default .) +# TEST_PKG names the package in the events (default the blockvolume command). +# Exits 0 once every named test has run; the verdict is the checker's. +set -euo pipefail +[ "$#" -ge 5 ] || { echo "usage: run-named-tests.sh TEST_BINARY NAMES_FILE EVENTS_OUT STATUS_OUT TIMEOUT [DIR]" >&2; exit 2; } +bin=$1 names=$2 out=$3 status=$4 to=$5 dir=${6:-.} +case "$bin" in /*) ;; *) echo "run-named-tests: TEST_BINARY must be absolute" >&2; exit 2 ;; esac +pkg=${TEST_PKG:-github.com/seaweedfs/seaweed-block/cmd/blockvolume} +: >"$out" +: >"$status" +while read -r name; do + start=$(date +%s) + rc=0 + (cd "$dir" && timeout -k 30 "$to" "$bin" -test.v=test2json -test.count=1 \ + -test.timeout "$to" -test.run "^${name}\$" 2>&1) | + go tool test2json -t -p "$pkg" >>"$out" || rc=$? + echo "$name $rc" >>"$status" + echo "$name: exit $rc, $(($(date +%s) - start))s" +done < <(sed 's/#.*//' "$names" | tr -d ' \t' | grep .) diff --git a/seaweed-block/.github/scripts/sametokens.go b/seaweed-block/.github/scripts/sametokens.go new file mode 100644 index 0000000000..c167f2429d --- /dev/null +++ b/seaweed-block/.github/scripts/sametokens.go @@ -0,0 +1,111 @@ +// Command sametokens reports whether two versions of a Go source file have the +// same tokens in the same order, ignoring comments that the compiler ignores. +// +// Usage: go run sametokens.go OLD NEW +// +// A missing file counts as empty. Directive comments are compared as tokens: +// //go:..., // +build, //line, /*line, //export; in a file that uses cgo +// (any "C" string literal, as in import "C"), every comment counts, since the +// preamble is code. Exit 0: same tokens; 1: different +// (the first difference is printed); 2: usage error or a file that does not scan. +package main + +import ( + "fmt" + "go/scanner" + "go/token" + "os" + "strings" +) + +type tok struct { + t token.Token + lit string +} + +func main() { + if len(os.Args) != 3 { + fmt.Fprintln(os.Stderr, "usage: sametokens OLD NEW") + os.Exit(2) + } + a, err := tokens(os.Args[1]) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + b, err := tokens(os.Args[2]) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + for i := 0; i < len(a) || i < len(b); i++ { + if i >= len(a) || i >= len(b) || a[i] != b[i] { + fmt.Printf("token %d differs: %v vs %v\n", i, at(a, i), at(b, i)) + os.Exit(1) + } + } +} + +func at(ts []tok, i int) string { + if i >= len(ts) { + return "end of file" + } + return fmt.Sprintf("%s %q", ts[i].t, ts[i].lit) +} + +// tokens scans a file and keeps every token except comments the compiler +// ignores. An automatic semicolon is compared by kind only. +func tokens(path string) ([]tok, error) { + src, err := os.ReadFile(path) + if os.IsNotExist(err) { + return nil, nil + } else if err != nil { + return nil, err + } + fset := token.NewFileSet() + file := fset.AddFile(path, -1, len(src)) + var s scanner.Scanner + var scanErr error + s.Init(file, src, func(pos token.Position, msg string) { + if scanErr == nil { + scanErr = fmt.Errorf("%s: %s", pos, msg) + } + }, scanner.ScanComments) + var all []tok + for { + _, t, lit := s.Scan() + if t == token.EOF { + break + } + if t == token.SEMICOLON { + lit = "" + } + all = append(all, tok{t, lit}) + } + if scanErr != nil { + return nil, scanErr + } + cgo := false + for _, x := range all { + if x.t == token.STRING && x.lit == "\"C\"" { + cgo = true + } + } + var out []tok + for _, x := range all { + if x.t == token.COMMENT && !cgo && !directive(x.lit) { + continue + } + out = append(out, x) + } + return out, nil +} + +func directive(c string) bool { + for _, p := range []string{"//go:", "// +build", "//+build", "//line ", "/*line ", "//export "} { + if strings.HasPrefix(c, p) { + return true + } + } + return false +} diff --git a/seaweed-block/.github/scripts/shard-named-tests-test.py b/seaweed-block/.github/scripts/shard-named-tests-test.py new file mode 100644 index 0000000000..2b36d94fe9 --- /dev/null +++ b/seaweed-block/.github/scripts/shard-named-tests-test.py @@ -0,0 +1,55 @@ +"""Tests shard-named-tests.py: every name in exactly one shard, longest first +into the least-loaded shard, the same split on every run, unknown names +counted, and a duplicate or empty list refused.""" +import importlib.util +import os +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +SCRIPT = os.path.join(HERE, "shard-named-tests.py") +spec = importlib.util.spec_from_file_location("shard", SCRIPT) +shard = importlib.util.module_from_spec(spec) +spec.loader.exec_module(shard) + +fail = 0 + + +def check(name, ok): + global fail + print(("ok " if ok else "FAIL ") + name) + if not ok: + fail = 1 + + +secs = {"A": 500, "B": 400, "C": 300, "D": 100, "E": 100} +parts, load = shard.shard(list(secs), secs, 2) +check("every name once", sorted(sum(parts, [])) == sorted(secs)) +check("longest first, least loaded", parts == [["A", "D", "E"], ["B", "C"]] and load == [700, 700]) +check("same split on every run", shard.shard(list(secs), secs, 2) == (parts, load)) +parts, load = shard.shard(["A", "Z"], {"A": 10}, 2) +check("an unknown name counts as the default", load == [shard.DEFAULT, 10.0]) +parts, _ = shard.shard(["A", "B"], {}, 4) +check("more shards than names leaves some empty", sum(len(p) for p in parts) == 2 and [] in parts) + +with tempfile.TemporaryDirectory() as d: + names = os.path.join(d, "names.txt") + seconds = os.path.join(d, "seconds.txt") + with open(seconds, "w") as f: + f.write("# times\nTestA 30\nTestB 20\n") + with open(names, "w") as f: + f.write("# list\nTestA\nTestB # note\n\nTestC\n") + rc = subprocess.run([sys.executable, "-I", SCRIPT, names, seconds, "2", os.path.join(d, "out")], capture_output=True, text=True).returncode + got = sorted(open(os.path.join(d, "out", f)).read().split() for f in ("1.txt", "2.txt")) + check("the files hold every name once", rc == 0 and sorted(sum(got, [])) == ["TestA", "TestB", "TestC"]) + with open(names, "w") as f: + f.write("TestA\nTestA\n") + rc = subprocess.run([sys.executable, "-I", SCRIPT, names, seconds, "2", os.path.join(d, "o2")], capture_output=True, text=True).returncode + check("a name listed twice is refused", rc == 2) + with open(names, "w") as f: + f.write("# nothing\n") + rc = subprocess.run([sys.executable, "-I", SCRIPT, names, seconds, "2", os.path.join(d, "o3")], capture_output=True, text=True).returncode + check("an empty list is refused", rc == 2) + +sys.exit(fail) diff --git a/seaweed-block/.github/scripts/shard-named-tests.py b/seaweed-block/.github/scripts/shard-named-tests.py new file mode 100644 index 0000000000..0997c60714 --- /dev/null +++ b/seaweed-block/.github/scripts/shard-named-tests.py @@ -0,0 +1,69 @@ +"""Split the named process-level tests into N balanced shards. + +Usage: shard-named-tests.py NAMES_FILE SECONDS_FILE N OUT_DIR + +Writes OUT_DIR/1.txt .. OUT_DIR/N.txt, one test name per line. Every name in +NAMES_FILE (# starts a comment) lands in exactly one shard. SECONDS_FILE holds +"Name seconds" lines from an earlier run; a name missing there counts as +DEFAULT seconds. Longest first, each into the shard with the least time so +far (ties to the lowest shard), so the result is the same on every run. +Prints each shard's names count and its estimated seconds. + +Exit 0, or 2 on a usage error, a duplicate name or an empty names list. +""" +import os +import sys + +DEFAULT = 60.0 + + +def names_of(path): + out = [] + for line in open(path, encoding="utf-8"): + name = line.split("#", 1)[0].strip() + if name: + out.append(name) + return out + + +def seconds_of(path): + out = {} + for line in open(path, encoding="utf-8"): + fields = line.split("#", 1)[0].split() + if len(fields) == 2: + out[fields[0]] = float(fields[1]) + return out + + +def shard(names, seconds, n): + load = [0.0] * n + shards = [[] for _ in range(n)] + for name in sorted(names, key=lambda x: (-seconds.get(x, DEFAULT), x)): + k = min(range(n), key=lambda i: (load[i], i)) + shards[k].append(name) + load[k] += seconds.get(name, DEFAULT) + return shards, load + + +def main(argv): + if len(argv) != 5: + print(__doc__.strip().splitlines()[2], file=sys.stderr) + return 2 + names = names_of(argv[1]) + if not names or len(set(names)) != len(names): + print("shard-named-tests: empty names list or a name listed twice", file=sys.stderr) + return 2 + n = int(argv[3]) + if n < 1: + return 2 + shards, load = shard(names, seconds_of(argv[2]), n) + os.makedirs(argv[4], exist_ok=True) + for i, part in enumerate(shards, 1): + with open(os.path.join(argv[4], "%d.txt" % i), "w", encoding="utf-8") as f: + f.write("".join(x + "\n" for x in part)) + print("shard %d: %d tests, about %d s" % (i, len(part), load[i - 1])) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/seaweed-block/.github/scripts/spec-trace-check-test.sh b/seaweed-block/.github/scripts/spec-trace-check-test.sh new file mode 100644 index 0000000000..da313fa225 --- /dev/null +++ b/seaweed-block/.github/scripts/spec-trace-check-test.sh @@ -0,0 +1,151 @@ +#!/usr/bin/env bash +# Self-test of the spec-trace check: PR descriptions and change lists against +# the exit code they must give. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +check=$here/spec-trace-check.sh +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +fail=0 + +# expect WANT_EXIT NAME BODY [STATUS PATH]... +expect() { + local want=$1 name=$2 body=$3 got=0 + shift 3 + printf '%s' "$body" >"$tmp/body" + if (($#)); then printf '%s\0' "$@"; fi | bash "$check" "$tmp/body" >/dev/null || got=$? + if [[ $got != "$want" ]]; then + echo "FAIL $name: exit $got, want $want" + fail=1 + fi +} + +ok='Feature: O-SNAP-2 +Machine/INV: IMPL M5.Quiesce>Copy / INV-MAINT-ONE-OWNER +Model: docs/spec/MaintenanceOwner.tla, exhausted +Red-first: 7f542dbc TestMaintenanceHeldPass failed on base' +simplest='Simplest: one owner per volume on the existing cut path; no new machine.' + +expect 0 "all four lines, docs only" "$ok" M docs/a.md +expect 0 "FIX kind" "${ok/IMPL M5.Quiesce>Copy/FIX INV-GC-SKEW-001}" +expect 0 "CHANGE kind" "${ok/IMPL M5.Quiesce>Copy/CHANGE M5}" +expect 0 "core change with Simplest" "$ok +$simplest" M core/storage/gc.go +expect 0 "core test only needs no Simplest" "$ok" M core/storage/gc_test.go +expect 0 "CRLF body" "$(printf '%s\n' "$ok" | sed 's/$/\r/')" +expect 0 "CHANGE of two machines" "${ok/IMPL M5.Quiesce>Copy/CHANGE M4, M6}" +expect 0 "list markers and bold keys" "$(printf '%s\n' "$ok" | sed "s/^Feature:/- **Feature:**/; s/^Model:/* Model:/")" +expect 0 "Model NONE with a reason" "${ok/Model: docs\/spec\/MaintenanceOwner.tla, exhausted/Model: NONE: CI wiring only, no state}" + +expect 1 "empty body" "" +expect 1 "missing Red-first" "$(printf '%s\n' "$ok" | grep -v Red-first)" +expect 1 "short NONE" "${ok/Model: docs\/spec\/MaintenanceOwner.tla, exhausted/Model: NONE: n/a}" +expect 1 "no kind" "${ok/IMPL M5.Quiesce>Copy/B,D,E}" +expect 1 "IMPL without transition" "${ok/IMPL M5.Quiesce>Copy/IMPL M5}" +expect 1 "NONE is not a kind" "${ok/IMPL M5.Quiesce>Copy \/ INV-MAINT-ONE-OWNER/NONE: tooling only, no machine}" +expect 1 "core file deleted without Simplest" "$ok" D core/storage/old.go +expect 1 "two kinds" "${ok/IMPL M5.Quiesce>Copy/IMPL M5.Quiesce>Copy FIX INV-MAINT-ONE-OWNER}" +expect 1 "second Machine/INV line with another kind" "$ok +Machine/INV: FIX INV-MAINT-ONE-OWNER" +expect 1 "second Machine/INV line in list and bold form" "$ok +- **Machine/INV:** CHANGE M5" +expect 1 "Simplest declared twice" "$ok +$simplest +$simplest" M core/storage/gc.go +expect 1 "kind token with a trailing junk" "${ok/IMPL M5.Quiesce>Copy/FIX INV-GC-SKEW-001x}" +expect 1 "transition with a stray character" "${ok/IMPL M5.Quiesce>Copy/IMPL M5.Quiesce>Copy;x}" +expect 1 "key inside another word" "${ok/Feature: O-SNAP-2/Not-Feature: O-SNAP-2}" +expect 1 "placeholder left in Feature" "${ok/Feature: O-SNAP-2/Feature: }" +expect 1 "placeholder left in Red-first" "$(printf '%s\n' "$ok" | sed "s/^Red-first:.*/Red-first: /")" +expect 1 "placeholder left in Simplest" "$ok +Simplest: " M core/storage/gc.go +expect 1 "unfilled template" "$(cat "$here/../pull_request_template.md")" +expect 1 "core change without Simplest" "$ok" M core/storage/gc.go +expect 1 "cmd change, short Simplest" "$ok +Simplest: small" A cmd/sw-block/new.go + +# expect_raw WANT_EXIT NAME BYTES: a change list given as printf format. +expect_raw() { + local want=$1 name=$2 got=0 + printf "%s" "$ok" >"$tmp/body" + printf "$3" | bash "$check" "$tmp/body" >/dev/null 2>&1 || got=$? + if [[ $got != "$want" ]]; then + echo "FAIL $name: exit $got, want $want" + fail=1 + fi +} +expect_raw 2 "record cut off before its NUL" "M\0core/storage/gc.go" +expect_raw 2 "status without a path" "M\0" +expect_raw 2 "status cut off before its NUL" "M\0docs/a.md\0M" +expect_raw 2 "unknown status" "R100\0core/a.go\0" +expect_raw 0 "well-formed docs change" "M\0docs/a.md\0" + + +# Kinds for PRs that change no behaviour: each is checked against its paths; +# DOCS also compares the old and new tokens of each changed non-test Go file. +# expect_kind WANT_EXIT NAME KIND OLD_GO NEW_GO [STATUS PATH]... +# OLD_GO/NEW_GO are core/x/s.go before and after ("-" = no blob for that side). +expect_kind() { + local want=$1 name=$2 k=$3 old=$4 new=$5 got=0 + shift 5 + printf '%s' "${ok/IMPL M5.Quiesce>Copy/$k} +$simplest" >"$tmp/body" + rm -rf "$tmp/blobs"; mkdir -p "$tmp/blobs/old/core/x" "$tmp/blobs/new/core/x" + [[ $old == - ]] || printf '%s' "$old" >"$tmp/blobs/old/core/x/s.go" + [[ $new == - ]] || printf '%s' "$new" >"$tmp/blobs/new/core/x/s.go" + if (($#)); then printf '%s\0' "$@"; fi | bash "$check" "$tmp/body" "$tmp/blobs" >/dev/null || got=$? + if [[ $got != "$want" ]]; then + echo "FAIL $name: exit $got, want $want" + fail=1 + fi +} +P=$'package x\n' +expect_kind 0 "DOCS: comment-only Go" DOCS "${P}var A = 1"$'\n' "${P}"$'// A is one.\nvar A = 1 // one\n' M docs/a.md M core/x/s.go A core/x/s_test.go +expect_kind 0 "DOCS: gofmt realignment" DOCS "${P}var A = 1"$'\n' "${P}var A = 1"$'\n' M core/x/s.go +expect_kind 0 "DOCS: block comment" DOCS "${P}var A = 1"$'\n' "${P}"$'/* doc */\nvar A = 1\n' M core/x/s.go +expect_kind 1 "DOCS: reorder" DOCS "${P}func f() { u(); p() }"$'\n' "${P}func f() { p(); u() }"$'\n' M core/x/s.go +expect_kind 1 "DOCS: build constraint comment" DOCS "$P" $'//go:build never\n\npackage x\n' M core/x/s.go +expect_kind 1 "DOCS: rune quote then // in a string" DOCS "${P}var _ = f('\"', \"http://a\")"$'\n' "${P}var _ = f('\"', \"http://b\")"$'\n' M core/x/s.go +expect_kind 1 "DOCS: line inside a raw string" DOCS "${P}var s = \`a"$'\n'"curl http://old | sh"$'\n'"\`"$'\n' "${P}var s = \`a"$'\n'"curl http://new | sh"$'\n'"\`"$'\n' M core/x/s.go +expect_kind 1 "DOCS: spaces inside a string" DOCS "${P}var s = \"a b\""$'\n' "${P}var s = \"a b\""$'\n' M core/x/s.go +expect_kind 1 "DOCS: cgo preamble" DOCS "${P}// #include "$'\nimport "C"\n' "${P}// #include "$'\nimport "C"\n' M core/x/s.go +expect_kind 1 "DOCS: cgo preamble, grouped import" DOCS "${P}// #include "$'\nimport (\n\t"C"\n)\n' "${P}// #include "$'\nimport (\n\t"C"\n)\n' M core/x/s.go +expect_kind 1 "DOCS: Go changed, no blob" DOCS - - M core/x/s.go +expect_kind 1 "DOCS: a model under docs/spec" DOCS - - M docs/spec/X.tla +expect_kind 1 "DOCS: a non-docs, non-Go file" DOCS - - M deploy/x.env +expect_kind 0 "TEST: tests and testdata" TEST - - M core/x/s_test.go A core/x/testdata/in.bin +expect_kind 1 "TEST: production Go" TEST - - M core/x/s.go +expect_kind 0 "TEST: a runner scenario only" TEST - - A testops/scenarios/gate.yaml +expect_kind 0 "TEST: a scenario next to tests" TEST - - M testops/scenarios/gate.yaml M core/x/s_test.go +expect_kind 1 "TEST: a scenario next to production Go" TEST - - M testops/scenarios/gate.yaml M core/x/s.go +expect_kind 1 "TEST: a script beside the scenarios" TEST - - A testops/scenarios/run.sh +expect_kind 1 "TEST: a yaml outside testops/scenarios" TEST - - M testops/gate.yaml +expect_kind 0 "CI: workflow" CI - - M .github/workflows/w.yml +expect_kind 1 "CI: scripts/ is shipped" CI - - A scripts/install.sh +expect_kind 1 "DOCS next to another kind" "DOCS FIX INV-X-001" - - M docs/a.md + +# The workflow supplies its base-owned map as the third argument. +expect_map() { + local want=$1 name=$2 model=$3 got=0 + shift 3 + printf '%s\n%s\n' "${ok/Model: docs\/spec\/MaintenanceOwner.tla, exhausted/Model: $model}" "$simplest" >"$tmp/body" + if (($#)); then printf '%s\0' "$@"; fi | + bash "$check" "$tmp/body" "" "$tmp/map.tsv" >/dev/null 2>&1 || got=$? + if [[ $got != "$want" ]]; then + echo "FAIL $name: exit $got, want $want" + fail=1 + fi +} +printf 'core/x/s.go\tEngineAdapter.Begin\ncore/y/s.go\tMoveAdmission.Revoke\n' >"$tmp/map.tsv" +expect_map 0 "mapped action" "EngineAdapter.Begin" M core/x/s.go +expect_map 0 "mapped pure function" "NONE (pure function of EngineAdapter)" M core/x/s.go +expect_map 0 "all mapped modules cited" "EngineAdapter.Begin; MoveAdmission.Revoke" M core/x/s.go M core/y/s.go +expect_map 1 "mapped file rejects old prose" "docs/spec/EngineAdapter.tla, exhausted" M core/x/s.go +expect_map 1 "deleted mapped file still needs model" "NONE: deletion has no new code" D core/x/s.go +expect_map 1 "one citation cannot cover another module" "EngineAdapter.Begin" M core/x/s.go M core/y/s.go +expect_map 0 "unmapped file keeps old policy" "docs/spec/EngineAdapter.tla, exhausted" M core/z/s.go +printf '# no canonical rows yet\n' >"$tmp/map.tsv" +expect_map 2 "empty map is not silently disabled" "EngineAdapter.Begin" M core/x/s.go + +[[ $fail == 0 ]] && echo "spec-trace self-test: ok" +exit $fail diff --git a/seaweed-block/.github/scripts/spec-trace-check.sh b/seaweed-block/.github/scripts/spec-trace-check.sh new file mode 100644 index 0000000000..89fe207e5d --- /dev/null +++ b/seaweed-block/.github/scripts/spec-trace-check.sh @@ -0,0 +1,171 @@ +#!/usr/bin/env bash +# Usage: spec-trace-check.sh BODY_FILE [BLOBS] [MODEL_MAP] < changes +# +# Checks the spec trace in a PR description. changes are NUL-separated +# STATUS, PATH pairs (post-merge-review-changed.sh). +# +# - Feature:, Machine/INV:, Model: and Red-first: each start a line (after +# optional indentation, a list marker or bold) and carry a value that is not +# a template placeholder; "NONE:" needs a reason of at least 10 characters. +# - Machine/INV: starts with exactly one PR kind: "IMPL .", +# "FIX ", "CHANGE ", or one of the kinds a PR that changes +# no behaviour may use, each checked against what it changes: +# DOCS (docs outside docs/spec/, tests, and non-test Go whose tokens are +# unchanged: BLOBS holds old/ and new/ for each changed non-test +# Go file, compared by sametokens.go), TEST (only tests, testdata, test +# helpers and runner scenarios, testops/scenarios/*.yaml), CI (only +# .github/). NONE is not a kind. Known limit: a docs file that is +# go:embed-ed into a binary changes behaviour under DOCS (none today). +# - Simplest: (20+ characters) is present when the PR adds, modifies or +# deletes non-test Go under core/ or cmd/. +# +# Prints every problem and exits 1 if there is one; exits 0 if none, 2 on a +# usage error or a malformed change list. +set -euo pipefail + +body_file=${1:?usage: spec-trace-check.sh BODY_FILE [BLOBS] < changes} +blobs=${2-} +model_map=${3-} +here=$(cd "$(dirname "$0")" && pwd) +[[ -f $body_file ]] || { echo "spec-trace: body file $body_file missing" >&2; exit 2; } +body=$(tr -d '\r' <"$body_file") + +# value KEY: the text after KEY on the first line that starts with KEY, +# trimmed. A key inside another word ("Not-Feature:") does not count. +value() { + local line + line=$(printf '%s\n' "$body" | grep -m1 -E "^[[:space:]]*([-*][[:space:]]+)?(\*\*)?$1" || true) + [[ -n $line ]] || return 0 + line=${line#*"$1"} + line=${line#\*\*} + line=${line#"${line%%[![:space:]]*}"} + printf '%s' "${line%"${line##*[![:space:]]}"}" +} + +bad=0 +problem() { echo "spec-trace: $1"; bad=1; } + +# Each trace line is declared once: a second Machine/INV line could carry a +# second kind past the check. +for key in Feature: Machine/INV: Model: Red-first: Simplest:; do + n=$(printf '%s\n' "$body" | grep -cE "^[[:space:]]*([-*][[:space:]]+)?(\*\*)?$key" || true) + ((n <= 1)) || problem "$key is declared $n times; declare it once" +done + +for key in Feature: Machine/INV: Model: Red-first:; do + v=$(value "$key") + if [[ -z $v ]]; then + problem "missing or empty $key" + elif [[ $v == '<'* ]]; then + problem "$key still holds the template placeholder" + elif [[ $v == NONE:* ]]; then + r=${v#NONE:} + r=${r#"${r%%[![:space:]]*}"} + ((${#r} >= 10)) || problem "$key NONE needs a reason of at least 10 characters" + fi +done + +# One kind token, ending at the line end, a space, a comma or a slash. +end='($|[[:space:],/])' +kind_re="^(IMPL [A-Za-z0-9_]+[.][A-Za-z0-9_>.-]+|FIX INV-[A-Z0-9]+(-[A-Z0-9]+)*|CHANGE [A-Za-z0-9_]+|DOCS|TEST|CI)$end" +kind="" +mi=$(value Machine/INV:) +if [[ -n $mi && $mi != '<'* ]]; then + if [[ ! $mi =~ $kind_re ]]; then + problem "Machine/INV: must start with IMPL ., FIX , CHANGE , DOCS, TEST or CI" + else + token=${BASH_REMATCH[1]} + if [[ ${mi#"${BASH_REMATCH[0]}"} =~ (^|[^A-Za-z0-9_])(IMPL|FIX|CHANGE|DOCS|TEST|CI)([^A-Za-z0-9_]|$) ]]; then + problem "Machine/INV: names more than one kind; a PR is exactly one kind" + else + kind=${token%% *} + fi + fi +fi + +# A runner scenario under testops/scenarios/ is a test definition. +is_test() { [[ $1 == *_test.go || $1 == testdata/* || $1 == */testdata/* || $1 == */testutil/* || $1 == testops/scenarios/*.yaml ]]; } +# docs/spec holds the models: changing one is not a docs change. +is_doc() { [[ $1 != docs/spec/* ]] && [[ $1 == *.md || $1 == docs/* ]]; } +core=0 +paths=() +while IFS= read -r -d '' status; do + [[ $status == [ADMT] ]] || { echo "spec-trace: malformed change list: status ${status@Q}" >&2; exit 2; } + IFS= read -r -d '' path || { echo "spec-trace: malformed change list: status $status without a path" >&2; exit 2; } + [[ -n $path ]] || { echo "spec-trace: malformed change list: empty path" >&2; exit 2; } + paths+=("$path") + if [[ $path == core/*.go || $path == cmd/*.go ]] && [[ $path != *_test.go ]]; then + core=1 + fi +done +# A record cut off before its NUL is malformed, not skipped. +[[ -z ${status-} ]] || { echo "spec-trace: malformed change list: unterminated record" >&2; exit 2; } +if [[ -n $model_map ]]; then + model_status=0 + { if ((${#paths[@]})); then printf '%s\0' "${paths[@]}"; fi; } | + "${PYTHON:-python3}" -B "$here/model-trace-check.py" "$model_map" "$(value Model:)" || model_status=$? + case $model_status in + 0) ;; + 1) bad=1 ;; + *) exit "$model_status" ;; + esac +fi +if ((core)); then + s=$(value Simplest:) + if ((${#s} < 20)) || [[ $s == '<'* ]]; then + problem "Simplest: (20+ characters) is required when non-test Go under core/ or cmd/ changes" + fi +fi + +case $kind in +CI) + for p in ${paths[@]+"${paths[@]}"}; do + [[ $p == .github/* ]] || problem "kind CI: $p is outside .github/ (scripts/ holds shipped install and deploy scripts)" + done + ;; +TEST) + for p in ${paths[@]+"${paths[@]}"}; do + is_test "$p" || problem "kind TEST: $p is not a test, testdata or test helper" + done + ;; +DOCS) + gofiles=() + for p in ${paths[@]+"${paths[@]}"}; do + if is_doc "$p" || is_test "$p"; then continue; fi + if [[ $p == *.go ]]; then gofiles+=("$p"); continue; fi + problem "kind DOCS: $p is neither docs, a test, nor Go" + done + if ((${#gofiles[@]})); then + if [[ -z $blobs || ! -d $blobs ]]; then + problem "kind DOCS: non-test Go changed but no old/new blobs were given to compare" + else + # Built here, not run with "go run": that would take the .go + # arguments as more source files of the program. + bin=$(mktemp -d) + trap 'rm -rf "$bin"' EXIT + if ! go build -o "$bin/sametokens" "$here/sametokens.go"; then + echo "spec-trace: could not build sametokens.go; the DOCS check did not run" >&2 + exit 2 + fi + for p in "${gofiles[@]}"; do + if [[ ! -e $blobs/old/$p && ! -e $blobs/new/$p ]]; then + problem "kind DOCS: $p has no old or new blob, so it was not compared" + continue + fi + rc=0 + "$bin/sametokens" "$blobs/old/$p" "$blobs/new/$p" >/dev/null || rc=$? + case $rc in + 0) ;; + 1) problem "kind DOCS: $p changes more than comments (its Go tokens differ)" ;; + *) + echo "spec-trace: sametokens failed on $p (exit $rc); the DOCS check did not run" >&2 + exit 2 + ;; + esac + done + fi + fi + ;; +esac + +exit $bad diff --git a/seaweed-block/.github/workflows/known-bugs.yml b/seaweed-block/.github/workflows/known-bugs.yml new file mode 100644 index 0000000000..0d3e03c6ec --- /dev/null +++ b/seaweed-block/.github/workflows/known-bugs.yml @@ -0,0 +1,66 @@ +name: Known bugs + +# Nightly: every open-issue reproduction that is skipped by default (t.Skip unless +# SEAWEED_KNOWN_BUGS=1) runs and is EXPECTED TO FAIL. If one passes, its bug is +# fixed but its skip is still in place: this job fails and names it, so the skip +# is removed in the fix PR (or right after). A fix PR removes the test's line here +# together with its skip. +on: + schedule: + - cron: "17 6 * * *" + workflow_dispatch: + +permissions: + contents: read + +jobs: + known-bugs: + name: known-bug reproductions still fail + runs-on: tp04-seaweed-block + timeout-minutes: 15 + env: + CGO_ENABLED: "0" + SEAWEED_KNOWN_BUGS: "1" + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + + - name: Runner disk is NVMe + # A self-hosted runner whose work, temp or Go cache directory sits on a + # SATA system disk times the process-level tests out under disk load; + # this names the runner and stops the job before it starts. + if: runner.environment == 'self-hosted' + run: | + bash .github/scripts/require-nvme-test.sh + bash .github/scripts/require-nvme.sh "$GITHUB_WORKSPACE" "$RUNNER_TEMP" "${TMPDIR:-/tmp}" "${GOCACHE:-$HOME/.cache/go-build}" + + - name: Set up Go + uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version-file: go.mod + cache: false + + - name: Each reproduction still fails + run: | + set -u + ok=1 + while read -r issue pkg test; do + [ -n "$issue" ] || continue + if go test -count=1 -run "^${test}\$" "$pkg" > "out-${test}.txt" 2>&1; then + echo "::error::${test} (${pkg}) now PASSES: ${issue} looks fixed, remove its skip" + ok=0 + elif grep -q "^--- FAIL: ${test} " "out-${test}.txt"; then + echo "${test} (${issue}) still fails, as expected" + else + echo "::error::${test} (${pkg}) did not run or failed to build:"; tail -20 "out-${test}.txt" + ok=0 + fi + done <<'LIST' + #186 ./cmd/blockmaster/ TestChartOptInLoopbackFlagIsAcceptedByBlockmaster + #187 ./cmd/blockmaster/ TestChartDefaultAuthorityStateSurvivesPodReplacement + #188 ./core/ops/ TestDeleteSafety_UntimedCleanupCannotProveFreshness + #189 ./core/storage/ TestMultiBlockRecordsRequireDistinctOnDiskImplVersion + LIST + [ "$ok" = 1 ] diff --git a/seaweed-block/.github/workflows/post-merge-review.yml b/seaweed-block/.github/workflows/post-merge-review.yml new file mode 100644 index 0000000000..de5bc638ec --- /dev/null +++ b/seaweed-block/.github/workflows/post-merge-review.yml @@ -0,0 +1,56 @@ +name: post-merge-review paths + +# A PR labelled "post-merge-review" may merge before its full review only if +# every changed file is allowed by .github/post-merge-review-allow.txt. +# This check fails such a PR otherwise; without the label it passes. +# +# pull_request_target: the workflow, the allow list and the script all come +# from the base branch, so a PR cannot change its own check. The PR's code is +# never checked out or run: only its commit is fetched, for the file list. +on: + pull_request_target: + # edited: a retarget changes the base, and with it the diff. + types: [opened, synchronize, reopened, labeled, unlabeled, edited] + +permissions: + contents: read + +concurrency: + group: post-merge-review-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + paths: + name: post-merge-review paths + # GitHub-hosted: on the self-hosted runners this job ended in 'Set up + # job' with no log on every runner (2026-11-29), while spec trace, on the + # same runners, passes. Unlabelled PRs only echo here, so the hosted + # queue costs little; the merge gate does not wait for it unless the PR + # is labelled. + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Not labelled + if: ${{ !contains(github.event.pull_request.labels.*.name, 'post-merge-review') }} + run: echo "no post-merge-review label; nothing to check" + + - name: Checkout base + if: ${{ contains(github.event.pull_request.labels.*.name, 'post-merge-review') }} + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ github.event.pull_request.base.sha }} + fetch-depth: 0 + persist-credentials: false + + - name: Check changed paths + if: ${{ contains(github.event.pull_request.labels.*.name, 'post-merge-review') }} + env: + BASE: ${{ github.event.pull_request.base.sha }} + HEAD: ${{ github.event.pull_request.head.sha }} + PR: ${{ github.event.pull_request.number }} + run: | + set -euo pipefail + bash .github/scripts/post-merge-review-check-test.sh + git -c fetch.fsckObjects=true fetch --no-tags origin "+refs/pull/${PR}/head:refs/remotes/pr/head" + bash .github/scripts/post-merge-review-changed.sh "$BASE" "$HEAD" >changed.bin + bash .github/scripts/post-merge-review-check.sh .github/post-merge-review-allow.txt &2 + exit 1 + fi + stable=false + move_alpha=false + if [[ "${version}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + stable=true + highest="$(git tag -l 'v*' | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -n 1)" + if [[ "${version}" == "${highest}" ]]; then + move_alpha=true + fi + fi + { + echo "block_tags<> "$GITHUB_OUTPUT" + + - name: Build and push block image + uses: docker/build-push-action@v6 + with: + context: . + file: deploy/k8s/g15b/Dockerfile.sw-block + push: true + tags: ${{ steps.tags.outputs.block_tags }} + + - name: Build and push CSI image + uses: docker/build-push-action@v6 + with: + context: . + file: deploy/k8s/g15b/Dockerfile.blockcsi + push: true + tags: ${{ steps.tags.outputs.csi_tags }} diff --git a/seaweed-block/.github/workflows/spec-trace.yml b/seaweed-block/.github/workflows/spec-trace.yml new file mode 100644 index 0000000000..25fe922ae8 --- /dev/null +++ b/seaweed-block/.github/workflows/spec-trace.yml @@ -0,0 +1,88 @@ +name: spec trace + +# Every PR description carries the spec trace (see the PR template); this +# check fails a PR whose description does not. +# +# pull_request_target: the workflow and the script come from the base branch, +# so a PR cannot change its own check. The PR's code is never checked out or +# run: only its commit is fetched, for the file list. The description is read +# from the event through an environment variable, never interpolated. +on: + pull_request_target: + # edited: the check reads the description and the base. + types: [opened, synchronize, reopened, edited] + +permissions: + contents: read + +concurrency: + group: spec-trace-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + trace: + name: spec trace + # A PR from a branch of this repository runs on the team's self-hosted + # runners: the GitHub-hosted queue is shared with the whole organization, + # where this five-minute check waited behind other repositories' jobs. + # pull_request_target starts for any PR without approval, so a PR from a + # fork keeps a throw-away GitHub-hosted machine. No PR code is checked + # out or run on either. + runs-on: ${{ github.event.pull_request.head.repo.full_name == github.repository && 'tp04-seaweed-block' || 'ubuntu-latest' }} + timeout-minutes: 5 + steps: + - name: Checkout base + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + # github.sha is the tip of the base branch when the event fires; the + # PR's base.sha can predate this workflow's own scripts. + ref: ${{ github.sha }} + fetch-depth: 0 + persist-credentials: false + + # spec-trace-check.sh builds the trusted sametokens.go; a self-hosted + # runner has no Go on its PATH unless the job sets it up. + - name: Set up Go + uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version-file: go.mod + cache: false + + - name: Check spec trace + env: + BASE: ${{ github.event.pull_request.base.sha }} + HEAD: ${{ github.event.pull_request.head.sha }} + PR: ${{ github.event.pull_request.number }} + BODY: ${{ github.event.pull_request.body }} + TITLE: ${{ github.event.pull_request.title }} + run: | + set -euo pipefail + bash .github/scripts/spec-trace-check-test.sh + python3 -B .github/scripts/model-trace-check-test.py + bash .github/scripts/changed-go-blobs-test.sh + # fsckObjects: a PR's objects are checked as they arrive, so a tree + # with a '..' or '.git' entry is refused here. + git -c fetch.fsckObjects=true fetch --no-tags origin "+refs/pull/${PR}/head:refs/remotes/pr/head" + printf '%s' "$BODY" >body.txt + bash .github/scripts/post-merge-review-changed.sh "$BASE" "$HEAD" >changed.bin + # Old and new blobs of each changed non-test Go file, for kind DOCS + # (objects only; a path that would leave blobs/ is refused). + mb=$(git merge-base "$BASE" "$HEAD") + bash .github/scripts/changed-go-blobs.sh "$mb" "$HEAD" blobs + # Mapping and validator come from the trusted base checkout above. + bash .github/scripts/spec-trace-check.sh body.txt blobs .github/model-code-trace.tsv title.txt + bash .github/scripts/public-text-check.sh "$mb" "$HEAD" title.txt body.txt + + - name: Invariants ledger anchors (report only) + # Every code and test anchor of docs/design/invariants.md must exist at + # the PR's commit (git objects only; nothing from the PR is run). It + # reports and does not fail the check while the known imprecise + # anchors are being corrected; then this step becomes gating. + continue-on-error: true + env: + HEAD: ${{ github.event.pull_request.head.sha }} + run: python3 -I .github/scripts/ledger_check.py . "$HEAD" || true diff --git a/seaweed-block/.github/workflows/test.yml b/seaweed-block/.github/workflows/test.yml new file mode 100644 index 0000000000..2fc36d0531 --- /dev/null +++ b/seaweed-block/.github/workflows/test.yml @@ -0,0 +1,350 @@ +name: Test + +on: + pull_request: + # ready_for_review: a Draft runs no Go suite (below); marking it ready starts one. + types: [opened, synchronize, reopened, ready_for_review] + push: + branches: + - main + +permissions: + contents: read + +# One run per PR (or per branch for pushes). A new push to a PR cancels the +# superseded run; runs on main are never cancelled so every merge gets a result. +concurrency: + group: test-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + test: + # One job, two suites, one runner selection. 'unit' is the Go suite below; + # 'process' runs the process-level tests: real blockmaster, blockvolume and + # sw-block against a pinned SeaweedFS release. Those tests are named in + # .github/process-level-tests.txt, and every one must PASS, so a test that + # skips, fails, never starts or is cut off by the timeout fails the suite. + # Tests that need root or systemd are not in the list (see its header). + strategy: + fail-fast: false + matrix: + suite: [unit, process] + name: ${{ matrix.suite == 'unit' && 'go test (linux)' || 'process-level tests (real binaries)' }} + # The suite writes heavily to the runner disk (real files, fsync), so a + # Draft PR skips it; its author tests locally until the PR is ready. + if: github.event_name == 'push' || !github.event.pull_request.draft + # Pull requests run on GitHub-hosted runners (free for this public repo, many + # jobs in parallel); pushes to main keep the team's tp04 runner (seaweed.slice, + # capped at 8 cores / 8 GiB) as the self-hosted signal. A train PR (branch + # train/* of this repository, a few a day) also runs on the team's runners: + # it is the merge gate, and the organization's shared GitHub-hosted queue held + # it 30-55 minutes before it started. A PR from a fork never runs there. + runs-on: ${{ (github.event_name == 'push' || (github.event.pull_request.head.repo.full_name == github.repository)) && 'tp04-seaweed-block' || 'ubuntu-latest' }} + # process: 44 tests in 4 parallel shards of about 13 min each (55 min in sequence). + timeout-minutes: ${{ matrix.suite == 'unit' && 40 || 90 }} + env: + # Pure-Go build: no package in the default build needs cgo, and the + # hosted runner should not depend on a C toolchain being present. + CGO_ENABLED: "0" + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + # Two commits: the PR merge commit and its base parent, so the test + # step can see which packages the PR touches. + fetch-depth: 2 + + - name: Runner disk is NVMe + # A self-hosted runner whose work, temp or Go cache directory sits on a + # SATA system disk times the process-level tests out under disk load; + # this names the runner and stops the job before it starts. + if: runner.environment == 'self-hosted' + run: | + bash .github/scripts/require-nvme-test.sh + bash .github/scripts/require-nvme.sh "$GITHUB_WORKSPACE" "$RUNNER_TEMP" "${TMPDIR:-/tmp}" "${GOCACHE:-$HOME/.cache/go-build}" + + - name: Start whole-job load evidence + # Begins after checkout, before toolchain setup/build/tests. No host + # installation or privileged reads. A job-sized lifetime also bounds + # the sampler if cancellation prevents the stop step. + continue-on-error: true + env: + CI_EVIDENCE_DIR: ${{ runner.temp }}/ci-${{ matrix.suite }}-${{ github.run_id }}-${{ github.run_attempt }} + run: | + echo "CI_EVIDENCE_DIR=$CI_EVIDENCE_DIR" >>"$GITHUB_ENV" + mkdir -p "$CI_EVIDENCE_DIR" + : >"$CI_EVIDENCE_DIR/go-test.json" + python3 -I .github/scripts/ci-load.py start "$CI_EVIDENCE_DIR/load.tsv" --duration ${{ matrix.suite == 'unit' && 2400 || 5400 }} + + - name: Self-test evidence capture + run: | + python3 -B .github/scripts/ci-load-test.py + bash .github/scripts/record-go-test-test.sh + + - name: Docs-only pull request + id: scope + if: matrix.suite == 'process' && github.event_name == 'pull_request' + # A pull request that changes only files under docs/ runs no product + # code the process-level tests could exercise, so they are skipped and + # the job still reports success. HEAD is the merge commit, HEAD^1 its + # base parent (fetch-depth 2 above). Pushes to main always run them, and + # so does any error of the check (.github/scripts/docs-only-scope.sh). + run: | + set -euo pipefail + bash .github/scripts/docs-only-scope-test.sh + if out=$(bash .github/scripts/docs-only-scope.sh HEAD^1 HEAD); then + case $out in + "docs_only "*) + echo "skipped: docs only (${out#docs_only } files under docs/); the process-level tests run on the merge to main" + echo "docs_only=1" >>"$GITHUB_OUTPUT" ;; + *) echo "process-level tests run: $out" ;; + esac + else + echo "process-level tests run: the docs-only check failed" + fi + + - name: Set up Go + uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version-file: go.mod + # The self-hosted runner keeps GOCACHE/GOMODCACHE on its own disk; + # uploading them as an Actions cache (~4 GB) in the post step + # outlasted the job timeout after every test had passed. Only the + # GitHub-hosted (fork PR) runner uses the Actions cache. + cache: ${{ runner.environment == 'github-hosted' }} + cache-dependency-path: go.sum + + - name: Go version + if: matrix.suite == 'unit' + run: go version + + - name: Build + if: matrix.suite == 'unit' + run: go build ./... + + - name: Vet + if: matrix.suite == 'unit' + run: go vet ./... + + - name: Lab build tags stay out of images and releases + if: matrix.suite == 'unit' + # swblock_lab_bigvol lifts the 1 TiB create cap and the local + # headroom refusal for scale rehearsals only; swblock_v11_format turns + # on the draft v1.1 store format. The default test run pins the + # release cap (TestReleaseBuildKeepsTheCreateCap) and the release + # format. This step checks the tags' allowlist and that every image + # Dockerfile refuses a lab binary (scripts/refuse-lab-binary.sh) after + # its build, with controls, then tests each tag alone and both. + run: | + set -euo pipefail + bash .github/scripts/lab-tag-check.sh . + bash .github/scripts/lab-tag-check-test.sh + for tags in swblock_lab_bigvol swblock_v11_format swblock_lab_bigvol,swblock_v11_format; do + go vet -tags "$tags" ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ ./core/storage/ + bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -tags "$tags" -run 'Lab|Headroom|Revision|LegacyBound' ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ + bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -tags "$tags" -run 'TestV11FormatFollowsItsOwnTagAlone' ./core/storage/ + done + + - name: Test default configuration + if: matrix.suite == 'unit' + # The runner disk is shared, so the long, disk-heavy, timing-sensitive + # packages do not run here on main or on train PRs: every train runs the + # whole suite (both configurations) on a separate test VM before it + # merges, and main moves only by those trains. A PR runs the light set + # plus every heavy package its own diff touches. + env: + EVENT: ${{ github.event_name }} + HEAD_REF: ${{ github.head_ref }} + run: | + set -euo pipefail + pkgs=$(go list ./... | grep -vE '/core/(storage|frontend/durable|host/master|authority)$') + if [ "$EVENT" != push ] && [[ "$HEAD_REF" != train/* ]]; then + mod=$(go list -m) + changed=$(git diff --name-only HEAD^1 HEAD) + for p in core/storage core/frontend/durable core/host/master core/authority; do + if printf '%s\n' "$changed" | grep -qE "^$p/[^/]+$"; then + pkgs="$pkgs $mod/$p" + fi + done + fi + # 20m per package: core/storage alone took 602 s on tp04 on main + # (2026-11-22), past the old 10m, so any PR touching it failed. + bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -p=1 -short -count=1 -timeout 20m $pkgs + + - name: Format v3 tagged tests + if: matrix.suite == 'unit' + # The swblock_format_v3_test tests of the four packages that carry them. + # Five durable tests are skipped by name: each installs a BASE on a chunk + # store, which no production path does (its invariant row is DORMANT); + # they are rewritten at the start of the next release, then this skip + # goes. + run: | + set -euo pipefail + skip='^(TestDurableProviderV3_AttachesCompletedChunkBASE|TestDurableProviderV3_CompletedBASEDoesNotRestoreOlderHEAD|TestDurableProviderV3_DefersBASERetirementUntilLocalPresence|TestDurableProviderV3_FreshMarkerCrashKeepsCompletedBASE|TestDurableProviderV3_FreshMarkerCaptureCrashKeepsCompletedBASE)$' + bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -p=1 -count=1 -timeout 20m -tags swblock_format_v3_test -skip "$skip" \ + ./core/frontend/durable/ ./core/recovery/ ./core/replication/ ./core/transport/ + + - name: Self-test of the required-tests gate + if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1' + # The gate must fail on a skip, a failure, a test that never ran, one + # cut off mid-run, and one that reports PASS and then exits nonzero or + # hangs; this proves it before it judges the real run. + run: | + python3 -I .github/scripts/required-tests-check-test.py + bash .github/scripts/chunkstore-scope-test.sh + bash .github/scripts/run-named-tests-test.sh + python3 -I .github/scripts/shard-named-tests-test.py + + - name: Pinned SeaweedFS + if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1' + # The release archive is checked against its sha256 before every use, + # also when taken from the runner's cache; a mismatch fails the step. + # Nothing else is fetched. + env: + WEED_VERSION: "4.53" + WEED_SHA256: d1a7dec9f48d8b33895a0ea8951971defc2dc5312906dcc76fa5a5f74a6ee90d + run: | + set -euo pipefail + cache="${RUNNER_TOOL_CACHE:-$RUNNER_TEMP}/seaweedfs-weed/$WEED_VERSION" + tgz="$cache/linux_amd64.tar.gz" + mkdir -p "$cache" + if ! echo "$WEED_SHA256 $tgz" | sha256sum -c --status - 2>/dev/null; then + part="$tgz.$$.part" + curl -fsSL --retry 3 -o "$part" "https://github.com/seaweedfs/seaweedfs/releases/download/$WEED_VERSION/linux_amd64.tar.gz" + echo "$WEED_SHA256 $part" | sha256sum -c - || { rm -f "$part"; exit 1; } + mv -f "$part" "$tgz" + fi + bin="$RUNNER_TEMP/weed-$WEED_VERSION" + mkdir -p "$bin" + tar -xzf "$tgz" -C "$bin" weed + echo "CHUNKSTORE_WEED=$bin/weed" >>"$GITHUB_ENV" + + - name: Real-filer integration tests + if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1' + # The chunkstore_integration tests run against the pinned weed above + # (master, volume and filer as real processes): the conditional HEAD + # writes, cut uploads and object deletes of the chunk store, and the + # layout sync crash cases of the durable provider. They fail, never + # skip, without the binary. Pushes to main and train PRs always run + # them; another PR runs them when it touches core/frontend/chunkstore/, + # core/storage/ or core/frontend/durable/. + env: + EVENT: ${{ github.event_name }} + HEAD_REF: ${{ github.head_ref }} + # .github/scripts/chunkstore-scope.sh decides; an error of that check + # runs the tests. Each filtered run must PASS at least one test, so a + # filter that matches nothing fails instead of passing empty. + run: | + set -euo pipefail + if [ "$EVENT" != push ] && [[ "$HEAD_REF" != train/* ]]; then + if out=$(bash .github/scripts/chunkstore-scope.sh HEAD^1 HEAD); then + case $out in + "skip "*) echo "skipped: the PR touches neither core/frontend/chunkstore/ nor core/storage/ ($out)"; exit 0 ;; + *) echo "real-filer integration tests run: $out" ;; + esac + else + echo "real-filer integration tests run: the scope check failed" + fi + fi + for spec in "./core/frontend/chunkstore/ ^TestIntegration" "./core/frontend/durable/ ^TestQD1LayoutSync"; do + pkg=${spec%% *}; filter=${spec#* } + log="$RUNNER_TEMP/integration-$(basename "$pkg").log" + bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -v -timeout 20m -tags chunkstore_integration -run "$filter" "$pkg" 2>&1 | tee "$log" + grep -q '^--- PASS: ' "$log" || { echo "no test of $pkg matched $filter"; exit 1; } + done + + - name: Build the binaries and the test binary once + if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1' + run: | + set -euo pipefail + bins="$RUNNER_TEMP/swblock-bins" + mkdir -p "$bins" + for b in blockmaster blockvolume sw-block; do go build -o "$bins/$b" "./cmd/$b"; done + go test -c -tags 'subprocess chunkstore_integration' -o "$bins/blockvolume.test" ./cmd/blockvolume + go test -c -o "$bins/blockcsi.test" ./cmd/blockcsi + # The known-zero acceptance's first-start crash step holds a test-only + # blockvolume (build tag kzhold, never released) at a chosen point. + go build -tags kzhold -o "$RUNNER_TEMP/blockvolume-kzhold" ./cmd/blockvolume + echo "SWBLOCK_TEST_BINS=$bins" >>"$GITHUB_ENV" + echo "KZ_HOLD_BIN=$RUNNER_TEMP/blockvolume-kzhold" >>"$GITHUB_ENV" + + - name: Run the named process-level tests + if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1' + # Each named test in its own process of the one test binary, in + # sequence, so a panic or a hang in one cannot hide the others; each + # is bounded (TEST_TIMEOUT, then killed) and its exit status is kept: + # the gate needs a PASS event AND exit 0 for every named test. The known-zero acceptance + # runs its small shape (1 GiB, user-space client, no device); the + # 1 TiB run is lab only. + env: + KZ_RUN: "1" + KZ_SIZE: 1G + F1_RUN: "1" + TEST_TIMEOUT: 15m + # A failed test copies each daemon's whole log here (keepFullLog); + # the step below keeps them as the run's artifact. + SWBLOCK_TEST_LOG_DIR: ${{ env.CI_EVIDENCE_DIR }}/daemon-logs + run: | + set -euo pipefail + # SHARDS parallel shards, balanced by their last measured times + # (.github/process-level-seconds.txt). Each shard is its own sequence + # of test processes with its own slice of the test port ranges + # (SWBLOCK_TEST_PORT_SHARD) and its own TMPDIR; the gate judges every + # named test from all the shards together. + names=.github/process-level-tests.txt + # The manifest tags CSI entries; every other name uses blockvolume.test. + # The final checker still requires the complete, unsplit manifest. + awk '!/# package=blockcsi/' "$names" > "$RUNNER_TEMP/blockvolume-names.txt" + awk '/# package=blockcsi/ {sub(/#.*/, ""); if ($0 ~ /[^[:space:]]/) print}' "$names" > "$RUNNER_TEMP/blockcsi-names.txt" + test -s "$RUNNER_TEMP/blockcsi-names.txt" + shards=4 + python3 -I .github/scripts/shard-named-tests.py "$RUNNER_TEMP/blockvolume-names.txt" .github/process-level-seconds.txt "$shards" "$RUNNER_TEMP/shard" + pids=() + for k in $(seq 1 "$shards"); do + mkdir -p "$RUNNER_TEMP/tmp-$k" + SWBLOCK_TEST_PORT_SHARD=$k SWBLOCK_TEST_PORT_SHARDS=$shards TMPDIR="$RUNNER_TEMP/tmp-$k" \ + bash .github/scripts/run-named-tests.sh "$SWBLOCK_TEST_BINS/blockvolume.test" "$RUNNER_TEMP/shard/$k.txt" \ + "$RUNNER_TEMP/process-level-$k.json" "$RUNNER_TEMP/process-level-$k.status" "$TEST_TIMEOUT" cmd/blockvolume \ + >"$RUNNER_TEMP/process-level-$k.log" 2>&1 & + pids+=($!) + done + for p in "${pids[@]}"; do wait "$p" || true; done + for k in $(seq 1 "$shards"); do sed "s/^/[shard $k] /" "$RUNNER_TEMP/process-level-$k.log"; done + # CSI uses the same per-case isolation, timeout and verdict as the shards. + TEST_PKG=github.com/seaweedfs/seaweed-block/cmd/blockcsi \ + bash .github/scripts/run-named-tests.sh "$SWBLOCK_TEST_BINS/blockcsi.test" "$RUNNER_TEMP/blockcsi-names.txt" \ + "$RUNNER_TEMP/process-level-csi.json" "$RUNNER_TEMP/process-level-csi.status" "$TEST_TIMEOUT" cmd/blockcsi \ + >"$RUNNER_TEMP/process-level-csi.log" 2>&1 || true + cat "$RUNNER_TEMP/process-level-csi.log" + cat "$RUNNER_TEMP"/process-level-*.status >"$RUNNER_TEMP/process-level.status" + python3 -I .github/scripts/required-tests-check.py --status "$RUNNER_TEMP/process-level.status" \ + "$names" "$RUNNER_TEMP"/process-level-*.json + + - name: Stop load evidence and collect raw process events + if: always() + continue-on-error: true + env: + SUITE: ${{ matrix.suite }} + run: | + if [ -z "${CI_EVIDENCE_DIR:-}" ]; then exit 0; fi + python3 -I .github/scripts/ci-load.py stop "$CI_EVIDENCE_DIR/load.tsv" || true + if [ "$SUITE" = process ]; then + mkdir -p "$CI_EVIDENCE_DIR/shards" + shopt -s nullglob + for file in "$RUNNER_TEMP"/process-level-*.json "$RUNNER_TEMP"/process-level-*.log "$RUNNER_TEMP"/process-level*.status; do + cp "$file" "$CI_EVIDENCE_DIR/shards/" + done + for file in "$CI_EVIDENCE_DIR"/shards/*.json; do cat "$file" >>"$CI_EVIDENCE_DIR/go-test.json"; done + fi + + - name: Keep failed-job tests, load, daemon logs and shard results + # Both suites retain timed events and whole-job load. Process evidence + # also retains the original shard receipts and full daemon logs. + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ci-${{ matrix.suite }}-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ env.CI_EVIDENCE_DIR }} + retention-days: 14 + if-no-files-found: warn diff --git a/seaweed-block/.gitignore b/seaweed-block/.gitignore new file mode 100644 index 0000000000..bd7441d732 --- /dev/null +++ b/seaweed-block/.gitignore @@ -0,0 +1,35 @@ +# Go toolchain caches (if GOCACHE/GOTMPDIR is pointed at the workspace) +.gocache/ +.gotmp/ + +# Built binaries at repo root (sparrow is a command; tests build their own +# transient copies). Anchored with / so these do NOT match the cmd/sparrow/ +# source directory's files. +/sparrow +/sparrow.exe + +# Test coverage artifacts +*.test +*.out +coverage.out + +# G5-5* cross-compile artifacts (m01 hardware iteration script +# stages binaries into _g5_bin/ before scp to the test host; root- +# level *.exe are Windows-side build outputs that go build leaves +# behind on iteration runs). +/_g5_bin/ +/blockmaster +/blockmaster.exe +/blockvolume +/blockvolume.exe + +# Local test runner outputs and ad-hoc Windows builds. Formal QA evidence lives +# under internal/docs/qa-assignments or external shared artifacts, not here. +/results/ +/sw-testops.exe + +# MkDocs engineering wiki build output +/site/ + +# Windows builds of the binaries (never committed) +/*.exe diff --git a/seaweed-block/AGENTS.md b/seaweed-block/AGENTS.md new file mode 100644 index 0000000000..dd02471cb0 --- /dev/null +++ b/seaweed-block/AGENTS.md @@ -0,0 +1,89 @@ +# Agent Guidelines + +Behavioral guidelines to reduce common LLM coding mistakes. Merge with +project-specific instructions as needed. + +Tradeoff: these guidelines bias toward caution over speed. For trivial tasks, +use judgment. + +## 1. Think Before Coding + +Do not assume. Do not hide confusion. Surface tradeoffs. + +Before implementing: + +- State assumptions explicitly. If uncertain, ask. +- If multiple interpretations exist, present them; do not pick silently. +- If a simpler approach exists, say so. Push back when warranted. +- If something is unclear, stop, name what is confusing, and ask. + +## 2. Simplicity First + +Minimum code that solves the problem. Nothing speculative. + +- No features beyond what was asked. +- No abstractions for single-use code. +- No flexibility or configurability that was not requested. +- No error handling for impossible scenarios. +- If 200 lines could be 50, rewrite it. + +Ask: would a senior engineer say this is overcomplicated? If yes, simplify. + +## 3. Surgical Changes + +Touch only what you must. Clean up only your own mess. + +When editing existing code: + +- Do not improve adjacent code, comments, or formatting. +- Do not refactor things that are not broken. +- Match existing style, even if you would do it differently. +- If you notice unrelated dead code, mention it; do not delete it. + +When your changes create orphans: + +- Remove imports, variables, and functions that your changes made unused. +- Do not remove pre-existing dead code unless asked. + +Every changed line should trace directly to the user's request. + +## 4. Goal-Driven Execution + +Define success criteria. Loop until verified. + +Transform tasks into verifiable goals: + +- "Add validation" -> "Write tests for invalid inputs, then make them pass." +- "Fix the bug" -> "Write a test that reproduces it, then make it pass." +- "Refactor X" -> "Ensure tests pass before and after." + +For multi-step tasks, state a brief plan: + +```text +1. [Step] -> verify: [check] +2. [Step] -> verify: [check] +3. [Step] -> verify: [check] +``` + +Strong success criteria let agents loop independently. Weak criteria such as +"make it work" require clarification. + +These guidelines are working if there are fewer unnecessary changes in diffs, +fewer rewrites due to overcomplication, and clarifying questions come before +implementation rather than after mistakes. + +## Protocol contract + +Seaweed Block's state machines and invariants are in +[`docs/design/invariants.md`](docs/design/invariants.md). Read it before +changing a protocol path: the storage engines, durability and `Sync`, +authority and epochs, replication and replica roles, the chunk layer and the +cut, the catalog, GC and volume delete, or the workspace lease. + +- Find the machine and transition (Part A) and the invariant IDs (Part B) + your change touches, and name them in the PR. +- Follow the change rules (Part C): a new or changed state or transition + updates Part A, the design-doc diagram, the ledger and the TLA+ spec that + covers it; an ACTIVE row never loses its test; a bug found by tests, soak + or TLA+ becomes a regression test plus a ledger row. +- Do not weaken a guard listed under "Enforced in" without updating its row. diff --git a/seaweed-block/LICENSE b/seaweed-block/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/seaweed-block/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/seaweed-block/README.md b/seaweed-block/README.md new file mode 100644 index 0000000000..ba25e41857 --- /dev/null +++ b/seaweed-block/README.md @@ -0,0 +1,308 @@ +# Seaweed Block + +[![tag](https://img.shields.io/github/v/tag/seaweedfs/seaweed-block?sort=semver&label=release)](docs/releases/v1.0.0.md) +[![CI](https://github.com/seaweedfs/seaweed-block/actions/workflows/test.yml/badge.svg)](https://github.com/seaweedfs/seaweed-block/actions/workflows/test.yml) +[![Go](https://img.shields.io/github/go-mod/go-version/seaweedfs/seaweed-block)](go.mod) +[![License](https://img.shields.io/github/license/seaweedfs/seaweed-block)](LICENSE) + +**Block storage for AI agent workspaces at local-disk speed, with snapshots, restore and moves backed by your own +[SeaweedFS](https://github.com/seaweedfs/seaweedfs).** Each sandbox or microVM gets a plain virtio block disk. Writes +and `fsync` complete on the host's local disk; cuts copy the changed data to SeaweedFS in the background. Losing the +host loses what was written since the last successful cut: normally about a day with the default schedule (one +snapshot a day), not a guaranteed bound; `--chunk-capture-interval` (5 minutes or more) cuts more often. The same core serves Kubernetes block volumes (alpha). + +

+ Seaweed Block. Write path: an agent sandbox or microVM writes over NVMe/TCP or iSCSI to blockvolume, which completes the write and fsync on its local WAL and acknowledges; a write does not wait on SeaweedFS, except that a restored volume fetches each chunk from its snapshot once, on its first read or write. Background path: a cut (by default one scheduled snapshot a day; periodic cuts are optional) uploads only the changed 4 MiB chunks to your SeaweedFS, then updates the HEAD root with a conditional update on generation and epoch. blockmaster issues epochs and leases. Snapshots name a root and share chunks; a restore reads the snapshot's chunks on first use; a move hands the volume to another host at a higher epoch, and a stale holder's update is refused. +

+ +**Branches.** `main` is v1.1 in development: it is not a release, and the store format it writes may change +before v1.1. Do not run it for data you keep. v1.0.x releases ship from the `release-1.0` branch. + +## Install + +The binaries are `blockmaster`, `blockvolume` and the `sw-block` CLI. The commands on this page are for v1.0.0. +**Option 1:** copy them from the v1.0.0 image, +`ghcr.io/seaweedfs/seaweed-block:v1.0.0` (index digest +`sha256:648980beb519a086349d44367e9d19ba6ae94b8939456ae3eb7b7bb5e4b3b28b`): + +```bash +docker create --name swb-extract ghcr.io/seaweedfs/seaweed-block:v1.0.0 +for b in blockmaster blockvolume sw-block; do docker cp swb-extract:/usr/local/bin/$b .; done +docker rm swb-extract && ./blockvolume --version +``` + +**Option 2:** build from the tag `v1.0.0` (the Go version in `go.mod`): +```bash +git clone --branch v1.0.0 https://github.com/seaweedfs/seaweed-block && cd seaweed-block +for b in blockmaster blockvolume sw-block; do go build -o $b ./cmd/$b; done +``` + +**Option 3:** Helm, see the [Kubernetes quick start](#quick-start-kubernetes-alpha). +Services: [standalone deployment](docs/standalone-deployment.md). Operator guide (supported setup, sizing, recovery point, host loss, limits): [operator guide](docs/operator-guide.md). + +## Try it + +The [first volume check](docs/standalone-deployment.md#first-volume-read-only-check) +starts `blockmaster` and one `blockvolume`, attaches a 256 MiB volume over +NVMe/TCP on loopback, shows the device and its status, and stops. It does +not format or write the attached device; it only creates local backing files +and logs. It needs Linux, bash, `nvme-cli`, `sudo` and the binaries +above. To format and write, use the [write test](docs/standalone-deployment.md#write-test-scratch-host-only) (scratch host only). + +### `sw-block mini` + +A trial on a scratch host, not for data you keep. One command starts a single-host +trial on loopback, with SeaweedFS's `weed mini` as the chunk store (run against SeaweedFS 4.53). Build all three +binaries from the same checkout and run the one you built, so that `mini` finds its matching `blockmaster` and +`blockvolume` next to it: + +```bash +git clone https://github.com/seaweedfs/seaweed-block && cd seaweed-block +for b in blockmaster blockvolume sw-block; do go build -o $b ./cmd/$b; done +./sw-block mini --dir ./swb-mini --weed /path/to/weed +``` + +It starts `weed mini`, `blockmaster` and one `blockvolume` (volume `v1`, 256 MiB, `walstore-chunk` with its chunk +control endpoint). Snapshots of `v1` work at once. A restore into a new volume is not possible inside a `mini` trial +yet: `mini`'s blockmaster is its own child and `mini` stops everything when a child exits, and that blockmaster +refuses a volume that is not in its one-volume cluster spec while its product loop is off. To restore today, use the +standalone setup +([restoring a snapshot](docs/standalone-deployment.md#restoring-a-snapshot-into-a-new-volume)). +It prints every command it runs and never runs `sudo`: it prints the `nvme connect` command that attaches `v1`, and +the status, check and snapshot commands. Before you stop it with Ctrl-C, unmount `v1` and run the +`sudo nvme disconnect` it printed. If no `weed` is found on `PATH` and `--weed` is not given, it starts the local +engine only, with no snapshots and a banner saying so; a `--weed` path that does not exist is refused. More in +[standalone deployment](docs/standalone-deployment.md#quick-start-sw-block-mini). + +## Why Seaweed Block + +- **Close to local-disk speed for agent work.** In a pre-release run on the `walstore` engine (the local engine the + released chunk path builds on), `npm ci`, `git clone` and untar ran within 0-4% of a local disk for the operation + itself. With the final file-system flush included on both sides, they were 11-23% slower than the local disk, and + untar of 5,000 small files took about 2.2 times as long. On the released path, `fsync` costs about + 1.3 times local ([measured results](#measured-results), [how each was measured](docs/workspace-measurements.md)). +- **`fsync` is durable on the host that serves the volume.** Every guest `fsync` reaches the host's disk; no write + cache is turned off to get the speed (a gate counts flushes against backend syncs, with an unsafe-cache control). + In fault injection on the release candidate (process kills and a store pause on one host; not a power-loss test), + 0 acknowledged writes were lost across 253 judged; the same runs failed other operation checks, listed with the + record. If the host itself is lost, the volume comes back from its last cut + ([records](docs/workspace-measurements.md)). +- **Snapshots in your object store.** A cut uploads only the changed 4 MiB chunks. A snapshot names a root of about + 2 KB and shares its chunks; a restore makes a new volume that reads them on first use + ([agent workspace design](docs/design/agent-workspace-design.md)). +- **Safe moves between hosts.** One blockmaster issues epochs and leases, and a holder admits I/O only while its own + lease is current; run exactly one blockmaster per cluster. Separately, every HEAD update is conditional on + `{gen, epoch}`, so the store refuses a stale holder's publish even before that holder notices it was replaced + ([volume lifecycle](docs/volume-lifecycle.md), [TLA+ specifications](docs/spec/README.md)). +- **Self-hosted.** Go, Apache-2.0, on your own hosts and your own SeaweedFS. +- **Against an early FUSE prototype on the same host** (host-side, built on the SeaweedFS filer; not a released + product), in the same pre-release run, untar, `npm ci` and `git clone` were 4 to 36 times faster with the final + flush included; `fsync`-bound work took the same time ([record](docs/workspace-measurements.md)). + +## Measured results + + + + Time on Seaweed Block relative to a local disk, over NVMe/TCP loopback: npm ci 1.00, git clone 1.02, untar 100,000 files 1.04, cold find and stat 0.97, 2,000 create plus write plus fsync 1.52, guest fsync median 1.31. + + +Lab runs, median of 3; not SLOs. Workloads: Firecracker microVMs (4 vCPU, 4 GiB) on one bare-metal host over +NVMe/TCP loopback, against a local file-backed disk. The first four rows come from a pre-release build on the +`walstore` engine and time the operation itself. With the final `syncfs` flush included on both sides (recorded +separately), the first three are 11-23% slower than the local disk (see the measurements page). The two `fsync` rows come from a later run of the released path +(`walstore-chunk`) on the same host, after the group-commit fix +([#173](https://github.com/seaweedfs/seaweed-block/pull/173)). The chart is drawn from +[measured-results.csv](docs/assets/measured-results.csv) by `docs/assets/readme-chart.py`. + +| Measurement | Seaweed Block | Local disk | +|---|---|---| +| `npm ci` (617 packages, offline) / `git clone` (Go 1.23, local) | 2.14 s / 7.10 s | 2.14 s / 6.99 s | +| Untar 100,000 files / cold `find` + `stat` over them | 1.10 s / 0.32 s | 1.06 s / 0.33 s | +| 2,000 × create + write + `fsync` | 9.27 s | 6.11 s | +| Guest `fsync` median, fio 4 KiB random write, one at a time | 3.59 ms | 2.74 ms | +| Snapshot of a 10 GiB volume (2,560 chunks) | 0.18 ms | | +| Two-host lifecycle (pre-release): create, snapshot, fork, move, stale holder, delete, GC | 35 of 35 checks | | + +The snapshot row is a host-side proxy without network latency, guest `fsync` or the block frontend. The two-host +lifecycle row is a pre-release run that included fork (removed from this release) and the earlier GC. The remaining +cost is `fsync`: a median of 3.59 ms against 2.74 ms local over NVMe/TCP loopback. The ublk frontend measured +3.23 ms in the same run; ublk is not among v1.0.0's supported frontends (NVMe/TCP and iSCSI). +[Workspace measurements](docs/workspace-measurements.md) has every number, the FUSE comparison and how each was +measured. + +## Status and limits + +- **Recovery point:** a lost host loses what was written since the volume's last successful snapshot or cut: + normally about a day with the default schedule (one scheduled snapshot a day, which is attempted, not + guaranteed). `--chunk-capture-interval` + (5 minutes or more) adds periodic cuts and shortens it. +- **v1.0.0 supports** the single-replica volume (`--durable-impl walstore-chunk`), backed up to SeaweedFS with + snapshots, restore, moves and volume delete. New volumes are at most 256 GiB. See the + [release note](docs/releases/v1.0.0.md) and its [known limits](docs/releases/v1.0.0.md#known-limits). +- **Replicated volumes** are a preview ([replicated volumes preview](docs/releases/replicated-volumes-preview.md)). +- **Kubernetes** is an alpha, for supported lab clusters ([Kubernetes status](docs/kubernetes-status.md)). + +## Direction + +Seaweed Block is block storage for AI agent workspaces: one local-speed disk per sandbox or microVM, with its history +(snapshots, restores, moves) in your own SeaweedFS. The same core serves Kubernetes block volumes (alpha). + +- **Works today (v1.0.1):** single-replica volumes up to 256 GiB over NVMe/TCP or iSCSI; scheduled and manual + snapshots; restore into a new volume; a planned hand-over to another machine (run across two machines on the + release candidate); a forced move after a host is lost, from the volume's last cut (tested with two server + identities on one machine); volume delete. Each is a documented sequence of `sw-block ops` commands and systemd + units. v1.0.1 adds `sw-block mini`, a single-host trial; whole-job volume commands (`sw-block volume start`, + `stop`, `backup`, `restore`); `sw-block shell` for inspection, with `cluster.check` and a troubleshooting page; a + log bundle without secrets; and a working `ops chunk verify` (see the [v1.0.1 note](docs/releases/v1.0.1.md)). +- **After that, planned:** volumes up to 1 TiB (v1.1); replicated volumes beyond the preview; export of a snapshot to another object store, and + import from it; `volume fork` and `volume move` commands. + +## Agent workspace disks: chunk lifecycle + +The workspace path runs `blockvolume` with `--durable-impl=walstore-chunk`, +`--chunk-filer ` and `--chunk-control-endpoint`, against a SeaweedFS +cluster. The `sw-block ops chunk` commands drive the lifecycle: + +```bash +sw-block ops chunk cut --volume v1 --status-addr # publish changed chunks, advance HEAD +sw-block ops chunk snapshot --volume v1 --status-addr --name s1 # name a snapshot +sw-block ops chunk snapshots --master --volume v1 --chunk-filer # list snapshots +sw-block ops chunk restore --master --chunk-filer --source v1 --snapshot s1 --target v3 # new volume from a snapshot +sw-block ops chunk detach --volume v1 --status-addr # final cut (seal); moving needs revoke + move, see docs/volume-lifecycle.md +sw-block ops chunk volume-delete --volume v3 --chunk-filer --master --request-id del-v3 +``` + +`volume-delete` is refused until the volume's holder has been revoked and its ACK +is recorded, and while the volume has snapshots: see +[Delete a volume](docs/volume-lifecycle.md#delete-a-volume). +Frozen detach and the pre-copy detach are not supported in this release: a +detach with `--frozen` (`frozen:true` on `POST /chunk/detach`) is refused with +409 `frozen_detach_unsupported`, and `blockvolume` refuses to start with +`--chunk-detach-precopy`. +`restore` creates the target from the snapshot; its blockvolume serves at +once and reads every chunk it has not made local from the source's snapshot +(there is no background copy). The source snapshot cannot be deleted while the +target exists. Fork is not supported in this release; the command is removed. +See [Restoring a snapshot](docs/standalone-deployment.md#restoring-a-snapshot-into-a-new-volume). +In v1.0.0 the chunk path (`walstore-chunk`) is the supported single-replica +configuration ([release note](docs/releases/v1.0.0.md), [operator guide](docs/operator-guide.md)); +it is not the `--durable-impl` default. + +## Quick start: Kubernetes (alpha) + +For supported lab clusters, not production. From the repository root, with +`kubectl` and `helm` configured: + +```bash +go build -o sw-block ./cmd/sw-block && export PATH="$PWD:$PATH" +sw-block ops generate-helm-values --out values.day1.yaml \ + --image ghcr.io/seaweedfs/seaweed-block:sha-dc2972d0059b \ + --csi-image ghcr.io/seaweedfs/seaweed-block-csi:sha-dc2972d0059b +helm install sw-block charts/seaweed-block --namespace kube-system \ + --create-namespace -f values.day1.yaml --wait --timeout 10m +SW_BLOCK_INSTALL_MODE=helm SW_BLOCK_HELM_RELEASE=sw-block \ +SW_BLOCK_HELM_NAMESPACE=kube-system SW_BLOCK_HELM_VALUES_FILE=values.day1.yaml \ + bash scripts/run-basic-app-example.sh "$PWD" +``` + +The last command writes a PVC from one pod and reads it from a replacement +pod; expect `first_volume_status=ok` in +`/tmp/sw-block-basic-app-*/first-volume-summary.txt`. `sha-dc2972d0059b` is +the validated tag for the v0.4 read-only status path; later paths need +matching [release images](docs/kubernetes-status.md#release-images), and +`:alpha` is for smoke tests only. Each step's output is in the [Kubernetes +quickstart](docs/quickstart-kubernetes.md). To clean up: + +```bash +helm uninstall sw-block --namespace kube-system +bash scripts/uninstall-k8s-alpha.sh "$PWD" && bash scripts/verify-helm-cleanup.sh +``` + +## Detailed status + +| Area | Status | +|---|---| +| Agent workspace disks (`walstore-chunk`), single replica | Supported in v1.0.0; see its [known limits](docs/releases/v1.0.0.md#known-limits) | +| Replicated volumes (`replication_factor` above 1) | Preview in v1.0.0 ([replicated volumes preview](docs/releases/replicated-volumes-preview.md)) | +| Kubernetes: Helm install, PVC provisioning, writer/reader check, read-only report and dashboard, CRD status and Events, support-bundle replay | Available (alpha) | +| Kubernetes: RF=3 multi-volume, CSI reattach recovery, iSCSI ALUA/dm-multipath mounted failover, restart persistence with hostPath | Gated (supported lab) | +| Kubernetes: `SwBlockVolume` finalizer lifecycle owner, returned-replica ACK eligibility executor | Beta candidate | +| Kubernetes: NVMe/TCP CSI multipath, returned-replica failback runtime, WAL multi-block record opt-in | Source-gated | +| Kubernetes: backup, snapshot and restore; returned-replica rebuild traffic | Planned | + +Full table and conditions: [Kubernetes status](docs/kubernetes-status.md); +run evidence: [release notes](docs/releases/README.md). + +**Upgrade note:** blockmaster listens off loopback only with mutual TLS +(`--tls-cert`, `--tls-key`, `--tls-client-ca`, `--role-file`); the runtime HTTP +listener always stays on loopback, and `--insecure-external-bind` is refused. +The Helm chart and the shipped manifests run with mutual TLS; create their +Secrets first ([quickstart](docs/quickstart-kubernetes.md)). + +### Not claimed yet + +- Production readiness, SLOs, or a published performance, RTO or RPO claim. +- `fsync` parity with local disk. Today it is about 1.3× local over NVMe/TCP + (see Measured results). +- ublk at high density. Unprivileged per-volume servers need a privileged + control broker, which is not done. +- Crash-restart recovery of a ublk server. A crashed server fails closed. +- Multi-replica workspaces combined with chunk snapshots. +- The experimental engines `smartwal` and `parallel-walstore`: removed in + v1.1; their volumes are refused (copy the data to a walstore volume with + v1.0.x first). +- Kubernetes: backup and restore, a production operator, automatic failback + or cleanup, upgrade execution, broad compatibility, and more: see + [what you should not expect yet](docs/kubernetes-status.md#what-you-should-not-expect-yet). + +## Correctness and verification + +- **CI** runs `go build`, `go vet` and `go test -short` on every pull request + and push to `main` ([workflow](.github/workflows/test.yml)); that set leaves out the four + long, disk-heavy packages (a pull request runs those of them it changes); + they run in full, together with the legacy-fixture configuration, on a + separate test VM for every merge train (commit status `full-suite (pool VM)` + on the train head). Crash, + mutation, real-SeaweedFS and binary tests are described in the + [core design, Part 2](docs/design/block-design.md#part-2-verification-lessons-known-issues), + with the known issues. +- **Formal models**: [TLA+ specifications](docs/spec/README.md) of the + protocols where a bug would lose data. Counterexamples became fixes and + regression tests ([#152](https://github.com/seaweedfs/seaweed-block/pull/152), [#156](https://github.com/seaweedfs/seaweed-block/pull/156), [#158](https://github.com/seaweedfs/seaweed-block/pull/158), [#159](https://github.com/seaweedfs/seaweed-block/pull/159)). +- **Fail closed**: recovery that cannot establish a consistent image reports + a typed reason (`wal_corrupt`, `io_error`) instead of serving; some + suspected damage (`wal_hole_suspected`) is a status warning only. + +## Documentation + +- Design: [core](docs/design/block-design.md), [agent workspace](docs/design/agent-workspace-design.md), + [Kubernetes block](docs/design/kubernetes-block-design.md), [invariants and state machines](docs/design/invariants.md), + [TLA+ specifications](docs/spec/README.md), + [workspace measurements](docs/workspace-measurements.md) +- Operations: [standalone deployment](docs/standalone-deployment.md), + [volume lifecycle](docs/volume-lifecycle.md), + [Kubernetes quickstart](docs/quickstart-kubernetes.md), [user capabilities](docs/user-capabilities.md) +- Claims: [Kubernetes status](docs/kubernetes-status.md), [release notes](docs/releases/README.md), + [NVMe/TCP supported-lab claim](docs/releases/nvme-tcp-supported-lab.md), + [known issues and work in progress](docs/design/block-design.md#24-known-issues-and-work-in-progress) +- Engineering references, not release-claim sources: [architecture](docs/architecture.md), + [developer architecture](docs/developer-architecture.md), [runtime state machines](docs/runtime-state-machines.md) + +## Development + +```bash +go build ./... && go vet ./... && go test -short ./... # what CI runs +go test ./cmd/sw-block ./core/ops ./core/csi ./core/launcher ./core/host/master -count=1 # release-scoped +``` + +The full `go test ./...` sweep may include in-progress packages outside the +release gate. `scripts/activate-k8s-alpha.sh` remains for local images. + +## Community + +Questions and bug reports: [GitHub Issues](https://github.com/seaweedfs/seaweed-block/issues). Seaweed Block builds on +[SeaweedFS](https://github.com/seaweedfs/seaweedfs). + +## License + +Apache-2.0 diff --git a/seaweed-block/charts/seaweed-block/.helmignore b/seaweed-block/charts/seaweed-block/.helmignore new file mode 100644 index 0000000000..18c681945f --- /dev/null +++ b/seaweed-block/charts/seaweed-block/.helmignore @@ -0,0 +1,5 @@ +.git/ +.github/ +results/ +*.tmp +*.log diff --git a/seaweed-block/charts/seaweed-block/Chart.yaml b/seaweed-block/charts/seaweed-block/Chart.yaml new file mode 100644 index 0000000000..153f1cb024 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/Chart.yaml @@ -0,0 +1,6 @@ +apiVersion: v2 +name: seaweed-block +description: Seaweed Block Kubernetes CSI storage provider +type: application +version: 0.3.0-alpha.0 +appVersion: "0.3-alpha" diff --git a/seaweed-block/charts/seaweed-block/README.md b/seaweed-block/charts/seaweed-block/README.md new file mode 100644 index 0000000000..06c39cc575 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/README.md @@ -0,0 +1,173 @@ +# Seaweed Block Helm Chart + +This chart installs the Seaweed Block alpha Kubernetes CSI stack: + +- `sw-blockmaster` +- CSI controller +- CSI node DaemonSet +- optional `StorageClass` +- optional CHAP secret for cross-node iSCSI + +The chart is read/write only through Kubernetes PVCs. It does not add a +mutating dashboard, operator reconciliation, backup/restore, or upgrade safety. + +## Quick Install + +Use generated values for the supported alpha install path. The generator reads +the live Kubernetes nodes and writes the node names/IPs that the launcher uses +for placement. On a single-node lab it keeps loopback/local-consumer mode; on a +multi-node lab it switches to non-loopback iSCSI with CHAP. For the +experimental NVMe/TCP path, pass `--protocol nvme`; this switches to +non-loopback NVMe/TCP, without enabling iSCSI CHAP. + +blockmaster runs with mutual TLS, so create its Secrets before installing +(`tls.*` values name them; the helper issues development certificates, one +node certificate per server id). + +```bash +SW_BLOCK_HELM_VALUES_OUT=values.day1.yaml \ + bash scripts/generate-helm-values-day1.sh "$PWD" + +bash scripts/k8s-alpha-certs.sh kube-system ~/.sw-block-alpha-tls ... + +helm install sw-block charts/seaweed-block \ + --namespace kube-system \ + -f values.day1.yaml +``` + +The raw chart defaults are render/development defaults only. Do not treat a +plain `helm install sw-block charts/seaweed-block` as a release-gated install: +it does not run preflight, does not discover the live Kubernetes node set, and +can leave placement/launcher evidence incomplete on real labs. + +A complete three-node example is in +[`examples/values-3node.yaml`](examples/values-3node.yaml): image tags, network +and compat settings, CHAP, the StorageClass replication factor, and three +`blockNodes` (`node-a`, `node-b`, `node-c`, with RFC 5737 documentation +addresses). Copy it and replace the node names and addresses with your own: + +```bash +helm install sw-block charts/seaweed-block -f my-values.yaml +``` + +`blockNodes[*].kubernetesNode` must match a real Kubernetes node name. The +`internalIP` is the management/control-plane address. `frontendIP` is optional; +when set, blockvolume `data_addr` and NVMe/TCP or iSCSI publish targets use +that address while `ctrl_addr` remains on `internalIP`. Use +`frontendNetworkClass: 100gbe_tcp` for a TCP frontend on the lab 100GbE data +network. + +The source-gated NVMe/RDMA path is explicit and remains off by default: + +```yaml +storageClass: + protocol: nvme + nvmeTransport: rdma +network: + externalNVMe: true +blockNodes: + - name: node-b + kubernetesNode: node-b + internalIP: 192.0.2.12 + frontendIP: 198.51.100.12 + frontendNetworkClass: 100gbe_roce +``` + +RDMA requires a non-loopback RoCE frontend address and host `nvme-rdma`, +`nvmet-rdma`, NBD, configfs, and RDMA-device prerequisites. This supported-lab +path does not claim RDMA multipath, failover, performance improvement, or an +SLO. + +`network.rejectLoopbackPublishTargets` records the intended safety boundary. +Some blockmaster launcher flags are gated by `compat.*` settings because older +published alpha images do not accept every v0.3 flag. Keep +`compat.launcherDurableImplFlag`, `compat.launcherReplicationAckFlag`, and +`compat.launcherRejectLoopbackFlag` false unless the selected image is known to +support the corresponding flag. The default durable implementation is still +`walstore` because that is the blockmaster binary default when the +`--launcher-durable-impl` flag is omitted. + +For source-gated NVMe/TCP write-path experiments, `nvme.maxH2CDataLength` can +be set explicitly. The chart default is `32768`; `65536` has a supported-lab +gate as an opt-in candidate. This is not a default change, NVMe/RDMA/RoCE +claim, or performance SLO. + +For source-gated WAL write-path experiments, multi-block WAL records can be +enabled explicitly: + +```yaml +blockmaster: + durableWALMultiBlockRecords: true +``` + +This is a lab-only optimization boundary backed by Phase 151/152/155 gates. It +is not a release-image claim until a matching-image smoke runs the explicit +opt-in recovery/status path. The default remains `false`. Do not set +`durableWALRecoveryTestDisableFlusher` outside recovery-test gates; that flag is +scaffolding used to force WAL replay evidence and is not a production tuning +knob. + +## RF=3 Sync-Quorum Profile + +For the gated RF=3 recovery shape: + +```yaml +storageClass: + replicationFactor: 3 +replication: + ackProfile: sync-quorum + expectedSlotsPerVolume: 3 +network: + externalISCSI: true + externalNVMe: false + externalStatus: false + rejectLoopbackPublishTargets: true +chap: + enabled: true + username: swblock + secret: replace-with-a-real-secret +``` + +## Stage 2 Multipath Baseline + +Stage 2 iSCSI ALUA/dm-multipath requires host prerequisites and is intentionally +opt-in: + +```yaml +stage2Multipath: + enabled: true +``` + +This only enables chart wiring. The host still needs iSCSI, multipath, and ALUA +support configured. + +## Optional Failback Runtime Wiring + +Returned-replica failback execution is disabled by default. The chart only +renders the blockmaster failback RPC and executor runtime flags when all +execution switches are explicit: + +```yaml +blockmaster: + failbackRuntimeRPC: true + +failbackExecutor: + create: true + dryRun: false + execution: + enabled: true + policy: true + failbackRuntimeGrpcAddr: blockmaster.kube-system.svc:9333 +``` + +The chart rejects unsafe combinations such as execution with `dryRun: true`, +missing execution policy, or both HTTP and gRPC runtime addresses. This wiring +does not enable automatic failback by default. + +## Current Boundary + +- Use immutable image tags such as `sha-` for QA and release checks. +- `:alpha` is a convenience tag and can drift from local source. +- Dynamic node discovery/onboarding is not yet handled by this chart. For now, + update `blockNodes` and run `helm upgrade`. +- Operator-managed node discovery, repair, and upgrade flows are future work. diff --git a/seaweed-block/charts/seaweed-block/crds/swblockclusters.block.seaweedfs.com.yaml b/seaweed-block/charts/seaweed-block/crds/swblockclusters.block.seaweedfs.com.yaml new file mode 100644 index 0000000000..f4089f8e2b --- /dev/null +++ b/seaweed-block/charts/seaweed-block/crds/swblockclusters.block.seaweedfs.com.yaml @@ -0,0 +1,318 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: swblockclusters.block.seaweedfs.com +spec: + group: block.seaweedfs.com + scope: Namespaced + names: + plural: swblockclusters + singular: swblockcluster + kind: SwBlockCluster + shortNames: + - swbc + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Ready + type: integer + jsonPath: .status.readyVolumeCount + - name: Blocked + type: integer + jsonPath: .status.blockedVolumeCount + - name: Stale + type: integer + jsonPath: .status.staleVolumeCount + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + description: Read-only Seaweed Block cluster status projection. + properties: + spec: + type: object + description: Declarative install metadata. Phase 35 does not reconcile spec into storage mutation. + properties: + image: + type: string + csiImage: + type: string + storageClass: + type: string + ackProfile: + type: string + protocol: + type: string + blockNodes: + type: array + items: + type: object + properties: + name: + type: string + internalIP: + type: string + frontendIP: + type: string + frontendNetworkClass: + type: string + status: + type: object + properties: + observedAt: + type: string + format: date-time + observedGeneration: + type: integer + format: int64 + nodeCount: + type: integer + minimum: 0 + nodes: + type: array + items: + type: object + required: + - name + - schedulable + - ready + properties: + name: + type: string + kubernetesNode: + type: string + internalIP: + type: string + frontendIP: + type: string + frontendNetworkClass: + type: string + schedulable: + type: boolean + ready: + type: boolean + status: + type: string + reasonCode: + type: string + lastHeartbeatAt: + type: string + format: date-time + replicaCount: + type: integer + minimum: 0 + requiredImages: + type: array + items: + type: string + missingImages: + type: array + items: + type: string + conditions: + type: array + items: + x-kubernetes-preserve-unknown-fields: true + type: object + required: + - type + - status + properties: + type: + type: string + enum: + - Ready + - Recovered + - Recovering + - Blocked + - Invalid + - CleanupRequired + - EvidenceStale + status: + type: string + enum: + - "True" + - "False" + - Unknown + reason: + type: string + severity: + type: string + enum: + - info + - warning + - error + message: + type: string + lastTransitionTime: + type: string + format: date-time + evidenceRefs: + type: array + items: + type: string + evidenceRefs: + type: array + items: + type: string + volumeCount: + type: integer + minimum: 0 + readyVolumeCount: + type: integer + minimum: 0 + blockedVolumeCount: + type: integer + minimum: 0 + staleVolumeCount: + type: integer + minimum: 0 + conditions: + type: array + items: + x-kubernetes-preserve-unknown-fields: true + type: object + required: + - type + - status + properties: + type: + type: string + enum: + - Ready + - Recovered + - Recovering + - Blocked + - Invalid + - CleanupRequired + - EvidenceStale + status: + type: string + enum: + - "True" + - "False" + - Unknown + reason: + type: string + severity: + type: string + enum: + - info + - warning + - error + message: + type: string + lastTransitionTime: + type: string + format: date-time + evidenceRefs: + type: array + items: + type: string + evidenceRefs: + type: array + items: + type: string + supportBundleRefs: + type: array + items: + type: string + cleanup: + type: object + properties: + status: + type: string + k8sResidueCount: + type: integer + minimum: 0 + iscsiResidueCount: + type: integer + minimum: 0 + multipathResidueCount: + type: integer + minimum: 0 + processResidueCount: + type: integer + minimum: 0 + hostPathResidueCount: + type: integer + minimum: 0 + failureCount: + type: integer + minimum: 0 + failedPhase: + type: string + reasonCodes: + type: array + items: + type: string + evidenceRef: + type: string + installDrift: + type: object + properties: + status: + type: string + enum: + - ok + - mismatch + - unknown + reasonCode: + type: string + chartName: + type: string + currentChartVersion: + type: string + desiredChartVersion: + type: string + currentAppVersion: + type: string + desiredAppVersion: + type: string + currentImage: + type: string + desiredImage: + type: string + currentCsiImage: + type: string + desiredCsiImage: + type: string + currentOperatorImage: + type: string + desiredOperatorImage: + type: string + evidenceRef: + type: string + safeNextSteps: + type: array + items: + type: object + required: + - type + - mode + - mutationAllowed + properties: + type: + type: string + mode: + type: string + enum: + - read_only + - dry_run + - scripted + command: + type: string + reasonCode: + type: string + mutationAllowed: + type: boolean + evidenceRefs: + type: array + items: + type: string diff --git a/seaweed-block/charts/seaweed-block/crds/swblockfrontendpublications.block.seaweedfs.com.yaml b/seaweed-block/charts/seaweed-block/crds/swblockfrontendpublications.block.seaweedfs.com.yaml new file mode 100644 index 0000000000..ddcda8ed70 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/crds/swblockfrontendpublications.block.seaweedfs.com.yaml @@ -0,0 +1,174 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: swblockfrontendpublications.block.seaweedfs.com +spec: + group: block.seaweedfs.com + scope: Namespaced + names: + plural: swblockfrontendpublications + singular: swblockfrontendpublication + kind: SwBlockFrontendPublication + shortNames: + - swbfp + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Volume + type: string + jsonPath: .spec.volumeName + - name: Replica + type: string + jsonPath: .spec.replicaID + - name: State + type: string + jsonPath: .status.state + - name: Reason + type: string + jsonPath: .status.reasonCode + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + description: Narrow target for future frontend publication. Phase 69 creates the target only; it does not publish frontend paths. + properties: + spec: + type: object + description: Identity and terminal ACK evidence required before a future frontend publication executor may act. + required: + - volumeName + - replicaID + properties: + volumeName: + type: string + volumeID: + type: string + pvcName: + type: string + replicaID: + type: string + targetDataAddr: + type: string + targetCtrlAddr: + type: string + sourceEligibilityName: + type: string + sourceFailbackName: + type: string + ackEligibilityKnown: + type: boolean + ackEligible: + type: boolean + frontendFencedAfterExecution: + type: boolean + primaryUnchanged: + type: boolean + durableFrontierCovered: + type: boolean + noCrossVolumeIdentityChange: + type: boolean + failbackCompleted: + type: boolean + authorityEpochAdvanced: + type: boolean + singlePrimaryAfterFailback: + type: boolean + publishTargetSwappedAfterFailback: + type: boolean + frontendPublicationDecision: + type: string + enum: + - blocked + - disabled + - enabled + frontendPublicationReason: + type: string + frontendPublicationMutationAllowed: + type: boolean + runtimeEndpoint: + type: string + status: + type: object + properties: + observedAt: + type: string + format: date-time + observedGeneration: + type: integer + format: int64 + minimum: 0 + executor: + type: string + state: + type: string + enum: + - planned + - blocked + - published + reasonCode: + type: string + publicationMutationAllowed: + type: boolean + frontendPublished: + type: boolean + failbackStarted: + type: boolean + noStorageMutation: + type: boolean + noCrossVolumeIdentityChange: + type: boolean + evidenceGeneration: + type: string + conditions: + type: array + items: + type: object + required: + - type + - status + properties: + type: + type: string + enum: + - Ready + - Blocked + - Recovering + - Recovered + - EvidenceStale + status: + type: string + enum: + - "True" + - "False" + - Unknown + reason: + type: string + severity: + type: string + enum: + - info + - warning + - error + message: + type: string + lastTransitionTime: + type: string + format: date-time + evidenceRefs: + type: array + items: + type: string + evidenceRefs: + type: array + items: + type: string + nonClaims: + type: array + items: + type: string diff --git a/seaweed-block/charts/seaweed-block/crds/swblockreplicaeligibilities.block.seaweedfs.com.yaml b/seaweed-block/charts/seaweed-block/crds/swblockreplicaeligibilities.block.seaweedfs.com.yaml new file mode 100644 index 0000000000..278daecd55 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/crds/swblockreplicaeligibilities.block.seaweedfs.com.yaml @@ -0,0 +1,137 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: swblockreplicaeligibilities.block.seaweedfs.com +spec: + group: block.seaweedfs.com + scope: Namespaced + names: + plural: swblockreplicaeligibilities + singular: swblockreplicaeligibility + kind: SwBlockReplicaEligibility + shortNames: + - swbre + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Volume + type: string + jsonPath: .spec.volumeName + - name: Replica + type: string + jsonPath: .spec.replicaID + - name: Eligible + type: boolean + jsonPath: .status.ackEligible + - name: Reason + type: string + jsonPath: .status.reasonCode + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + description: Narrow ACK eligibility evidence target for returned-replica reintegration. + properties: + spec: + type: object + description: Identity of the returned replica whose ACK eligibility may be recorded. + required: + - volumeName + - replicaID + properties: + volumeName: + type: string + volumeID: + type: string + pvcName: + type: string + replicaID: + type: string + status: + type: object + properties: + observedAt: + type: string + format: date-time + observedGeneration: + type: integer + format: int64 + minimum: 0 + executor: + type: string + reasonCode: + type: string + ackEligibilityKnown: + type: boolean + ackEligible: + type: boolean + frontendFencedAfterExecution: + type: boolean + primaryUnchanged: + type: boolean + durableFrontierCovered: + type: boolean + noCrossVolumeIdentityChange: + type: boolean + frontendPublicationDecision: + type: string + enum: + - blocked + - disabled + frontendPublicationReason: + type: string + frontendPublicationMutationAllowed: + type: boolean + evidenceGeneration: + type: string + conditions: + type: array + items: + type: object + required: + - type + - status + properties: + type: + type: string + enum: + - Ready + - Blocked + - EvidenceStale + status: + type: string + enum: + - "True" + - "False" + - Unknown + reason: + type: string + severity: + type: string + enum: + - info + - warning + - error + message: + type: string + lastTransitionTime: + type: string + format: date-time + evidenceRefs: + type: array + items: + type: string + evidenceRefs: + type: array + items: + type: string + nonClaims: + type: array + items: + type: string diff --git a/seaweed-block/charts/seaweed-block/crds/swblockreplicafailbacks.block.seaweedfs.com.yaml b/seaweed-block/charts/seaweed-block/crds/swblockreplicafailbacks.block.seaweedfs.com.yaml new file mode 100644 index 0000000000..7268ebe9df --- /dev/null +++ b/seaweed-block/charts/seaweed-block/crds/swblockreplicafailbacks.block.seaweedfs.com.yaml @@ -0,0 +1,163 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: swblockreplicafailbacks.block.seaweedfs.com +spec: + group: block.seaweedfs.com + scope: Namespaced + names: + plural: swblockreplicafailbacks + singular: swblockreplicafailback + kind: SwBlockReplicaFailback + shortNames: + - swbrf + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Volume + type: string + jsonPath: .spec.volumeName + - name: Replica + type: string + jsonPath: .spec.replicaID + - name: State + type: string + jsonPath: .status.state + - name: Reason + type: string + jsonPath: .status.reasonCode + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + description: Narrow target for future returned-replica authority failback. Phase 75 creates the target only; it does not mutate authority. + properties: + spec: + type: object + description: Identity and terminal ACK evidence required before a future failback executor may act. + required: + - volumeName + - replicaID + properties: + volumeName: + type: string + volumeID: + type: string + pvcName: + type: string + replicaID: + type: string + targetDataAddr: + type: string + targetCtrlAddr: + type: string + expectedCurrentReplicaID: + type: string + expectedCurrentEpoch: + type: integer + format: int64 + minimum: 0 + ackEligible: + type: boolean + frontendFencedBeforeFailback: + type: boolean + durableFrontierCovered: + type: boolean + noCrossVolumeIdentityChange: + type: boolean + failbackDecision: + type: string + enum: ["disabled", "enabled"] + failbackReason: + type: string + failbackMutationAllowed: + type: boolean + runtimeEndpoint: + type: string + status: + type: object + properties: + observedAt: + type: string + format: date-time + observedGeneration: + type: integer + format: int64 + minimum: 0 + executor: + type: string + state: + type: string + enum: + - planned + - blocked + - failed_back + reasonCode: + type: string + failbackMutationAllowed: + type: boolean + failbackStarted: + type: boolean + authorityEpochAdvanced: + type: boolean + singlePrimaryAfterFailback: + type: boolean + publishTargetSwappedAfterFailback: + type: boolean + noCrossVolumeIdentityChange: + type: boolean + evidenceGeneration: + type: string + conditions: + type: array + items: + type: object + required: + - type + - status + properties: + type: + type: string + enum: + - Ready + - Blocked + - Recovering + - Recovered + - EvidenceStale + status: + type: string + enum: + - "True" + - "False" + - Unknown + reason: + type: string + severity: + type: string + enum: + - info + - warning + - error + message: + type: string + lastTransitionTime: + type: string + format: date-time + evidenceRefs: + type: array + items: + type: string + evidenceRefs: + type: array + items: + type: string + nonClaims: + type: array + items: + type: string diff --git a/seaweed-block/charts/seaweed-block/crds/swblockreplicarebuilds.block.seaweedfs.com.yaml b/seaweed-block/charts/seaweed-block/crds/swblockreplicarebuilds.block.seaweedfs.com.yaml new file mode 100644 index 0000000000..4f4f45d928 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/crds/swblockreplicarebuilds.block.seaweedfs.com.yaml @@ -0,0 +1,188 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: swblockreplicarebuilds.block.seaweedfs.com +spec: + group: block.seaweedfs.com + scope: Namespaced + names: + plural: swblockreplicarebuilds + singular: swblockreplicarebuild + kind: SwBlockReplicaRebuild + shortNames: + - swbrr + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Volume + type: string + jsonPath: .spec.volumeName + - name: Replica + type: string + jsonPath: .spec.replicaID + - name: State + type: string + jsonPath: .status.state + - name: Reason + type: string + jsonPath: .status.reasonCode + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + description: Narrow status target for returned-replica rebuild/catch-up progress evidence. + properties: + spec: + type: object + description: Identity of the returned replica whose rebuild/catch-up progress may be recorded. + required: + - volumeName + - replicaID + properties: + volumeName: + type: string + volumeID: + type: string + pvcName: + type: string + replicaID: + type: string + sourceReplicaID: + type: string + runtimeEndpoint: + type: string + targetDataAddr: + type: string + sessionID: + type: integer + format: int64 + minimum: 0 + epoch: + type: integer + format: int64 + minimum: 0 + endpointVersion: + type: integer + format: int64 + minimum: 0 + fromLsn: + type: integer + format: int64 + minimum: 0 + frontierHintLsn: + type: integer + format: int64 + minimum: 0 + basePinLsn: + type: integer + format: int64 + minimum: 0 + status: + type: object + properties: + observedAt: + type: string + format: date-time + observedGeneration: + type: integer + format: int64 + minimum: 0 + executor: + type: string + state: + type: string + enum: + - planned + - blocked + - running + - caught_up + reasonCode: + type: string + frontendFencedBeforeRebuild: + type: boolean + primaryUnchanged: + type: boolean + durableFrontierKnown: + type: boolean + durableFrontierLsn: + type: integer + format: int64 + minimum: 0 + requiredFrontierKnown: + type: boolean + requiredFrontierLsn: + type: integer + format: int64 + minimum: 0 + durableFrontierCaughtUp: + type: boolean + rebuildTrafficStarted: + type: boolean + publicationDecision: + type: string + enum: + - blocked + - disabled + publicationReason: + type: string + publicationMutationAllowed: + type: boolean + noFrontendPublication: + type: boolean + noCrossVolumeIdentityChange: + type: boolean + evidenceGeneration: + type: string + conditions: + type: array + items: + type: object + required: + - type + - status + properties: + type: + type: string + enum: + - Ready + - Blocked + - Recovering + - Recovered + - EvidenceStale + status: + type: string + enum: + - "True" + - "False" + - Unknown + reason: + type: string + severity: + type: string + enum: + - info + - warning + - error + message: + type: string + lastTransitionTime: + type: string + format: date-time + evidenceRefs: + type: array + items: + type: string + evidenceRefs: + type: array + items: + type: string + nonClaims: + type: array + items: + type: string diff --git a/seaweed-block/charts/seaweed-block/crds/swblockvolumes.block.seaweedfs.com.yaml b/seaweed-block/charts/seaweed-block/crds/swblockvolumes.block.seaweedfs.com.yaml new file mode 100644 index 0000000000..71f943b172 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/crds/swblockvolumes.block.seaweedfs.com.yaml @@ -0,0 +1,442 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: swblockvolumes.block.seaweedfs.com +spec: + group: block.seaweedfs.com + scope: Namespaced + names: + plural: swblockvolumes + singular: swblockvolume + kind: SwBlockVolume + shortNames: + - swbv + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Status + type: string + jsonPath: .status.status + - name: Reason + type: string + jsonPath: .status.reasonCode + - name: PVC + type: string + jsonPath: .status.pvcName + - name: Age + type: date + jsonPath: .metadata.creationTimestamp + schema: + openAPIV3Schema: + type: object + description: Read-only Seaweed Block volume status projection. + properties: + spec: + type: object + description: PVC binding metadata. Phase 35 does not reconcile spec into storage mutation. + properties: + pvcName: + type: string + storageClass: + type: string + status: + type: object + properties: + volumeID: + type: string + pvcName: + type: string + primaryReplicaID: + type: string + publishTarget: + type: string + authorityEpoch: + type: integer + format: int64 + minimum: 0 + authorityEndpointVersion: + type: integer + format: int64 + minimum: 0 + status: + type: string + enum: + - ready + - recovered + - recovering + - degraded + - blocked + - invalid + - unsafe + - unknown + reasonCode: + type: string + observedAt: + type: string + format: date-time + conditions: + type: array + items: + x-kubernetes-preserve-unknown-fields: true + type: object + required: + - type + - status + properties: + type: + type: string + enum: + - Ready + - Recovered + - Recovering + - Blocked + - Invalid + - CleanupRequired + - EvidenceStale + status: + type: string + enum: + - "True" + - "False" + - Unknown + reason: + type: string + severity: + type: string + enum: + - info + - warning + - error + message: + type: string + lastTransitionTime: + type: string + format: date-time + evidenceRefs: + type: array + items: + type: string + deleteSafety: + type: object + properties: + actionType: + type: string + decision: + type: string + enum: + - allowed + - rejected + - unknown + state: + type: string + enum: + - not_requested + - requested + - blocked + - releasable + - released + reason: + type: string + finalizerReleaseAllowed: + type: boolean + missingFacts: + type: array + items: + type: string + evidenceRefs: + type: array + items: + type: string + safeNextAction: + type: string + nvme: + type: object + properties: + protocol: + type: string + enum: + - nvme + transport: + type: string + enum: + - tcp + - rdma + nqn: + type: string + nsid: + type: integer + format: int64 + minimum: 0 + nvmeAddr: + type: string + nvmeAddrs: + type: array + items: + type: string + pathCount: + type: integer + minimum: 0 + multipathObserved: + type: boolean + anaState: + type: string + reasonCode: + type: string + replicaReintegrations: + type: array + items: + type: object + required: + - replicaID + - state + - frontendFenced + - frontendPrimaryReady + - ackEligibilityKnown + - ackEligible + - durableFrontierKnown + properties: + replicaID: + type: string + state: + type: string + enum: + - fenced + - recovering + - ready + - blocked + - unknown + reasonCode: + type: string + frontendFenced: + type: boolean + frontendPrimaryReady: + type: boolean + ackEligibilityKnown: + type: boolean + ackEligible: + type: boolean + durableFrontierKnown: + type: boolean + durableFrontierLsn: + type: integer + format: int64 + minimum: 0 + requiredFrontierKnown: + type: boolean + requiredFrontierLsn: + type: integer + format: int64 + minimum: 0 + runtimeEndpoint: + type: string + targetDataAddr: + type: string + targetCtrlAddr: + type: string + sessionID: + type: integer + format: int64 + minimum: 0 + epoch: + type: integer + format: int64 + minimum: 0 + endpointVersion: + type: integer + format: int64 + minimum: 0 + fromLsn: + type: integer + format: int64 + minimum: 0 + frontierHintLsn: + type: integer + format: int64 + minimum: 0 + basePinLsn: + type: integer + format: int64 + minimum: 0 + evidenceRefs: + type: array + items: + type: string + executorPreflights: + type: array + items: + type: object + required: + - actionType + - decision + - reason + - mode + - sideEffectClass + - ownerExecutor + - mutationAllowed + - frontendFenced + - ackEligibilityKnown + - ackEligible + - durableFrontierKnown + - requiredFrontierKnown + properties: + actionType: + type: string + replicaID: + type: string + decision: + type: string + enum: + - ready + - hold + reason: + type: string + mode: + type: string + enum: + - dry_run + sideEffectClass: + type: string + enum: + - authority_mutating + ownerExecutor: + type: string + mutationAllowed: + type: boolean + frontendFenced: + type: boolean + ackEligibilityKnown: + type: boolean + ackEligible: + type: boolean + durableFrontierKnown: + type: boolean + durableFrontierLsn: + type: integer + format: int64 + minimum: 0 + requiredFrontierKnown: + type: boolean + requiredFrontierLsn: + type: integer + format: int64 + minimum: 0 + evidenceRequired: + type: string + evidenceRefs: + type: array + items: + type: string + forbiddenMutationClass: + type: array + items: + type: string + executorContracts: + type: array + items: + type: object + required: + - actionType + - decision + - reason + - ownerExecutor + - executionEnabled + - mutationAllowed + properties: + actionType: + type: string + replicaID: + type: string + decision: + type: string + enum: + - blocked + - disabled + reason: + type: string + ownerExecutor: + type: string + executionEnabled: + type: boolean + mutationAllowed: + type: boolean + preflightDecision: + type: string + preflightReason: + type: string + allowedMutationClass: + type: array + items: + type: string + forbiddenMutationClass: + type: array + items: + type: string + terminalEvidenceRequired: + type: array + items: + type: string + evidenceRefs: + type: array + items: + type: string + nonClaims: + type: array + items: + type: string + evidenceRefs: + type: array + items: + type: string + allowedActions: + type: array + items: + type: object + required: + - type + - mode + - mutationAllowed + properties: + type: + type: string + mode: + type: string + enum: + - read_only + - dry_run + - scripted + sideEffectClass: + type: string + ownerExecutor: + type: string + decision: + type: string + enum: + - allowed + - rejected + - unknown + decisionReason: + type: string + missingFacts: + type: array + items: + type: string + mutationAllowed: + type: boolean + preconditions: + type: array + items: + type: string + invariantRefs: + type: array + items: + type: string + evidenceRequired: + type: string + evidenceRefs: + type: array + items: + type: string diff --git a/seaweed-block/charts/seaweed-block/examples/values-3node.yaml b/seaweed-block/charts/seaweed-block/examples/values-3node.yaml new file mode 100644 index 0000000000..ccee983eac --- /dev/null +++ b/seaweed-block/charts/seaweed-block/examples/values-3node.yaml @@ -0,0 +1,48 @@ +# Example values for a three-node install (see ../README.md). +# +# Node names and addresses are placeholders. The addresses come from the +# RFC 5737 documentation ranges: 192.0.2.0/24 stands for the internal +# (management/control-plane) network and 198.51.100.0/24 for the frontend +# (data-plane) network. Replace them with your own Kubernetes node names and +# addresses; `sw-block ops generate-helm-values` derives them from the live +# cluster. +image: + tag: sha- +csiImage: + tag: sha- + +network: + externalISCSI: true + externalNVMe: false + externalStatus: false # not supported with mutual TLS (the volume status stays on loopback) + rejectLoopbackPublishTargets: true + +compat: + launcherDurableImplFlag: false + launcherReplicationAckFlag: false + launcherRejectLoopbackFlag: false + +chap: + enabled: true + username: swblock + secret: replace-with-a-real-secret + +storageClass: + replicationFactor: 1 + +blockNodes: + - name: node-a + kubernetesNode: node-a + internalIP: 192.0.2.11 + frontendIP: 198.51.100.11 + frontendNetworkClass: 100gbe_tcp + - name: node-b + kubernetesNode: node-b + internalIP: 192.0.2.12 + frontendIP: 198.51.100.12 + frontendNetworkClass: 100gbe_tcp + - name: node-c + kubernetesNode: node-c + internalIP: 192.0.2.13 + frontendIP: 198.51.100.13 + frontendNetworkClass: 100gbe_tcp diff --git a/seaweed-block/charts/seaweed-block/templates/NOTES.txt b/seaweed-block/charts/seaweed-block/templates/NOTES.txt new file mode 100644 index 0000000000..04c134d443 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/NOTES.txt @@ -0,0 +1,11 @@ +Seaweed Block has been rendered by Helm. + +Next checks: + kubectl -n {{ .Release.Namespace }} wait --for=condition=available deploy/sw-blockmaster --timeout=120s + kubectl -n {{ .Release.Namespace }} wait --for=condition=available deploy/sw-block-csi-controller --timeout=120s + kubectl -n {{ .Release.Namespace }} rollout status ds/sw-block-csi-node --timeout=120s + +Create volumes through Kubernetes PVCs using StorageClass {{ .Values.storageClass.name }}. + +This chart is read-only/operator-free alpha packaging. It does not install a +mutating dashboard, operator CRDs, backup/restore, or upgrade safety. diff --git a/seaweed-block/charts/seaweed-block/templates/_helpers.tpl b/seaweed-block/charts/seaweed-block/templates/_helpers.tpl new file mode 100644 index 0000000000..6d19e8919e --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/_helpers.tpl @@ -0,0 +1,100 @@ +{{/* +Common template helpers for Seaweed Block. +*/}} +{{- define "seaweed-block.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{- define "seaweed-block.fullname" -}} +{{- if .Values.fullnameOverride -}} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- printf "%s-%s" .Release.Name (include "seaweed-block.name" .) | trunc 63 | trimSuffix "-" -}} +{{- end -}} +{{- end -}} + +{{- define "seaweed-block.labels" -}} +app.kubernetes.io/name: {{ include "seaweed-block.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }} +{{- end -}} + +{{- define "seaweed-block.image" -}} +{{- if .Values.image.digest -}} +{{- printf "%s@%s" .Values.image.repository .Values.image.digest -}} +{{- else -}} +{{- printf "%s:%s" .Values.image.repository .Values.image.tag -}} +{{- end -}} +{{- end -}} + +{{- define "seaweed-block.csiImage" -}} +{{- if .Values.csiImage.digest -}} +{{- printf "%s@%s" .Values.csiImage.repository .Values.csiImage.digest -}} +{{- else -}} +{{- printf "%s:%s" .Values.csiImage.repository .Values.csiImage.tag -}} +{{- end -}} +{{- end -}} + +{{- define "seaweed-block.statePermissionsImage" -}} +{{- if .Values.blockmaster.statePermissionsImage.digest -}} +{{- printf "%s@%s" .Values.blockmaster.statePermissionsImage.repository .Values.blockmaster.statePermissionsImage.digest -}} +{{- else -}} +{{- printf "%s:%s" .Values.blockmaster.statePermissionsImage.repository .Values.blockmaster.statePermissionsImage.tag -}} +{{- end -}} +{{- end -}} + +{{- define "seaweed-block.blockmasterAddress" -}} +{{- printf "%s.%s.svc.cluster.local:%v" .Values.blockmaster.serviceName .Release.Namespace .Values.blockmaster.listenPort -}} +{{- end -}} + +{{- define "seaweed-block.expectedSlotsPerVolume" -}} +{{- if gt (int .Values.replication.expectedSlotsPerVolume) 0 -}} +{{- .Values.replication.expectedSlotsPerVolume -}} +{{- else -}} +{{- .Values.storageClass.replicationFactor -}} +{{- end -}} +{{- end -}} + +{{/* Mutual TLS toward blockmaster for an in-cluster client: its own Secret + (one of .Values.tls.clientSecrets, passed to masterTLSClientVolume) + mounted at /etc/sw-block/master-tls. */}} +{{- define "seaweed-block.masterTLSClientFlags" -}} +- "--master-tls-cert=/etc/sw-block/master-tls/tls.crt" +- "--master-tls-key=/etc/sw-block/master-tls/tls.key" +- "--master-ca=/etc/sw-block/master-tls/ca.crt" +{{- end -}} + +{{- define "seaweed-block.masterTLSClientEnv" -}} +- name: SW_BLOCK_TLS_CERT + value: /etc/sw-block/master-tls/tls.crt +- name: SW_BLOCK_TLS_KEY + value: /etc/sw-block/master-tls/tls.key +- name: SW_BLOCK_TLS_CA + value: /etc/sw-block/master-tls/ca.crt +{{- end -}} + +{{- define "seaweed-block.masterTLSClientMount" -}} +- name: master-tls + mountPath: /etc/sw-block/master-tls + readOnly: true +{{- end -}} + +{{/* The CSI node and the status operator only read: refuse a Secret named + like an admin client's or blockmaster's own (the chart sees names, not + roles; the role file decides the role). */}} +{{- define "seaweed-block.readOnlyClientSecrets" -}} +{{- $s := .Values.tls.clientSecrets -}} +{{- if eq $s.csiNode $s.csiController $s.failbackExecutor .Values.tls.masterSecret -}} +{{- fail (printf "tls.clientSecrets.csiNode %q is the CSI controller's, the failback executor's or blockmaster's Secret: the node plugin never mounts an admin key" $s.csiNode) -}} +{{- end -}} +{{- if eq $s.operatorStatus $s.csiController $s.failbackExecutor .Values.tls.masterSecret -}} +{{- fail (printf "tls.clientSecrets.operatorStatus %q is the CSI controller's, the failback executor's or blockmaster's Secret: the status operator never mounts an admin key" $s.operatorStatus) -}} +{{- end -}} +{{- end -}} + +{{- define "seaweed-block.masterTLSClientVolume" -}} +- name: master-tls + secret: + secretName: {{ . }} +{{- end -}} diff --git a/seaweed-block/charts/seaweed-block/templates/authority-executor-rbac.yaml b/seaweed-block/charts/seaweed-block/templates/authority-executor-rbac.yaml new file mode 100644 index 0000000000..721c1ecf9e --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/authority-executor-rbac.yaml @@ -0,0 +1,49 @@ +{{- if and .Values.authorityExecutor.create .Values.authorityExecutor.rbac.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "seaweed-block.fullname" . }}-authority-executor + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "seaweed-block.fullname" . }}-authority-executor + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +rules: + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockvolumes"] + verbs: ["get", "list", "watch"] + {{- if .Values.authorityExecutor.execution.enabled }} + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockreplicaeligibilities"] + verbs: ["get", "list", "watch"] + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockreplicaeligibilities/status"] + verbs: ["get", "update", "patch"] + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockreplicarebuilds"] + verbs: ["get", "list", "watch"] + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockreplicarebuilds/status"] + verbs: ["get", "update", "patch"] + {{- end }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "seaweed-block.fullname" . }}-authority-executor + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +subjects: + - kind: ServiceAccount + name: {{ include "seaweed-block.fullname" . }}-authority-executor + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "seaweed-block.fullname" . }}-authority-executor +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/authority-executor.yaml b/seaweed-block/charts/seaweed-block/templates/authority-executor.yaml new file mode 100644 index 0000000000..546bf4fd99 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/authority-executor.yaml @@ -0,0 +1,41 @@ +{{- if .Values.authorityExecutor.create }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-block-authority-executor + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} + app: sw-block-authority-executor +spec: + replicas: 1 + selector: + matchLabels: + app: sw-block-authority-executor + template: + metadata: + labels: + app: sw-block-authority-executor + {{- include "seaweed-block.labels" . | nindent 8 }} + spec: + serviceAccountName: {{ include "seaweed-block.fullname" . }}-authority-executor + {{- with .Values.authorityExecutor.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + containers: + - name: authority-executor + image: {{ include "seaweed-block.image" . | quote }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + command: ["/usr/local/bin/sw-block"] + args: + - "ops" + - "authority-executor" + - "--namespace={{ .Release.Namespace }}" + - "--allowed-mutation-class={{ .Values.authorityExecutor.execution.allowedMutationClass }}" + {{- if .Values.authorityExecutor.execution.enabled }} + - "--execution-policy" + - "--enable-execution" + {{- end }} + - "--interval={{ .Values.authorityExecutor.interval }}" +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/blockmaster.yaml b/seaweed-block/charts/seaweed-block/templates/blockmaster.yaml new file mode 100644 index 0000000000..53f340d92b --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/blockmaster.yaml @@ -0,0 +1,184 @@ +{{- if and .Values.network.externalISCSI (not .Values.chap.enabled) -}} +{{- fail "network.externalISCSI=true requires chap.enabled=true so cross-node iSCSI is not published without CHAP credentials" -}} +{{- end -}} +{{- if .Values.network.externalStatus -}} +{{- fail "network.externalStatus=true is not supported: blockmaster runs with mutual TLS and an authenticated volume's status listener stays on loopback" -}} +{{- end -}} +{{- if .Values.blockmaster.frontendPublicationRuntimeHTTP -}} +{{- fail "blockmaster.frontendPublicationRuntimeHTTP=true is not supported: the runtime HTTP API is unauthenticated and stays on loopback, out of reach of the executor pod" -}} +{{- end -}} +{{- if and (ne .Values.blockmaster.durableImpl "walstore") (not .Values.compat.launcherDurableImplFlag) -}} +{{- fail "blockmaster.durableImpl requires compat.launcherDurableImplFlag=true because older published images do not accept --launcher-durable-impl" -}} +{{- end -}} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-blockmaster + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} + app: sw-blockmaster +spec: + replicas: {{ .Values.blockmaster.replicas }} + selector: + matchLabels: + app: sw-blockmaster + template: + metadata: + labels: + app: sw-blockmaster + {{- include "seaweed-block.labels" . | nindent 8 }} + spec: + hostNetwork: true + dnsPolicy: ClusterFirstWithHostNet + serviceAccountName: {{ include "seaweed-block.fullname" . }}-master + {{- with .Values.blockmaster.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- if .Values.blockmaster.stateHostPath }} + initContainers: + - name: state-permissions + image: {{ include "seaweed-block.statePermissionsImage" . | quote }} + imagePullPolicy: {{ .Values.blockmaster.statePermissionsImage.pullPolicy }} + command: ["/bin/sh", "-c"] + args: + - "mkdir -p /var/lib/sw-block/authority /var/lib/sw-block/lifecycle && chown -R 65532:65532 /var/lib/sw-block" + securityContext: + runAsUser: 0 + volumeMounts: + - name: state + mountPath: /var/lib/sw-block + {{- end }} + containers: + - name: blockmaster + image: {{ include "seaweed-block.image" . | quote }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + command: ["/usr/local/bin/blockmaster"] + args: + - "--authority-store={{ .Values.blockmaster.authorityStore }}" + - "--lifecycle-store={{ .Values.blockmaster.lifecycleStore }}" + - "--cluster-spec=/config/cluster-spec.yaml" + - "--lifecycle-product-loop-interval={{ .Values.blockmaster.lifecycleProductLoopInterval }}" + - "--launcher-loop-interval={{ .Values.blockmaster.launcherLoopInterval }}" + - "--launcher-manifest-dir={{ .Values.blockmaster.launcherManifestDir }}" + - "--launcher-master-addr={{ include "seaweed-block.blockmasterAddress" . }}" + - "--launcher-image={{ include "seaweed-block.image" . }}" + - "--launcher-namespace={{ .Release.Namespace }}" + - "--launcher-durable-root={{ .Values.blockmaster.durableRoot }}" + {{- if .Values.compat.launcherDurableImplFlag }} + - "--launcher-durable-impl={{ .Values.blockmaster.durableImpl }}" + {{- end }} + {{- if .Values.blockmaster.durableWALMultiBlockRecords }} + - "--launcher-durable-wal-multiblock-records" + {{- end }} + {{- if .Values.blockmaster.durableWALRecoveryTestDisableFlusher }} + - "--launcher-durable-wal-recovery-test-disable-flusher" + {{- end }} + {{- if .Values.blockmaster.launcherStatus }} + - "--launcher-status" + {{- end }} + {{- if .Values.compat.launcherReplicationAckFlag }} + - "--launcher-replication-ack={{ .Values.replication.ackProfile }}" + {{- end }} + - "--launcher-iscsi-port-base={{ .Values.ports.iscsiBase }}" + - "--launcher-nvme-port-base={{ .Values.ports.nvmeBase }}" + {{- if ne (int .Values.nvme.maxH2CDataLength) 32768 }} + - "--launcher-nvme-max-h2c-data-length={{ .Values.nvme.maxH2CDataLength }}" + {{- end }} + {{- if .Values.blockmaster.launcherPVCOwnerRef }} + - "--launcher-pvc-owner-ref" + {{- end }} + {{- if .Values.blockmaster.stateHostPath }} + - "--launcher-state-hostpath={{ .Values.blockmaster.stateHostPath }}" + {{- end }} + {{- if .Values.network.externalISCSI }} + - "--launcher-external-iscsi" + - "--launcher-iscsi-chap-secret-name={{ .Values.chap.secretName }}" + - "--launcher-iscsi-chap-username-key={{ .Values.chap.usernameKey }}" + - "--launcher-iscsi-chap-secret-key={{ .Values.chap.secretKey }}" + {{- end }} + {{- if .Values.network.externalNVMe }} + - "--launcher-external-nvme" + {{- end }} + {{- if and .Values.network.rejectLoopbackPublishTargets .Values.compat.launcherRejectLoopbackFlag }} + - "--launcher-reject-loopback-publish-targets" + {{- end }} + - "--launcher-kubernetes-apply" + - "--listen=0.0.0.0:{{ .Values.blockmaster.listenPort }}" + - "--tls-cert=/etc/sw-block/tls/tls.crt" + - "--tls-key=/etc/sw-block/tls/tls.key" + - "--tls-client-ca=/etc/sw-block/tls/ca.crt" + - "--role-file=/etc/sw-block/roles/roles" + - "--audit-log=/var/lib/sw-block/audit.log" + - "--launcher-master-tls-secret-prefix={{ .Values.tls.nodeSecretPrefix }}" + {{- if .Values.blockmaster.failbackRuntimeRPC }} + - "--failback-runtime-rpc" + {{- end }} + {{- if .Values.blockmaster.frontendPublicationRuntimeHTTP }} + - "--frontend-publication-runtime-http" + - "--frontend-publication-runtime-listen=0.0.0.0:{{ .Values.blockmaster.frontendPublicationRuntimePort }}" + {{- end }} + - "--expected-slots-per-volume={{ include "seaweed-block.expectedSlotsPerVolume" . }}" + ports: + - name: grpc + containerPort: {{ .Values.blockmaster.listenPort }} + {{- if .Values.blockmaster.frontendPublicationRuntimeHTTP }} + - name: frontend-http + containerPort: {{ .Values.blockmaster.frontendPublicationRuntimePort }} + {{- end }} + volumeMounts: + - name: cluster-spec + mountPath: /config + readOnly: true + - name: state + mountPath: /var/lib/sw-block + - name: manifests + mountPath: /manifests + - name: tls + mountPath: /etc/sw-block/tls + readOnly: true + - name: roles + mountPath: /etc/sw-block/roles + readOnly: true + volumes: + - name: cluster-spec + configMap: + name: {{ include "seaweed-block.fullname" . }}-cluster-spec + - name: state + {{- if .Values.blockmaster.stateHostPath }} + hostPath: + path: {{ .Values.blockmaster.stateHostPath | quote }} + type: {{ .Values.blockmaster.stateHostPathType | quote }} + {{- else }} + emptyDir: {} + {{- end }} + - name: manifests + emptyDir: {} + - name: tls + secret: + secretName: {{ .Values.tls.masterSecret }} + - name: roles + secret: + secretName: {{ .Values.tls.roleSecret }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ .Values.blockmaster.serviceName }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} + app: sw-blockmaster +spec: + selector: + app: sw-blockmaster + ports: + - name: grpc + port: {{ .Values.blockmaster.listenPort }} + targetPort: grpc + {{- if .Values.blockmaster.frontendPublicationRuntimeHTTP }} + - name: frontend-http + port: {{ .Values.blockmaster.frontendPublicationRuntimePort }} + targetPort: frontend-http + {{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/chap-secret.yaml b/seaweed-block/charts/seaweed-block/templates/chap-secret.yaml new file mode 100644 index 0000000000..f7ec393f5a --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/chap-secret.yaml @@ -0,0 +1,27 @@ +{{- if and .Values.chap.enabled .Values.chap.create }} +apiVersion: v1 +kind: Secret +metadata: + name: {{ .Values.chap.secretName }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +type: Opaque +stringData: + {{ .Values.chap.usernameKey }}: {{ required "chap.username is required when chap.enabled=true" .Values.chap.username | quote }} + {{ .Values.chap.secretKey }}: {{ required "chap.secret is required when chap.enabled=true" .Values.chap.secret | quote }} +{{- if ne .Values.appNamespace .Release.Namespace }} +--- +apiVersion: v1 +kind: Secret +metadata: + name: {{ .Values.chap.secretName }} + namespace: {{ .Values.appNamespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +type: Opaque +stringData: + {{ .Values.chap.usernameKey }}: {{ .Values.chap.username | quote }} + {{ .Values.chap.secretKey }}: {{ .Values.chap.secret | quote }} +{{- end }} +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/cluster-spec-configmap.yaml b/seaweed-block/charts/seaweed-block/templates/cluster-spec-configmap.yaml new file mode 100644 index 0000000000..6d4008faa3 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/cluster-spec-configmap.yaml @@ -0,0 +1,29 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "seaweed-block.fullname" . }}-cluster-spec + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +data: + cluster-spec.yaml: | + nodes: +{{- range $i, $node := .Values.blockNodes }} +{{- $internalIP := required "blockNodes[].internalIP is required" $node.internalIP }} +{{- $frontendIP := default $internalIP $node.frontendIP }} +{{- $managementIP := default $internalIP $node.managementIP }} + - server_id: {{ default $node.name $node.serverID | quote }} + addr: {{ printf "%s:%v" $frontendIP (default 19101 $node.dataPort) | quote }} + data_addr: {{ printf "%s:%v" $frontendIP (default 19101 $node.dataPort) | quote }} + ctrl_addr: {{ printf "%s:%v" $internalIP (default 19102 $node.controlPort) | quote }} + labels: + kubernetes.io/hostname: {{ default $node.name $node.kubernetesNode | quote }} + sw-block.seaweedfs.com/management-ip: {{ $managementIP | quote }} + sw-block.seaweedfs.com/frontend-ip: {{ $frontendIP | quote }} + sw-block.seaweedfs.com/frontend-network-class: {{ default "management_lan" $node.frontendNetworkClass | quote }} + pools: + - pool_id: {{ default (printf "pool-%d" (add $i 1)) $node.poolID | quote }} + total_bytes: {{ default 1073741824 $node.totalBytes }} + free_bytes: {{ default 1073741824 $node.freeBytes }} + block_size: 4096 +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/csi-controller.yaml b/seaweed-block/charts/seaweed-block/templates/csi-controller.yaml new file mode 100644 index 0000000000..129c7e3e8e --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/csi-controller.yaml @@ -0,0 +1,75 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-block-csi-controller + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} + app: sw-block-csi-controller +spec: + replicas: {{ .Values.csiController.replicas }} + selector: + matchLabels: + app: sw-block-csi-controller + template: + metadata: + labels: + app: sw-block-csi-controller + {{- include "seaweed-block.labels" . | nindent 8 }} + spec: + serviceAccountName: {{ include "seaweed-block.fullname" . }}-csi + containers: + - name: block-csi + image: {{ include "seaweed-block.csiImage" . | quote }} + imagePullPolicy: {{ .Values.csiImage.pullPolicy }} + args: + - "--endpoint=unix:///csi/csi.sock" + - "--master=$(BLOCKMASTER_ADDR)" + - "--node-id=$(NODE_NAME)" + {{- include "seaweed-block.masterTLSClientFlags" . | nindent 12 }} + {{- if .Values.blockmaster.launcherPVCOwnerRef }} + - "--kubernetes-pvc-uid-lookup" + {{- end }} + {{- if or .Values.operatorStatus.create .Values.lifecycleOwner.create }} + - "--swblockvolume-cr-namespace={{ .Release.Namespace }}" + {{- end }} + {{- if .Values.stage2Multipath.enabled }} + - "--stage2-multipath" + {{- end }} + {{- if .Values.network.rejectLoopbackPublishTargets }} + - "--reject-loopback-publish-targets" + {{- end }} + env: + - name: BLOCKMASTER_ADDR + value: {{ include "seaweed-block.blockmasterAddress" . | quote }} + - name: NODE_NAME + valueFrom: + fieldRef: + fieldPath: spec.nodeName + volumeMounts: + - name: socket-dir + mountPath: /csi + {{- include "seaweed-block.masterTLSClientMount" . | nindent 12 }} + - name: csi-provisioner + image: {{ .Values.sidecars.provisionerImage | quote }} + args: + - "--csi-address=/csi/csi.sock" + - "--timeout=30s" + - "--leader-election=true" + - "--extra-create-metadata=true" + volumeMounts: + - name: socket-dir + mountPath: /csi + - name: csi-attacher + image: {{ .Values.sidecars.attacherImage | quote }} + args: + - "--csi-address=/csi/csi.sock" + - "--timeout=30s" + - "--leader-election=true" + volumeMounts: + - name: socket-dir + mountPath: /csi + volumes: + - name: socket-dir + emptyDir: {} + {{- include "seaweed-block.masterTLSClientVolume" .Values.tls.clientSecrets.csiController | nindent 8 }} diff --git a/seaweed-block/charts/seaweed-block/templates/csi-driver.yaml b/seaweed-block/charts/seaweed-block/templates/csi-driver.yaml new file mode 100644 index 0000000000..f9514abbbb --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/csi-driver.yaml @@ -0,0 +1,12 @@ +apiVersion: storage.k8s.io/v1 +kind: CSIDriver +metadata: + name: {{ .Values.driver.name }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +spec: + attachRequired: true + podInfoOnMount: false + fsGroupPolicy: File + volumeLifecycleModes: + - Persistent diff --git a/seaweed-block/charts/seaweed-block/templates/csi-node.yaml b/seaweed-block/charts/seaweed-block/templates/csi-node.yaml new file mode 100644 index 0000000000..0b30211398 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/csi-node.yaml @@ -0,0 +1,120 @@ +{{- include "seaweed-block.readOnlyClientSecrets" . }} +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: sw-block-csi-node + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} + app: sw-block-csi-node +spec: + selector: + matchLabels: + app: sw-block-csi-node + template: + metadata: + labels: + app: sw-block-csi-node + {{- include "seaweed-block.labels" . | nindent 8 }} + spec: + serviceAccountName: {{ include "seaweed-block.fullname" . }}-csi + hostNetwork: true + dnsPolicy: ClusterFirstWithHostNet + hostPID: true + {{- if .Values.csiNode.loadKernelModules }} + initContainers: + - name: load-iscsi-tcp + image: {{ include "seaweed-block.csiImage" . | quote }} + imagePullPolicy: {{ .Values.csiImage.pullPolicy }} + command: ["/bin/sh", "-c"] + args: + - "modprobe iscsi_tcp || true; modprobe nvme_tcp || true; modprobe nvme_rdma || true; modprobe dm_multipath || true; modprobe scsi_dh_alua || true" + securityContext: + privileged: true + volumeMounts: + - name: modules-dir + mountPath: /lib/modules + readOnly: true + {{- end }} + containers: + - name: block-csi + image: {{ include "seaweed-block.csiImage" . | quote }} + imagePullPolicy: {{ .Values.csiImage.pullPolicy }} + args: + - "--endpoint=unix:///csi/csi.sock" + - "--master=$(BLOCKMASTER_ADDR)" + - "--node-id=$(NODE_NAME)" + {{- include "seaweed-block.masterTLSClientFlags" . | nindent 12 }} + {{- if .Values.stage2Multipath.enabled }} + - "--stage2-multipath" + {{- end }} + {{- if .Values.csiNode.nvmeReconnect.enabled }} + - "--nvme-reconnect-owner" + - "--nvme-reconnect-interval={{ .Values.csiNode.nvmeReconnect.interval }}" + {{- end }} + {{- if .Values.network.rejectLoopbackPublishTargets }} + - "--reject-loopback-publish-targets" + {{- end }} + env: + - name: BLOCKMASTER_ADDR + value: {{ include "seaweed-block.blockmasterAddress" . | quote }} + - name: NODE_NAME + valueFrom: + fieldRef: + fieldPath: spec.nodeName + securityContext: + privileged: true + volumeMounts: + - name: socket-dir + mountPath: /csi + - name: kubelet-dir + mountPath: /var/lib/kubelet + mountPropagation: Bidirectional + - name: dev + mountPath: /dev + - name: iscsi-dir + mountPath: /etc/iscsi + - name: udev-run + mountPath: /run/udev + readOnly: true + {{- include "seaweed-block.masterTLSClientMount" . | nindent 12 }} + - name: csi-node-driver-registrar + image: {{ .Values.sidecars.nodeDriverRegistrarImage | quote }} + args: + - "--csi-address=/csi/csi.sock" + - "--kubelet-registration-path={{ .Values.csiNode.pluginPath }}/csi.sock" + volumeMounts: + - name: socket-dir + mountPath: /csi + - name: registration-dir + mountPath: /registration + volumes: + {{- include "seaweed-block.masterTLSClientVolume" .Values.tls.clientSecrets.csiNode | nindent 8 }} + - name: socket-dir + hostPath: + path: {{ .Values.csiNode.pluginPath | quote }} + type: DirectoryOrCreate + - name: kubelet-dir + hostPath: + path: {{ .Values.csiNode.kubeletPath | quote }} + type: Directory + - name: dev + hostPath: + path: /dev + type: Directory + - name: iscsi-dir + hostPath: + path: /etc/iscsi + type: DirectoryOrCreate + - name: udev-run + hostPath: + path: /run/udev + type: Directory + - name: modules-dir + hostPath: + path: /lib/modules + type: Directory + - name: registration-dir + hostPath: + path: {{ .Values.csiNode.registrationPath | quote }} + type: Directory diff --git a/seaweed-block/charts/seaweed-block/templates/failback-executor-rbac.yaml b/seaweed-block/charts/seaweed-block/templates/failback-executor-rbac.yaml new file mode 100644 index 0000000000..c88ec391e2 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/failback-executor-rbac.yaml @@ -0,0 +1,38 @@ +{{- if and .Values.failbackExecutor.create .Values.failbackExecutor.rbac.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "seaweed-block.fullname" . }}-failback-executor + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "seaweed-block.fullname" . }}-failback-executor + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +rules: + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockreplicafailbacks"] + verbs: ["get", "list", "watch"] + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockreplicafailbacks/status"] + verbs: ["get", "update", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "seaweed-block.fullname" . }}-failback-executor + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +subjects: + - kind: ServiceAccount + name: {{ include "seaweed-block.fullname" . }}-failback-executor + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "seaweed-block.fullname" . }}-failback-executor +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/failback-executor.yaml b/seaweed-block/charts/seaweed-block/templates/failback-executor.yaml new file mode 100644 index 0000000000..466a444d26 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/failback-executor.yaml @@ -0,0 +1,72 @@ +{{- if .Values.failbackExecutor.create }} +{{- if and .Values.failbackExecutor.execution.enabled .Values.failbackExecutor.dryRun -}} +{{- fail "failbackExecutor.execution.enabled=true requires failbackExecutor.dryRun=false" -}} +{{- end -}} +{{- if and .Values.failbackExecutor.execution.enabled (not .Values.failbackExecutor.execution.policy) -}} +{{- fail "failbackExecutor.execution.enabled=true requires failbackExecutor.execution.policy=true" -}} +{{- end -}} +{{- if and .Values.failbackExecutor.execution.failbackRuntimeGrpcAddr (not .Values.failbackExecutor.execution.enabled) -}} +{{- fail "failbackExecutor.execution.failbackRuntimeGrpcAddr requires failbackExecutor.execution.enabled=true" -}} +{{- end -}} +{{- if and .Values.failbackExecutor.execution.failbackRuntimeURL (not .Values.failbackExecutor.execution.enabled) -}} +{{- fail "failbackExecutor.execution.failbackRuntimeURL requires failbackExecutor.execution.enabled=true" -}} +{{- end -}} +{{- if and .Values.failbackExecutor.execution.failbackRuntimeGrpcAddr .Values.failbackExecutor.execution.failbackRuntimeURL -}} +{{- fail "failbackExecutor.execution.failbackRuntimeGrpcAddr and failbackExecutor.execution.failbackRuntimeURL are mutually exclusive" -}} +{{- end -}} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-block-failback-executor + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} + app: sw-block-failback-executor +spec: + replicas: 1 + selector: + matchLabels: + app: sw-block-failback-executor + template: + metadata: + labels: + app: sw-block-failback-executor + {{- include "seaweed-block.labels" . | nindent 8 }} + spec: + serviceAccountName: {{ include "seaweed-block.fullname" . }}-failback-executor + {{- with .Values.failbackExecutor.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + containers: + - name: failback-executor + image: {{ include "seaweed-block.image" . | quote }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + command: ["/usr/local/bin/sw-block"] + args: + - "ops" + - "failback-executor" + - "--namespace={{ .Release.Namespace }}" + {{- if .Values.failbackExecutor.dryRun }} + - "--dry-run" + {{- end }} + {{- if .Values.failbackExecutor.execution.enabled }} + - "--enable-execution" + {{- end }} + {{- if .Values.failbackExecutor.execution.policy }} + - "--execution-policy" + {{- end }} + {{- if .Values.failbackExecutor.execution.failbackRuntimeGrpcAddr }} + - "--failback-runtime-grpc-addr={{ .Values.failbackExecutor.execution.failbackRuntimeGrpcAddr }}" + {{- end }} + {{- if .Values.failbackExecutor.execution.failbackRuntimeURL }} + - "--failback-runtime-url={{ .Values.failbackExecutor.execution.failbackRuntimeURL }}" + {{- end }} + - "--interval={{ .Values.failbackExecutor.interval }}" + env: + {{- include "seaweed-block.masterTLSClientEnv" . | nindent 12 }} + volumeMounts: + {{- include "seaweed-block.masterTLSClientMount" . | nindent 12 }} + volumes: + {{- include "seaweed-block.masterTLSClientVolume" .Values.tls.clientSecrets.failbackExecutor | nindent 8 }} +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/failback-target-owner-rbac.yaml b/seaweed-block/charts/seaweed-block/templates/failback-target-owner-rbac.yaml new file mode 100644 index 0000000000..9fdc423933 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/failback-target-owner-rbac.yaml @@ -0,0 +1,38 @@ +{{- if and .Values.failbackTargetOwner.create .Values.failbackTargetOwner.rbac.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "seaweed-block.fullname" . }}-failback-target-owner + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "seaweed-block.fullname" . }}-failback-target-owner + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +rules: + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockvolumes"] + verbs: ["get", "list", "watch"] + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockreplicafailbacks"] + verbs: ["get", "list", "watch", "create"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "seaweed-block.fullname" . }}-failback-target-owner + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +subjects: + - kind: ServiceAccount + name: {{ include "seaweed-block.fullname" . }}-failback-target-owner + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "seaweed-block.fullname" . }}-failback-target-owner +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/failback-target-owner.yaml b/seaweed-block/charts/seaweed-block/templates/failback-target-owner.yaml new file mode 100644 index 0000000000..0981286627 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/failback-target-owner.yaml @@ -0,0 +1,48 @@ +{{- if .Values.failbackTargetOwner.create }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-block-failback-target-owner + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} + app: sw-block-failback-target-owner +spec: + replicas: 1 + selector: + matchLabels: + app: sw-block-failback-target-owner + template: + metadata: + labels: + app: sw-block-failback-target-owner + {{- include "seaweed-block.labels" . | nindent 8 }} + spec: + serviceAccountName: {{ include "seaweed-block.fullname" . }}-failback-target-owner + {{- with .Values.failbackTargetOwner.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + containers: + - name: failback-target-owner + image: {{ include "seaweed-block.image" . | quote }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + command: ["/usr/local/bin/sw-block"] + args: + - "ops" + - "failback-target-owner" + - "--namespace={{ .Release.Namespace }}" + {{- if .Values.failbackTargetOwner.dryRun }} + - "--dry-run" + {{- end }} + - "--interval={{ .Values.failbackTargetOwner.interval }}" + {{- if .Values.failbackTargetOwner.activation.enabled }} + - "--activate-targets" + {{- end }} + {{- if .Values.failbackTargetOwner.activation.policy }} + - "--activation-policy" + {{- end }} + {{- if .Values.failbackTargetOwner.activation.runtimeEndpoint }} + - "--runtime-endpoint={{ .Values.failbackTargetOwner.activation.runtimeEndpoint }}" + {{- end }} +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/frontend-publication-executor-rbac.yaml b/seaweed-block/charts/seaweed-block/templates/frontend-publication-executor-rbac.yaml new file mode 100644 index 0000000000..f8251fbeb3 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/frontend-publication-executor-rbac.yaml @@ -0,0 +1,32 @@ +{{- if and .Values.frontendPublicationExecutor.create .Values.frontendPublicationExecutor.rbac.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "seaweed-block.fullname" . }}-frontend-publication-executor + namespace: {{ .Release.Namespace }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "seaweed-block.fullname" . }}-frontend-publication-executor +rules: + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockfrontendpublications"] + verbs: ["get", "list", "watch"] + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockfrontendpublications/status"] + verbs: ["get", "update", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "seaweed-block.fullname" . }}-frontend-publication-executor +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "seaweed-block.fullname" . }}-frontend-publication-executor +subjects: + - kind: ServiceAccount + name: {{ include "seaweed-block.fullname" . }}-frontend-publication-executor + namespace: {{ .Release.Namespace }} +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/frontend-publication-executor.yaml b/seaweed-block/charts/seaweed-block/templates/frontend-publication-executor.yaml new file mode 100644 index 0000000000..afa4608e09 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/frontend-publication-executor.yaml @@ -0,0 +1,46 @@ +{{- if .Values.frontendPublicationExecutor.create }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-block-frontend-publication-executor + namespace: {{ .Release.Namespace }} + labels: + app: sw-block-frontend-publication-executor +spec: + replicas: 1 + selector: + matchLabels: + app: sw-block-frontend-publication-executor + template: + metadata: + labels: + app: sw-block-frontend-publication-executor + spec: + serviceAccountName: {{ include "seaweed-block.fullname" . }}-frontend-publication-executor + {{- with .Values.frontendPublicationExecutor.nodeSelector }} + nodeSelector: +{{ toYaml . | indent 8 }} + {{- end }} + containers: + - name: frontend-publication-executor + image: {{ include "seaweed-block.image" . }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + command: ["/usr/local/bin/sw-block"] + args: + - "ops" + - "frontend-publication-executor" + - "--namespace={{ .Release.Namespace }}" + {{- if .Values.frontendPublicationExecutor.dryRun }} + - "--dry-run" + {{- end }} + {{- if .Values.frontendPublicationExecutor.execution.enabled }} + - "--enable-execution" + {{- end }} + {{- if .Values.frontendPublicationExecutor.execution.policy }} + - "--execution-policy" + {{- end }} + {{- if .Values.frontendPublicationExecutor.execution.runtimeUrl }} + - "--frontend-publication-runtime-url={{ .Values.frontendPublicationExecutor.execution.runtimeUrl }}" + {{- end }} + - "--interval={{ .Values.frontendPublicationExecutor.interval }}" +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/frontend-publication-target-owner-rbac.yaml b/seaweed-block/charts/seaweed-block/templates/frontend-publication-target-owner-rbac.yaml new file mode 100644 index 0000000000..22d9ce2b8c --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/frontend-publication-target-owner-rbac.yaml @@ -0,0 +1,35 @@ +{{- if and .Values.frontendPublicationTargetOwner.create .Values.frontendPublicationTargetOwner.rbac.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "seaweed-block.fullname" . }}-frontend-publication-target-owner + namespace: {{ .Release.Namespace }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "seaweed-block.fullname" . }}-frontend-publication-target-owner +rules: + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockreplicaeligibilities"] + verbs: ["get", "list", "watch"] + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockreplicafailbacks"] + verbs: ["get", "list", "watch"] + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockfrontendpublications"] + verbs: ["get", "list", "watch", "create"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "seaweed-block.fullname" . }}-frontend-publication-target-owner +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "seaweed-block.fullname" . }}-frontend-publication-target-owner +subjects: + - kind: ServiceAccount + name: {{ include "seaweed-block.fullname" . }}-frontend-publication-target-owner + namespace: {{ .Release.Namespace }} +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/frontend-publication-target-owner.yaml b/seaweed-block/charts/seaweed-block/templates/frontend-publication-target-owner.yaml new file mode 100644 index 0000000000..15c13f4baa --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/frontend-publication-target-owner.yaml @@ -0,0 +1,46 @@ +{{- if .Values.frontendPublicationTargetOwner.create }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-block-frontend-publication-target-owner + namespace: {{ .Release.Namespace }} + labels: + app: sw-block-frontend-publication-target-owner +spec: + replicas: 1 + selector: + matchLabels: + app: sw-block-frontend-publication-target-owner + template: + metadata: + labels: + app: sw-block-frontend-publication-target-owner + spec: + serviceAccountName: {{ include "seaweed-block.fullname" . }}-frontend-publication-target-owner + {{- with .Values.frontendPublicationTargetOwner.nodeSelector }} + nodeSelector: +{{ toYaml . | indent 8 }} + {{- end }} + containers: + - name: frontend-publication-target-owner + image: {{ include "seaweed-block.image" . }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + command: ["/usr/local/bin/sw-block"] + args: + - "ops" + - "frontend-publication-target-owner" + - "--namespace={{ .Release.Namespace }}" + {{- if .Values.frontendPublicationTargetOwner.dryRun }} + - "--dry-run" + {{- end }} + {{- if .Values.frontendPublicationTargetOwner.activation.enabled }} + - "--activate-targets" + {{- end }} + {{- if .Values.frontendPublicationTargetOwner.activation.policy }} + - "--activation-policy" + {{- end }} + {{- if .Values.frontendPublicationTargetOwner.activation.runtimeEndpoint }} + - "--runtime-endpoint={{ .Values.frontendPublicationTargetOwner.activation.runtimeEndpoint }}" + {{- end }} + - "--interval={{ .Values.frontendPublicationTargetOwner.interval }}" +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/lifecycle-owner-admission.yaml b/seaweed-block/charts/seaweed-block/templates/lifecycle-owner-admission.yaml new file mode 100644 index 0000000000..822b485d98 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/lifecycle-owner-admission.yaml @@ -0,0 +1,47 @@ +{{- if and .Values.lifecycleOwner.create .Values.lifecycleOwner.admission.create }} +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: {{ include "seaweed-block.fullname" . }}-lifecycle-owner-finalizer-boundary + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - apiGroups: ["block.seaweedfs.com"] + apiVersions: ["v1alpha1"] + operations: ["UPDATE"] + resources: ["swblockvolumes"] + validations: + - expression: >- + request.userInfo.username != "system:serviceaccount:{{ .Release.Namespace }}:{{ include "seaweed-block.fullname" . }}-lifecycle-owner" || + ( + (has(object.spec) == has(oldObject.spec)) && + (!has(object.spec) || object.spec == oldObject.spec) && + (has(object.status) == has(oldObject.status)) && + (!has(object.status) || object.status == oldObject.status) && + (has(object.metadata.labels) == has(oldObject.metadata.labels)) && + (!has(object.metadata.labels) || object.metadata.labels == oldObject.metadata.labels) && + (has(object.metadata.annotations) == has(oldObject.metadata.annotations)) && + (!has(object.metadata.annotations) || object.metadata.annotations == oldObject.metadata.annotations) && + (has(object.metadata.ownerReferences) == has(oldObject.metadata.ownerReferences)) && + (!has(object.metadata.ownerReferences) || object.metadata.ownerReferences == oldObject.metadata.ownerReferences) && + (has(object.metadata.deletionTimestamp) == has(oldObject.metadata.deletionTimestamp)) && + (!has(object.metadata.deletionTimestamp) || object.metadata.deletionTimestamp == oldObject.metadata.deletionTimestamp) && + ((has(object.metadata.finalizers) ? object.metadata.finalizers : []).filter(f, f != "{{ .Values.lifecycleOwner.finalizerName | default "block.seaweedfs.com/swblockvolume-protection" }}") == + (has(oldObject.metadata.finalizers) ? oldObject.metadata.finalizers : []).filter(f, f != "{{ .Values.lifecycleOwner.finalizerName | default "block.seaweedfs.com/swblockvolume-protection" }}")) && + ((has(object.metadata.finalizers) ? object.metadata.finalizers : []).filter(f, f == "{{ .Values.lifecycleOwner.finalizerName | default "block.seaweedfs.com/swblockvolume-protection" }}").size() <= 1) + ) + message: lifecycle-owner may only add or remove the Seaweed Block protection finalizer +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: {{ include "seaweed-block.fullname" . }}-lifecycle-owner-finalizer-boundary + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +spec: + policyName: {{ include "seaweed-block.fullname" . }}-lifecycle-owner-finalizer-boundary + validationActions: ["Deny"] +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/lifecycle-owner-rbac.yaml b/seaweed-block/charts/seaweed-block/templates/lifecycle-owner-rbac.yaml new file mode 100644 index 0000000000..d8939534ea --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/lifecycle-owner-rbac.yaml @@ -0,0 +1,38 @@ +{{- if and .Values.lifecycleOwner.create .Values.lifecycleOwner.rbac.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "seaweed-block.fullname" . }}-lifecycle-owner + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "seaweed-block.fullname" . }}-lifecycle-owner + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +rules: + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockvolumes"] + verbs: ["get", "list", "watch", "patch"] + - apiGroups: [""] + resources: ["events"] + verbs: ["create"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "seaweed-block.fullname" . }}-lifecycle-owner + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +subjects: + - kind: ServiceAccount + name: {{ include "seaweed-block.fullname" . }}-lifecycle-owner + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "seaweed-block.fullname" . }}-lifecycle-owner +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/lifecycle-owner.yaml b/seaweed-block/charts/seaweed-block/templates/lifecycle-owner.yaml new file mode 100644 index 0000000000..13b8ddf75b --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/lifecycle-owner.yaml @@ -0,0 +1,39 @@ +{{- if .Values.lifecycleOwner.create }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-block-lifecycle-owner + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} + app: sw-block-lifecycle-owner +spec: + replicas: 1 + selector: + matchLabels: + app: sw-block-lifecycle-owner + template: + metadata: + labels: + app: sw-block-lifecycle-owner + {{- include "seaweed-block.labels" . | nindent 8 }} + spec: + serviceAccountName: {{ include "seaweed-block.fullname" . }}-lifecycle-owner + {{- with .Values.lifecycleOwner.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + containers: + - name: lifecycle-owner + image: {{ include "seaweed-block.image" . | quote }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + command: ["/usr/local/bin/sw-block"] + args: + - "ops" + - "lifecycle-owner" + {{- if .Values.lifecycleOwner.dryRun }} + - "--dry-run" + {{- end }} + - "--namespace={{ .Release.Namespace }}" + - "--interval={{ .Values.lifecycleOwner.interval }}" +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/operator-status-rbac.yaml b/seaweed-block/charts/seaweed-block/templates/operator-status-rbac.yaml new file mode 100644 index 0000000000..e8f8568c0c --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/operator-status-rbac.yaml @@ -0,0 +1,47 @@ +{{- if and .Values.operatorStatus.create .Values.operatorStatus.rbac.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "seaweed-block.fullname" . }}-operator-status + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "seaweed-block.fullname" . }}-operator-status + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +rules: + - apiGroups: [""] + resources: ["nodes", "pods"] + verbs: ["get", "list", "watch"] + - apiGroups: ["storage.k8s.io"] + resources: ["csidrivers", "csinodes"] + verbs: ["get", "list", "watch"] + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockclusters", "swblockvolumes"] + verbs: ["get", "list", "watch"] + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockclusters/status", "swblockvolumes/status"] + verbs: ["get", "update", "patch"] + - apiGroups: [""] + resources: ["events"] + verbs: ["create"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "seaweed-block.fullname" . }}-operator-status + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +subjects: + - kind: ServiceAccount + name: {{ include "seaweed-block.fullname" . }}-operator-status + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "seaweed-block.fullname" . }}-operator-status +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/operator-status.yaml b/seaweed-block/charts/seaweed-block/templates/operator-status.yaml new file mode 100644 index 0000000000..d6074ee00d --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/operator-status.yaml @@ -0,0 +1,48 @@ +{{- if .Values.operatorStatus.create }} +{{- include "seaweed-block.readOnlyClientSecrets" . }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-block-operator-status + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} + app: sw-block-operator-status +spec: + replicas: 1 + selector: + matchLabels: + app: sw-block-operator-status + template: + metadata: + labels: + app: sw-block-operator-status + {{- include "seaweed-block.labels" . | nindent 8 }} + spec: + serviceAccountName: {{ include "seaweed-block.fullname" . }}-operator-status + {{- with .Values.operatorStatus.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + containers: + - name: operator-status + image: {{ include "seaweed-block.image" . | quote }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + command: ["/usr/local/bin/sw-block"] + args: + - "ops" + - "operator-status" + {{- if .Values.operatorStatus.dryRun }} + - "--dry-run" + {{- end }} + - "--master-api={{ include "seaweed-block.blockmasterAddress" . }}" + - "--namespace={{ .Release.Namespace }}" + - "--cluster-name={{ .Values.operatorStatus.clusterName }}" + - "--interval={{ .Values.operatorStatus.interval }}" + env: + {{- include "seaweed-block.masterTLSClientEnv" . | nindent 12 }} + volumeMounts: + {{- include "seaweed-block.masterTLSClientMount" . | nindent 12 }} + volumes: + {{- include "seaweed-block.masterTLSClientVolume" .Values.tls.clientSecrets.operatorStatus | nindent 8 }} +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/rbac.yaml b/seaweed-block/charts/seaweed-block/templates/rbac.yaml new file mode 100644 index 0000000000..6e0a6cceb4 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/rbac.yaml @@ -0,0 +1,83 @@ +{{- if .Values.rbac.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "seaweed-block.fullname" . }}-csi + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "seaweed-block.fullname" . }}-master + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "seaweed-block.fullname" . }}-master-launcher + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +rules: + - apiGroups: ["apps"] + resources: ["deployments"] + verbs: ["get", "list", "watch", "create", "delete", "update", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "seaweed-block.fullname" . }}-master-launcher + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +subjects: + - kind: ServiceAccount + name: {{ include "seaweed-block.fullname" . }}-master + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "seaweed-block.fullname" . }}-master-launcher +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "seaweed-block.fullname" . }}-csi-controller + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +rules: + - apiGroups: [""] + resources: ["persistentvolumes", "persistentvolumeclaims", "nodes"] + verbs: ["get", "list", "watch", "create", "delete", "update", "patch"] + - apiGroups: [""] + resources: ["events"] + verbs: ["get", "list", "watch", "create", "update", "patch"] + - apiGroups: ["storage.k8s.io"] + resources: ["storageclasses", "volumeattachments", "volumeattachments/status", "csinodes", "csidrivers"] + verbs: ["get", "list", "watch", "create", "delete", "update", "patch"] + - apiGroups: ["coordination.k8s.io"] + resources: ["leases"] + verbs: ["get", "list", "watch", "create", "update", "patch"] + {{- if or .Values.operatorStatus.create .Values.lifecycleOwner.create }} + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockvolumes"] + verbs: ["get", "list", "watch", "create", "update", "patch"] + {{- end }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "seaweed-block.fullname" . }}-csi-controller + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +subjects: + - kind: ServiceAccount + name: {{ include "seaweed-block.fullname" . }}-csi + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "seaweed-block.fullname" . }}-csi-controller +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/rebuild-target-owner-rbac.yaml b/seaweed-block/charts/seaweed-block/templates/rebuild-target-owner-rbac.yaml new file mode 100644 index 0000000000..41ea1c6c18 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/rebuild-target-owner-rbac.yaml @@ -0,0 +1,38 @@ +{{- if and .Values.rebuildTargetOwner.create .Values.rebuildTargetOwner.rbac.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "seaweed-block.fullname" . }}-rebuild-target-owner + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "seaweed-block.fullname" . }}-rebuild-target-owner + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +rules: + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockvolumes"] + verbs: ["get", "list", "watch"] + - apiGroups: ["block.seaweedfs.com"] + resources: ["swblockreplicarebuilds"] + verbs: ["get", "list", "watch", "create"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "seaweed-block.fullname" . }}-rebuild-target-owner + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +subjects: + - kind: ServiceAccount + name: {{ include "seaweed-block.fullname" . }}-rebuild-target-owner + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "seaweed-block.fullname" . }}-rebuild-target-owner +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/rebuild-target-owner.yaml b/seaweed-block/charts/seaweed-block/templates/rebuild-target-owner.yaml new file mode 100644 index 0000000000..bad40e5f39 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/rebuild-target-owner.yaml @@ -0,0 +1,39 @@ +{{- if .Values.rebuildTargetOwner.create }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-block-rebuild-target-owner + namespace: {{ .Release.Namespace }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} + app: sw-block-rebuild-target-owner +spec: + replicas: 1 + selector: + matchLabels: + app: sw-block-rebuild-target-owner + template: + metadata: + labels: + app: sw-block-rebuild-target-owner + {{- include "seaweed-block.labels" . | nindent 8 }} + spec: + serviceAccountName: {{ include "seaweed-block.fullname" . }}-rebuild-target-owner + {{- with .Values.rebuildTargetOwner.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + containers: + - name: rebuild-target-owner + image: {{ include "seaweed-block.image" . | quote }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + command: ["/usr/local/bin/sw-block"] + args: + - "ops" + - "rebuild-target-owner" + - "--namespace={{ .Release.Namespace }}" + {{- if .Values.rebuildTargetOwner.dryRun }} + - "--dry-run" + {{- end }} + - "--interval={{ .Values.rebuildTargetOwner.interval }}" +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/templates/storageclass.yaml b/seaweed-block/charts/seaweed-block/templates/storageclass.yaml new file mode 100644 index 0000000000..43e5b5bc11 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/templates/storageclass.yaml @@ -0,0 +1,28 @@ +{{- if .Values.storageClass.create }} +{{- if and (eq .Values.storageClass.nvmeTransport "rdma") (ne .Values.storageClass.protocol "nvme") }} +{{- fail "storageClass.nvmeTransport=rdma requires storageClass.protocol=nvme" }} +{{- end }} +{{- if and (eq .Values.storageClass.nvmeTransport "rdma") (not .Values.network.externalNVMe) }} +{{- fail "storageClass.nvmeTransport=rdma requires network.externalNVMe=true" }} +{{- end }} +apiVersion: storage.k8s.io/v1 +kind: StorageClass +metadata: + name: {{ .Values.storageClass.name }} + labels: + {{- include "seaweed-block.labels" . | nindent 4 }} +provisioner: {{ .Values.driver.name }} +reclaimPolicy: {{ .Values.storageClass.reclaimPolicy }} +volumeBindingMode: {{ .Values.storageClass.volumeBindingMode }} +allowVolumeExpansion: {{ .Values.storageClass.allowVolumeExpansion }} +parameters: + replicationFactor: {{ .Values.storageClass.replicationFactor | quote }} + sw-block.seaweedfs.com/protocol: {{ .Values.storageClass.protocol | quote }} + {{- if eq .Values.storageClass.protocol "nvme" }} + sw-block.seaweedfs.com/nvme-transport: {{ .Values.storageClass.nvmeTransport | quote }} + {{- end }} + {{- if and .Values.chap.enabled .Values.storageClass.nodeStageSecret.enabled }} + csi.storage.k8s.io/node-stage-secret-name: {{ .Values.chap.secretName | quote }} + csi.storage.k8s.io/node-stage-secret-namespace: {{ .Values.appNamespace | quote }} + {{- end }} +{{- end }} diff --git a/seaweed-block/charts/seaweed-block/values.schema.json b/seaweed-block/charts/seaweed-block/values.schema.json new file mode 100644 index 0000000000..36e66c157c --- /dev/null +++ b/seaweed-block/charts/seaweed-block/values.schema.json @@ -0,0 +1,204 @@ +{ + "$schema": "https://json-schema.org/draft-07/schema#", + "type": "object", + "properties": { + "image": { + "type": "object", + "properties": { + "repository": { "type": "string", "minLength": 1 }, + "tag": { "type": "string" }, + "digest": { "type": "string" }, + "pullPolicy": { "type": "string" } + } + }, + "csiImage": { + "type": "object", + "properties": { + "repository": { "type": "string", "minLength": 1 }, + "tag": { "type": "string" }, + "digest": { "type": "string" }, + "pullPolicy": { "type": "string" } + } + }, + "storageClass": { + "type": "object", + "properties": { + "replicationFactor": { "type": "integer", "minimum": 1 }, + "protocol": { "type": "string", "enum": ["iscsi", "nvme"] }, + "nvmeTransport": { "type": "string", "enum": ["tcp", "rdma"] } + } + }, + "blockmaster": { + "type": "object", + "properties": { + "nodeSelector": { + "type": "object", + "additionalProperties": { "type": "string" } + }, + "failbackRuntimeRPC": { "type": "boolean" }, + "durableImpl": { "type": "string", "enum": ["walstore"] }, + "durableWALMultiBlockRecords": { "type": "boolean" }, + "durableWALRecoveryTestDisableFlusher": { "type": "boolean" }, + "stateHostPath": { "type": "string" }, + "stateHostPathType": { "type": "string" }, + "statePermissionsImage": { + "type": "object", + "properties": { + "repository": { "type": "string", "minLength": 1 }, + "tag": { "type": "string" }, + "digest": { "type": "string" }, + "pullPolicy": { "type": "string" } + } + } + } + }, + "restartPersistence": { + "type": "object", + "properties": { + "mode": { "type": "string", "enum": ["ephemeral", "hostpath"] }, + "stateHostPath": { "type": "string" } + } + }, + "tls": { + "type": "object", + "properties": { + "masterSecret": { "type": "string", "minLength": 1 }, + "roleSecret": { "type": "string", "minLength": 1 }, + "clientSecrets": { + "type": "object", + "required": ["csiController", "csiNode", "operatorStatus", "failbackExecutor"], + "properties": { + "csiController": { "type": "string", "minLength": 1 }, + "csiNode": { "type": "string", "minLength": 1 }, + "operatorStatus": { "type": "string", "minLength": 1 }, + "failbackExecutor": { "type": "string", "minLength": 1 } + } + }, + "nodeSecretPrefix": { "type": "string", "minLength": 1 } + } + }, + "network": { + "type": "object", + "properties": { + "externalISCSI": { "type": "boolean" }, + "externalNVMe": { "type": "boolean" }, + "externalStatus": { "type": "boolean" }, + "rejectLoopbackPublishTargets": { "type": "boolean" } + } + }, + "ports": { + "type": "object", + "properties": { + "iscsiBase": { "type": "integer", "minimum": 1, "maximum": 65535 }, + "nvmeBase": { "type": "integer", "minimum": 1, "maximum": 65535 }, + "statusBase": { "type": "integer", "minimum": 1, "maximum": 65535 } + } + }, + "nvme": { + "type": "object", + "properties": { + "maxH2CDataLength": { "type": "integer", "minimum": 32768, "maximum": 1048576 } + } + }, + "compat": { + "type": "object", + "properties": { + "launcherDurableImplFlag": { "type": "boolean" }, + "launcherReplicationAckFlag": { "type": "boolean" }, + "launcherRejectLoopbackFlag": { "type": "boolean" } + } + }, + "blockNodes": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": ["name", "internalIP"], + "properties": { + "name": { "type": "string", "minLength": 1 }, + "serverID": { "type": "string" }, + "internalIP": { "type": "string", "minLength": 1 }, + "managementIP": { "type": "string" }, + "frontendIP": { "type": "string" }, + "frontendNetworkClass": { "type": "string" }, + "dataPort": { "type": "integer", "minimum": 1 }, + "controlPort": { "type": "integer", "minimum": 1 }, + "ctrlPort": { "type": "integer", "minimum": 1 }, + "poolID": { "type": "string" } + } + } + }, + "operatorStatus": { + "type": "object", + "properties": { + "create": { "type": "boolean" }, + "dryRun": { "type": "boolean" }, + "interval": { "type": "string" }, + "clusterName": { "type": "string" }, + "rbac": { + "type": "object", + "properties": { + "create": { "type": "boolean" } + } + }, + "nodeSelector": { + "type": "object", + "additionalProperties": { "type": "string" } + } + } + }, + "failbackTargetOwner": { + "type": "object", + "properties": { + "create": { "type": "boolean" }, + "dryRun": { "type": "boolean" }, + "interval": { "type": "string" }, + "activation": { + "type": "object", + "properties": { + "enabled": { "type": "boolean" }, + "policy": { "type": "boolean" }, + "runtimeEndpoint": { "type": "string" } + } + }, + "rbac": { + "type": "object", + "properties": { + "create": { "type": "boolean" } + } + }, + "nodeSelector": { + "type": "object", + "additionalProperties": { "type": "string" } + } + } + }, + "failbackExecutor": { + "type": "object", + "properties": { + "create": { "type": "boolean" }, + "dryRun": { "type": "boolean" }, + "interval": { "type": "string" }, + "execution": { + "type": "object", + "properties": { + "enabled": { "type": "boolean" }, + "policy": { "type": "boolean" }, + "failbackRuntimeGrpcAddr": { "type": "string" }, + "failbackRuntimeURL": { "type": "string" } + } + }, + "rbac": { + "type": "object", + "properties": { + "create": { "type": "boolean" } + } + }, + "nodeSelector": { + "type": "object", + "additionalProperties": { "type": "string" } + } + } + } + } +} diff --git a/seaweed-block/charts/seaweed-block/values.yaml b/seaweed-block/charts/seaweed-block/values.yaml new file mode 100644 index 0000000000..43828d0541 --- /dev/null +++ b/seaweed-block/charts/seaweed-block/values.yaml @@ -0,0 +1,289 @@ +# Seaweed Block Helm values. +# +# This chart packages the existing alpha Kubernetes install path. It does not +# claim operator lifecycle, backup/restore, upgrade safety, or mutating admin +# actions. + +image: + repository: ghcr.io/seaweedfs/seaweed-block + tag: alpha + digest: "" + pullPolicy: IfNotPresent + +csiImage: + repository: ghcr.io/seaweedfs/seaweed-block-csi + tag: alpha + digest: "" + pullPolicy: IfNotPresent + +sidecars: + provisionerImage: registry.k8s.io/sig-storage/csi-provisioner:v5.2.0 + attacherImage: registry.k8s.io/sig-storage/csi-attacher:v4.8.1 + nodeDriverRegistrarImage: registry.k8s.io/sig-storage/csi-node-driver-registrar:v2.13.0 + +driver: + name: block.csi.seaweedfs.com + +appNamespace: default + +blockmaster: + replicas: 1 + nodeSelector: {} + serviceName: blockmaster + listenPort: 9333 + failbackRuntimeRPC: false + frontendPublicationRuntimeHTTP: false + frontendPublicationRuntimePort: 9334 + authorityStore: /var/lib/sw-block/authority + lifecycleStore: /var/lib/sw-block/lifecycle + durableRoot: /var/lib/sw-block + lifecycleProductLoopInterval: 100ms + launcherLoopInterval: 100ms + launcherManifestDir: /manifests + launcherNamespace: kube-system + launcherStatus: true + launcherPVCOwnerRef: true + durableImpl: walstore + durableWALMultiBlockRecords: false + durableWALRecoveryTestDisableFlusher: false + stateHostPath: "" + stateHostPathType: DirectoryOrCreate + statePermissionsImage: + repository: busybox + tag: "1.36" + digest: "" + pullPolicy: IfNotPresent + +restartPersistence: + # ephemeral keeps the alpha/dev default. hostpath persists blockmaster and + # generated blockvolume state across Kubernetes pod restarts. + mode: ephemeral + stateHostPath: "" + +storageClass: + create: true + name: sw-block-dynamic + reclaimPolicy: Delete + volumeBindingMode: Immediate + allowVolumeExpansion: false + replicationFactor: 1 + protocol: iscsi + # tcp is the backward-compatible NVMe fabric. Set protocol=nvme and + # nvmeTransport=rdma to opt into the kernel NVMe/RDMA path. + nvmeTransport: tcp + nodeStageSecret: + enabled: true + +replication: + ackProfile: best-effort + expectedSlotsPerVolume: 0 + +# blockmaster listens on the pod network only with mutual TLS: create these +# Secrets before installing (docs/operator-guide.md, "Authenticate the control +# API"). Every certificate is signed by the CA in each Secret's ca.crt. +tls: + # blockmaster's own certificate (tls.crt, tls.key) and the CA every client + # certificate must verify against (ca.crt). Its subjectAltName must include + # the blockmaster Service name the clients dial. + masterSecret: sw-block-master-tls + # The role file (key "roles"): one line per certificate, + # "sha256: ". + roleSecret: sw-block-roles + # Each in-cluster client's own certificate (tls.crt, tls.key, ca.crt), with + # the least role its calls need: the CSI controller deletes volumes and the + # failback executor runs failbacks (admin); the CSI node and the status + # operator only read (viewer). + clientSecrets: + csiController: sw-block-csi-controller-tls + csiNode: sw-block-csi-node-tls + operatorStatus: sw-block-operator-status-tls + failbackExecutor: sw-block-failback-executor-tls + # Each volume host's certificate is the Secret - + # (tls.crt, tls.key, ca.crt); its CN is the server id, its role node. + nodeSecretPrefix: sw-block-node-tls + +network: + externalISCSI: false + externalNVMe: false + externalStatus: false + rejectLoopbackPublishTargets: false + +compat: + # Some published alpha images predate these blockmaster launcher flags. Keep + # these false unless the selected image is known to support the flag. + launcherDurableImplFlag: false + launcherReplicationAckFlag: false + launcherRejectLoopbackFlag: false + +stage2Multipath: + enabled: false + +chap: + enabled: false + secretName: sw-block-iscsi-chap + usernameKey: chapUsername + secretKey: chapSecret + username: "" + secret: "" + create: true + +ports: + iscsiBase: 3260 + nvmeBase: 4420 + statusBase: 23260 + +nvme: + maxH2CDataLength: 32768 + +# Initial block-capable nodes. D2 will add a generator that derives this from +# `kubectl get nodes` so node names and InternalIPs are verified against the +# live cluster. +blockNodes: + # Placeholder for a single-node render. Replace with your own node (name = + # Kubernetes node name); see examples/values-3node.yaml. + - name: block-node-1 + serverID: block-node-1 + internalIP: 127.0.0.1 + # Optional frontend/data-plane bind address. When set, cluster-spec data_addr + # and frontend publish targets use this IP while ctrl_addr keeps internalIP. + frontendIP: "" + frontendNetworkClass: management_lan + dataPort: 19101 + ctrlPort: 19102 + poolID: pool-a + totalBytes: 1073741824 + freeBytes: 1073741824 + +rbac: + create: true + +operatorStatus: + # Phase 35 read-only operator foundation. When enabled, this installs the + # status service account/RBAC plus a status projection Deployment. dryRun + # logs the projection only. dryRun=false patches existing SwBlockCluster / + # SwBlockVolume .status subresources and does not create CR objects. + create: false + dryRun: true + interval: 30s + clusterName: sw-block + rbac: + create: true + nodeSelector: {} + +lifecycleOwner: + # Phase 43 bounded lifecycle owner. Disabled by default. When enabled with + # dryRun=false it may patch only SwBlockVolume metadata.finalizers, and the + # admission policy confines the patch to the Seaweed Block protection + # finalizer. + create: false + dryRun: true + interval: 30s + finalizerName: block.seaweedfs.com/swblockvolume-protection + rbac: + create: true + admission: + create: true + nodeSelector: {} + +authorityExecutor: + # Returned-replica authority executor. Disabled by default. When created + # without execution enabled it only observes SwBlockVolume.status + # executorContracts[]; it has no status, finalizer, workload, storage, or + # Event mutation permissions. + create: false + interval: 30s + execution: + enabled: false + allowedMutationClass: ack_eligibility + rbac: + create: true + nodeSelector: {} + +rebuildTargetOwner: + # Rebuild target owner. Disabled by default. When enabled it creates + # SwBlockReplicaRebuild target CRs from ready rebuild_returned_replica + # executor contracts. It does not write status, publish frontend paths, + # start rebuild traffic, or change authority. + create: false + dryRun: true + interval: 30s + activation: + enabled: false + policy: false + runtimeEndpoint: "" + rbac: + create: true + nodeSelector: {} + +failbackTargetOwner: + # Failback target owner. Disabled by default. When enabled it creates + # SwBlockReplicaFailback target CRs from ready failback_returned_replica + # executor contracts. It does not execute failback, publish frontend paths, + # write status, or mutate storage. + create: false + dryRun: true + interval: 30s + activation: + enabled: false + policy: false + runtimeEndpoint: "" + rbac: + create: true + nodeSelector: {} + +failbackExecutor: + # Failback executor boundary. Disabled by default. This phase writes + # disabled/blocked SwBlockReplicaFailback.status only. It does not execute + # failback, advance authority, publish frontend paths, or mutate storage. + create: false + dryRun: true + interval: 30s + execution: + enabled: false + policy: false + failbackRuntimeGrpcAddr: "" + failbackRuntimeURL: "" + rbac: + create: true + nodeSelector: {} + +frontendPublicationTargetOwner: + # Frontend publication target owner. Disabled by default. When enabled it + # creates SwBlockFrontendPublication target CRs from terminal ACK eligibility + # evidence or terminal failed_back failback evidence. It does not publish + # frontend paths, fail back authority, write status, or mutate storage. + create: false + dryRun: true + interval: 30s + rbac: + create: true + nodeSelector: {} + +frontendPublicationExecutor: + # Frontend publication executor boundary. Disabled by default. With execution + # disabled it writes blocked SwBlockFrontendPublication.status only. Execution + # requires both execution.enabled and execution.policy plus an explicit + # runtimeUrl. It must not fail back authority, create targets, or mutate + # storage. + create: false + dryRun: true + interval: 30s + execution: + enabled: false + policy: false + runtimeUrl: "" + rbac: + create: true + nodeSelector: {} + +csiController: + replicas: 1 + +csiNode: + kubeletPath: /var/lib/kubelet + pluginPath: /var/lib/kubelet/plugins/block.csi.seaweedfs.com + registrationPath: /var/lib/kubelet/plugins_registry + loadKernelModules: true + nvmeReconnect: + enabled: false + interval: 5s diff --git a/seaweed-block/cmd/blockcsi/g15b_manifest_test.go b/seaweed-block/cmd/blockcsi/g15b_manifest_test.go new file mode 100644 index 0000000000..c48cd42904 --- /dev/null +++ b/seaweed-block/cmd/blockcsi/g15b_manifest_test.go @@ -0,0 +1,584 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "gopkg.in/yaml.v3" +) + +func TestG15b_Manifest_CSIDriverRequiresAttach(t *testing.T) { + doc := g15bFindKind(t, "csi-driver.yaml", "CSIDriver") + spec := g15bMap(t, doc, "spec") + if got, ok := spec["attachRequired"].(bool); !ok || !got { + t.Fatalf("CSIDriver.spec.attachRequired=%v (%T), want true", spec["attachRequired"], spec["attachRequired"]) + } +} + +func TestG15b_Manifest_ControllerUsesAttacherNotProvisioner(t *testing.T) { + body := g15bReadManifest(t, "csi-controller.yaml") + if !strings.Contains(body, "csi-attacher") { + t.Fatalf("controller manifest must include csi-attacher") + } + if strings.Contains(body, "csi-provisioner") { + t.Fatalf("G15b static PV controller must not include csi-provisioner") + } + if !strings.Contains(body, "--master=$(BLOCKMASTER_ADDR)") { + t.Fatalf("controller block-csi args must wire read-only blockmaster lookup") + } +} + +func TestG15b_Manifest_ProductStackSingleNodeLoopbackShape(t *testing.T) { + body := g15bReadManifest(t, "block-stack.yaml") + for _, want := range []string{ + "name: sw-blockmaster", + "name: sw-blockvolume-r1", + "name: sw-blockvolume-r2", + "--cluster-spec=/config/cluster-spec.yaml", + "--lifecycle-product-loop-interval=100ms", + "--expected-slots-per-volume=2", + "--recovery-mode=dual-lane", + "--iscsi-listen=127.0.0.1:3260", + "--iscsi-iqn=iqn.2026-05.io.seaweedfs:g15b-v1", + } { + if !strings.Contains(body, want) { + t.Fatalf("block-stack.yaml missing %q", want) + } + } + if strings.Contains(body, "--iscsi-listen=0.0.0.0") { + t.Fatalf("G15b must not weaken loopback-only iSCSI bind") + } + + for _, name := range []string{"sw-blockvolume-r1", "sw-blockvolume-r2"} { + deploy := g15bFindDeployment(t, "block-stack.yaml", name) + spec := g15bMap(t, g15bMap(t, g15bMap(t, deploy, "spec"), "template"), "spec") + if got, ok := spec["hostNetwork"].(bool); !ok || !got { + t.Fatalf("%s hostNetwork=%v, want true", name, spec["hostNetwork"]) + } + if got := spec["dnsPolicy"]; got != "ClusterFirstWithHostNet" { + t.Fatalf("%s dnsPolicy=%v, want ClusterFirstWithHostNet", name, got) + } + } +} + +func TestG15b_Manifest_AttachableReplicaIsFirstPlacementSlot(t *testing.T) { + cfg := g15bFindKind(t, "block-stack.yaml", "ConfigMap") + data := g15bMap(t, cfg, "data") + clusterSpec, ok := data["cluster-spec.yaml"].(string) + if !ok { + t.Fatalf("cluster-spec.yaml has type %T, want string", data["cluster-spec.yaml"]) + } + var spec struct { + Volumes []struct { + ID string `yaml:"id"` + Placements []struct { + ServerID string `yaml:"server_id"` + ReplicaID string `yaml:"replica_id"` + } `yaml:"placements"` + } `yaml:"volumes"` + } + if err := yaml.Unmarshal([]byte(clusterSpec), &spec); err != nil { + t.Fatalf("decode cluster spec: %v", err) + } + if len(spec.Volumes) != 1 || len(spec.Volumes[0].Placements) < 2 { + t.Fatalf("cluster spec shape=%+v", spec) + } + first := spec.Volumes[0].Placements[0] + if first.ServerID != "s1" || first.ReplicaID != "r1" { + t.Fatalf("first placement=%+v want attachable r1/s1", first) + } + + r1 := g15bReadDeploymentArgs(t, "sw-blockvolume-r1") + r2 := g15bReadDeploymentArgs(t, "sw-blockvolume-r2") + if !g15bArgsContain(r1, "--iscsi-listen=127.0.0.1:3260") { + t.Fatalf("r1 must expose the G15b static attach iSCSI target") + } + if g15bArgsContainPrefix(r2, "--iscsi-listen=") { + t.Fatalf("r2 must not expose a competing static iSCSI target in G15b") + } +} + +func TestG15b_Manifest_StaticPVDoesNotEmbedTargetFacts(t *testing.T) { + body := g15bReadManifest(t, "static-pv-pvc-pod.yaml") + for _, forbidden := range []string{"iscsiAddr", "iqn", "nqn", "endpointVersion", "epoch"} { + if strings.Contains(body, forbidden) { + t.Fatalf("static PV close-path manifest must not embed %q", forbidden) + } + } +} + +func TestG15b_Manifest_NodePluginPrivilegedShape(t *testing.T) { + doc := g15bFindKind(t, "csi-node.yaml", "DaemonSet") + spec := g15bMap(t, doc, "spec") + tpl := g15bMap(t, spec, "template") + podSpec := g15bMap(t, tpl, "spec") + if got, ok := podSpec["hostNetwork"].(bool); !ok || !got { + t.Fatalf("node DaemonSet hostNetwork=%v, want true", podSpec["hostNetwork"]) + } + + containers := g15bSlice(t, podSpec, "containers") + blockCSI := g15bContainer(t, containers, "block-csi") + sec := g15bMap(t, blockCSI, "securityContext") + if got, ok := sec["privileged"].(bool); !ok || !got { + t.Fatalf("block-csi privileged=%v, want true", sec["privileged"]) + } + + mounts := g15bSlice(t, blockCSI, "volumeMounts") + wantMounts := map[string]bool{ + "/var/lib/kubelet": false, + "/dev": false, + "/etc/iscsi": false, + } + for _, raw := range mounts { + m := raw.(map[string]any) + path, _ := m["mountPath"].(string) + if _, ok := wantMounts[path]; ok { + wantMounts[path] = true + } + if path == "/var/lib/kubelet" && m["mountPropagation"] != "Bidirectional" { + t.Fatalf("/var/lib/kubelet mountPropagation=%v, want Bidirectional", m["mountPropagation"]) + } + } + for path, found := range wantMounts { + if !found { + t.Fatalf("node plugin missing mountPath %s", path) + } + } +} + +func TestG15b_Manifest_NodePluginLoadsFrontendKernelModules(t *testing.T) { + doc := g15bFindKind(t, "csi-node.yaml", "DaemonSet") + podSpec := g15bMap(t, g15bMap(t, g15bMap(t, doc, "spec"), "template"), "spec") + initContainers := g15bSlice(t, podSpec, "initContainers") + loader := g15bContainer(t, initContainers, "load-iscsi-tcp") + got := strings.Join(g15bStringSlice(t, loader, "args"), " ") + for _, want := range []string{"modprobe iscsi_tcp", "modprobe nvme_tcp"} { + if !strings.Contains(got, want) { + t.Fatalf("load-iscsi-tcp args=%q, want %s", got, want) + } + } + sec := g15bMap(t, loader, "securityContext") + if got, ok := sec["privileged"].(bool); !ok || !got { + t.Fatalf("load-iscsi-tcp privileged=%v, want true", sec["privileged"]) + } + + mounts := g15bSlice(t, loader, "volumeMounts") + foundModules := false + for _, raw := range mounts { + m := raw.(map[string]any) + if m["mountPath"] == "/lib/modules" { + foundModules = true + if got, ok := m["readOnly"].(bool); !ok || !got { + t.Fatalf("/lib/modules readOnly=%v, want true", m["readOnly"]) + } + } + } + if !foundModules { + t.Fatalf("load-iscsi-tcp missing /lib/modules host mount") + } +} + +func TestG15b_Manifest_StaticPVUsesBlockCSIDriver(t *testing.T) { + doc := g15bFindKind(t, "static-pv-pvc-pod.yaml", "PersistentVolume") + spec := g15bMap(t, doc, "spec") + csi := g15bMap(t, spec, "csi") + if got := csi["driver"]; got != "block.csi.seaweedfs.com" { + t.Fatalf("PV csi.driver=%v, want block.csi.seaweedfs.com", got) + } + if got := csi["volumeHandle"]; got != "v1" { + t.Fatalf("PV csi.volumeHandle=%v, want v1", got) + } +} + +func TestG15b_Manifest_NoAuthorityShapedFields(t *testing.T) { + for _, file := range []string{"block-stack.yaml", "csi-driver.yaml", "csi-controller.yaml", "csi-node.yaml", "static-pv-pvc-pod.yaml"} { + body := strings.ToLower(g15bStripYAMLComments(g15bReadManifest(t, file))) + for _, forbidden := range []string{"endpointversion", "authorityepoch", "assignmentfact", "assignmentask"} { + if strings.Contains(body, forbidden) { + t.Fatalf("%s contains authority-shaped field %q", file, forbidden) + } + } + } +} + +func TestG15b_ImageBuildInputs_ContainExpectedBinariesAndNodeTools(t *testing.T) { + swBlock := g15bReadDeployFile(t, "Dockerfile.sw-block") + for _, want := range []string{ + "./cmd/blockmaster", + "./cmd/blockvolume", + "./cmd/sw-block", + "/usr/local/bin/blockmaster", + "/usr/local/bin/blockvolume", + "/usr/local/bin/sw-block", + } { + if !strings.Contains(swBlock, want) { + t.Fatalf("Dockerfile.sw-block missing %q", want) + } + } + + csi := g15bReadDeployFile(t, "Dockerfile.blockcsi") + for _, want := range []string{"./cmd/blockcsi", "open-iscsi", "multipath-tools", "sg3-utils", "nvme-cli", "e2fsprogs", "kmod", "util-linux", "/usr/local/bin/blockcsi"} { + if !strings.Contains(csi, want) { + t.Fatalf("Dockerfile.blockcsi missing %q", want) + } + } + + buildScript := g15bReadScript(t, "build-alpha-images.sh") + for _, want := range []string{"Dockerfile.sw-block", "Dockerfile.blockcsi", "sw-block:local", "sw-block-csi:local"} { + if !strings.Contains(buildScript, want) { + t.Fatalf("build-alpha-images.sh missing %q", want) + } + } + for _, want := range []string{ + "SW_BLOCK_IMPORT_K3S", + "sudo -n k3s ctr -n k8s.io images import -", + "docker image inspect", + "alpha-images.env", + "blockmaster.version.txt", + "blockvolume.version.txt", + "blockcsi.version.txt", + } { + if !strings.Contains(buildScript, want) { + t.Fatalf("build-alpha-images.sh missing pin-build/import contract %q", want) + } + } + + pinBuild := g15bReadScript(t, "testops-pin-alpha-images.sh") + for _, want := range []string{ + "run-request.json", + "SW_BLOCK_IMPORT_K3S", + "pin-build", + "alpha image pin-build/import failed", + "result.json", + } { + if !strings.Contains(pinBuild, want) { + t.Fatalf("testops-pin-alpha-images.sh missing %q", want) + } + } + + suite := g15bReadScript(t, "testops-run-nvme-p5-suite.sh") + for _, want := range []string{ + "alpha-images-pin-build", + "nvme-p5-csi-dynamic", + "nvme-p5-default-iscsi-regression", + "SW_BLOCK_ALPHA_IMAGES_ENV=$PIN_ENV", + "nvme-p5-csi-suite", + "result.json", + } { + if !strings.Contains(suite, want) { + t.Fatalf("testops-run-nvme-p5-suite.sh missing %q", want) + } + } + + releaseGate := g15bReadScript(t, "testops-run-protocol-release-gate.sh") + for _, want := range []string{ + "protocol-release-gate-suite", + "iscsi-p6-alua-failover-chain.yaml", + "nvme-p4-multipath-failover-chain.yaml", + "nvme-p5-csi-protocol-chain.yaml", + "iscsi-p8-compat-soak-chain.yaml", + "child-run.txt", + "result.json", + "wall_clock_s", + "started_at", + "swblock exited 0 but did not write latest run pointer", + } { + if !strings.Contains(releaseGate, want) { + t.Fatalf("testops-run-protocol-release-gate.sh missing %q", want) + } + } + + releaseGatePS := g15bReadScript(t, "testops-run-protocol-release-gate.ps1") + for _, want := range []string{ + "protocol-release-gate-suite", + "iscsi-p6-alua-failover-chain.yaml", + "nvme-p4-multipath-failover-chain.yaml", + "nvme-p5-csi-protocol-chain.yaml", + "iscsi-p8-compat-soak-chain.yaml", + "child-run.txt", + "result.json", + "wall_clock_s", + "started_at", + "Invoke-NativeRedirect", + } { + if !strings.Contains(releaseGatePS, want) { + t.Fatalf("testops-run-protocol-release-gate.ps1 missing %q", want) + } + } + + releaseGateValidate := g15bReadScript(t, "testops-validate-protocol-release-gate.py") + for _, want := range []string{ + "protocol-release-gate-suite", + "EXPECTED_CHILDREN", + "iscsi-p6-alua-failover", + "nvme-p4-multipath-failover", + "nvme-p5-csi-protocol", + "iscsi-p8-compat-soak", + "wall_clock_s", + "--expect-product-commit", + "--allow-fail", + } { + if !strings.Contains(releaseGateValidate, want) { + t.Fatalf("testops-validate-protocol-release-gate.py missing %q", want) + } + } + + releaseGateValidatePS := g15bReadScript(t, "testops-validate-latest-protocol-release-gate.ps1") + for _, want := range []string{ + "validate-bundle", + "--profile", + "protocol-release-gate", + "--expect-commit", + "Find-LatestProtocolGateArtifact", + "Invoke-Native", + } { + if !strings.Contains(releaseGateValidatePS, want) { + t.Fatalf("testops-validate-latest-protocol-release-gate.ps1 missing %q", want) + } + } + + releaseGateValidateSH := g15bReadScript(t, "testops-validate-latest-protocol-release-gate.sh") + for _, want := range []string{ + "validate-bundle", + "--profile", + "protocol-release-gate", + "--expect-commit", + "find_latest_protocol_gate_artifact", + "SWBLOCK_RUNNER_ROOT", + } { + if !strings.Contains(releaseGateValidateSH, want) { + t.Fatalf("testops-validate-latest-protocol-release-gate.sh missing %q", want) + } + } +} + +func TestG15dHarnessConsumesPinnedAlphaImagesEnv(t *testing.T) { + body := g15bReadScript(t, "run-g15d-k8s-dynamic.sh") + for _, want := range []string{ + "SW_BLOCK_ALPHA_IMAGES_ENV", + "SW_BLOCK_PIN_BUILD_ENV", + "source \"$ALPHA_IMAGES_ENV\"", + "alpha-images.env", + "alpha_images_env=", + } { + if !strings.Contains(body, want) { + t.Fatalf("run-g15d-k8s-dynamic.sh missing pinned image env contract %q", want) + } + } +} + +func TestG15b_Harness_CollectsDaemonLogsOnExit(t *testing.T) { + body := g15bReadScript(t, "run-g15b-k8s-static.sh") + for _, want := range []string{ + "collect_daemon_logs()", + "trap 'collect_daemon_logs; cleanup' EXIT", + "blockmaster.log", + "blockvolume-r1.log", + "blockvolume-r2.log", + "blockcsi-controller.log", + } { + if !strings.Contains(body, want) { + t.Fatalf("run-g15b-k8s-static.sh missing %q", want) + } + } + if strings.Contains(body, "trap cleanup EXIT") { + t.Fatalf("harness must collect daemon logs before cleanup") + } +} + +func g15bReadManifest(t *testing.T, name string) string { + t.Helper() + return g15bReadDeployFile(t, name) +} + +func g15bReadDeployFile(t *testing.T, name string) string { + t.Helper() + path := filepath.Join(g15bRepoRoot(t), "deploy", "k8s", "g15b", name) + b, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + return string(b) +} + +func g15bReadScript(t *testing.T, name string) string { + t.Helper() + path := filepath.Join(g15bRepoRoot(t), "scripts", name) + b, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + return string(b) +} + +func g15bFindKind(t *testing.T, name, kind string) map[string]any { + t.Helper() + for _, doc := range g15bDecodeDocs(t, g15bReadManifest(t, name)) { + if doc["kind"] == kind { + return doc + } + } + t.Fatalf("%s: kind %s not found", name, kind) + return nil +} + +func g15bFindDeployment(t *testing.T, name, deployName string) map[string]any { + t.Helper() + for _, doc := range g15bDecodeDocs(t, g15bReadManifest(t, name)) { + if doc["kind"] != "Deployment" { + continue + } + meta := g15bMap(t, doc, "metadata") + if meta["name"] == deployName { + return doc + } + } + t.Fatalf("%s: Deployment %s not found", name, deployName) + return nil +} + +func g15bDecodeDocs(t *testing.T, body string) []map[string]any { + t.Helper() + dec := yaml.NewDecoder(strings.NewReader(body)) + var out []map[string]any + for { + var doc map[string]any + err := dec.Decode(&doc) + if err != nil { + if err.Error() == "EOF" { + break + } + t.Fatalf("decode yaml: %v", err) + } + if len(doc) > 0 { + out = append(out, doc) + } + } + return out +} + +func g15bRepoRoot(t *testing.T) string { + t.Helper() + _, file, _, ok := runtime.Caller(0) + if !ok { + t.Fatal("runtime.Caller failed") + } + dir := filepath.Dir(file) + for { + if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { + return dir + } + parent := filepath.Dir(dir) + if parent == dir { + t.Fatal("repo root not found") + } + dir = parent + } +} + +func g15bMap(t *testing.T, m map[string]any, key string) map[string]any { + t.Helper() + v, ok := m[key] + if !ok { + t.Fatalf("missing key %q in %v", key, m) + } + out, ok := v.(map[string]any) + if !ok { + t.Fatalf("key %q has type %T, want map", key, v) + } + return out +} + +func g15bSlice(t *testing.T, m map[string]any, key string) []any { + t.Helper() + v, ok := m[key] + if !ok { + t.Fatalf("missing key %q in %v", key, m) + } + out, ok := v.([]any) + if !ok { + t.Fatalf("key %q has type %T, want slice", key, v) + } + return out +} + +func g15bStringSlice(t *testing.T, m map[string]any, key string) []string { + t.Helper() + raw := g15bSlice(t, m, key) + out := make([]string, 0, len(raw)) + for _, v := range raw { + s, ok := v.(string) + if !ok { + t.Fatalf("key %q item has type %T, want string", key, v) + } + out = append(out, s) + } + return out +} + +func g15bContainer(t *testing.T, containers []any, name string) map[string]any { + t.Helper() + for _, raw := range containers { + c, ok := raw.(map[string]any) + if !ok { + t.Fatalf("container has type %T, want map", raw) + } + if c["name"] == name { + return c + } + } + t.Fatalf("container %q not found", name) + return nil +} + +func g15bReadDeploymentArgs(t *testing.T, deployName string) []string { + t.Helper() + deploy := g15bFindDeployment(t, "block-stack.yaml", deployName) + spec := g15bMap(t, g15bMap(t, g15bMap(t, deploy, "spec"), "template"), "spec") + containers := g15bSlice(t, spec, "containers") + blockVolume := g15bContainer(t, containers, "blockvolume") + raw := g15bSlice(t, blockVolume, "args") + out := make([]string, 0, len(raw)) + for _, v := range raw { + s, ok := v.(string) + if !ok { + t.Fatalf("%s arg has type %T, want string", deployName, v) + } + out = append(out, s) + } + return out +} + +func g15bArgsContain(args []string, want string) bool { + for _, arg := range args { + if arg == want { + return true + } + } + return false +} + +func g15bArgsContainPrefix(args []string, prefix string) bool { + for _, arg := range args { + if strings.HasPrefix(arg, prefix) { + return true + } + } + return false +} + +func g15bStripYAMLComments(body string) string { + var out bytes.Buffer + for _, line := range strings.Split(body, "\n") { + if idx := strings.Index(line, "#"); idx >= 0 { + line = line[:idx] + } + out.WriteString(line) + out.WriteByte('\n') + } + return out.String() +} diff --git a/seaweed-block/cmd/blockcsi/g15c_l2_dynamic_create_test.go b/seaweed-block/cmd/blockcsi/g15c_l2_dynamic_create_test.go new file mode 100644 index 0000000000..dbf936a2b8 --- /dev/null +++ b/seaweed-block/cmd/blockcsi/g15c_l2_dynamic_create_test.go @@ -0,0 +1,132 @@ +package main + +import ( + "context" + "encoding/json" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + csipb "github.com/container-storage-interface/spec/lib/go/csi" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +func TestG15c_BlockCSICreateVolumeWritesMasterLifecycleIntent(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess dynamic provisioning test; -short skip") + } + bins := buildG15aBinaries(t) + art := t.TempDir() + lifecycleDir := filepath.Join(art, "lifecycle") + + master := startG15cMaster(t, bins.master, art, lifecycleDir) + csi := startG15aCSI(t, bins.csi, master.addr) + + conn, err := grpc.NewClient(csi.addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("dial blockcsi: %v", err) + } + defer conn.Close() + client := csipb.NewControllerClient(conn) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + resp, err := client.CreateVolume(ctx, &csipb.CreateVolumeRequest{ + Name: "pvc-a", + CapacityRange: &csipb.CapacityRange{ + RequiredBytes: 1 << 20, + }, + Parameters: map[string]string{ + "replicationFactor": "2", + "sw-block.seaweedfs.com/protocol": "nvme", + }, + VolumeCapabilities: []*csipb.VolumeCapability{ + testMountCapability(), + }, + }) + if err != nil { + t.Fatalf("CreateVolume: %v", err) + } + if resp.GetVolume().GetVolumeId() != "pvc-a" { + t.Fatalf("volume id=%q want pvc-a", resp.GetVolume().GetVolumeId()) + } + raw, err := os.ReadFile(filepath.Join(lifecycleDir, "volumes", "pvc-a.json")) + if err != nil { + t.Fatalf("read lifecycle volume record: %v", err) + } + var rec struct { + Spec struct { + VolumeID string `json:"volume_id"` + SizeBytes uint64 `json:"size_bytes"` + ReplicationFactor int `json:"replication_factor"` + Protocol string `json:"protocol"` + } `json:"spec"` + } + if err := json.Unmarshal(raw, &rec); err != nil { + t.Fatalf("parse lifecycle volume record: %v", err) + } + if rec.Spec.VolumeID != "pvc-a" || rec.Spec.SizeBytes != 1<<20 || rec.Spec.ReplicationFactor != 2 { + t.Fatalf("record=%+v", rec.Spec) + } + if rec.Spec.Protocol != "nvme" { + t.Fatalf("record protocol=%q want nvme", rec.Spec.Protocol) + } + if got := resp.GetVolume().GetVolumeContext()["protocol"]; got != "nvme" { + t.Fatalf("response protocol=%q want nvme", got) + } +} + +func startG15cMaster(t *testing.T, bin, art, lifecycleDir string) *g15aProc { + t.Helper() + logPath := filepath.Join(art, "blockmaster-g15c.log") + lf, err := os.Create(logPath) + if err != nil { + t.Fatalf("master log: %v", err) + } + cmd := exec.Command(bin, + "--authority-store", filepath.Join(art, "authority-store"), + "--lifecycle-store", lifecycleDir, + "--expected-slots-per-volume", "2", // matches the RF2 provisioning request + "--listen", "127.0.0.1:0", + "--lifecycle-product-loop-interval", "100ms", + "--t0-print-ready", + ) + stdout, err := cmd.StdoutPipe() + if err != nil { + lf.Close() + t.Fatalf("master stdout: %v", err) + } + cmd.Stderr = lf + if err := cmd.Start(); err != nil { + lf.Close() + t.Fatalf("master start: %v", err) + } + p := &g15aProc{cmd: cmd, logPath: logPath} + t.Cleanup(func() { + p.stop(t) + lf.Close() + }) + var ready readyLine + if err := json.NewDecoder(stdout).Decode(&ready); err != nil { + t.Fatalf("master ready: %v", err) + } + if ready.Addr == "" { + t.Fatal("master ready missing addr") + } + p.addr = ready.Addr + return p +} + +func testMountCapability() *csipb.VolumeCapability { + return &csipb.VolumeCapability{ + AccessType: &csipb.VolumeCapability_Mount{ + Mount: &csipb.VolumeCapability_MountVolume{FsType: "ext4"}, + }, + AccessMode: &csipb.VolumeCapability_AccessMode{ + Mode: csipb.VolumeCapability_AccessMode_SINGLE_NODE_WRITER, + }, + } +} diff --git a/seaweed-block/cmd/blockcsi/g15d_manifest_test.go b/seaweed-block/cmd/blockcsi/g15d_manifest_test.go new file mode 100644 index 0000000000..8f64a0b784 --- /dev/null +++ b/seaweed-block/cmd/blockcsi/g15d_manifest_test.go @@ -0,0 +1,851 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestG15d_K8sBlockStack_HasLauncherButNoPrecreatedBlockvolume(t *testing.T) { + body := g15dReadFile(t, "deploy", "k8s", "g15d", "block-stack.yaml") + for _, want := range []string{ + "--launcher-loop-interval=100ms", + "--launcher-manifest-dir=/manifests", + "__NODE_NAME__", + "pools:", + } { + if !strings.Contains(body, want) { + t.Fatalf("block-stack missing %q", want) + } + } + if strings.Contains(body, "name: sw-blockvolume-r1") || strings.Contains(body, "/usr/local/bin/blockvolume") { + t.Fatalf("G15d block stack must not precreate blockvolume workloads:\n%s", body) + } +} + +func TestG15d_K8sCSIController_IncludesExternalProvisioner(t *testing.T) { + body := g15dReadFile(t, "deploy", "k8s", "g15d", "csi-controller.yaml") + for _, want := range []string{ + "name: csi-provisioner", + "registry.k8s.io/sig-storage/csi-provisioner:", + "name: csi-attacher", + "--csi-address=/csi/csi.sock", + "--extra-create-metadata=true", + } { + if !strings.Contains(body, want) { + t.Fatalf("csi-controller missing %q", want) + } + } +} + +func TestAlphaK8sCSIController_IncludesCreateMetadata(t *testing.T) { + body := g15dReadFile(t, "deploy", "k8s", "alpha", "csi-controller.yaml") + if !strings.Contains(body, "--extra-create-metadata=true") { + t.Fatalf("alpha csi-controller must enable PVC metadata propagation:\n%s", body) + } +} + +func TestPhase44HelmCSIController_RegistersSwBlockVolumeWhenOperatorSurfacesEnabled(t *testing.T) { + controller := g15dReadFile(t, "charts", "seaweed-block", "templates", "csi-controller.yaml") + for _, want := range []string{ + "or .Values.operatorStatus.create .Values.lifecycleOwner.create", + `"--swblockvolume-cr-namespace={{ .Release.Namespace }}"`, + } { + if !strings.Contains(controller, want) { + t.Fatalf("csi-controller template missing %q:\n%s", want, controller) + } + } + rbac := g15dReadFile(t, "charts", "seaweed-block", "templates", "rbac.yaml") + for _, want := range []string{ + `apiGroups: ["block.seaweedfs.com"]`, + `resources: ["swblockvolumes"]`, + `verbs: ["get", "list", "watch", "create", "update", "patch"]`, + } { + if !strings.Contains(rbac, want) { + t.Fatalf("csi RBAC template missing %q:\n%s", want, rbac) + } + } + if strings.Contains(rbac, `resources: ["swblockvolumes/status"]`) || strings.Contains(rbac, `resources: ["swblockvolumes/finalizers"]`) { + t.Fatalf("CSI controller must not receive SwBlockVolume status/finalizer ownership:\n%s", rbac) + } +} + +func TestG15d_K8sDynamicPVC_UsesStorageClassNoPrecreatedPV(t *testing.T) { + body := g15dReadFile(t, "deploy", "k8s", "g15d", "dynamic-pvc-pod.yaml") + for _, want := range []string{ + "kind: StorageClass", + "provisioner: block.csi.seaweedfs.com", + "name: sw-block-dynamic-v1", + "sha256sum -c /data/payload.sha256", + } { + if !strings.Contains(body, want) { + t.Fatalf("dynamic-pvc-pod missing %q", want) + } + } + if strings.Contains(body, "kind: PersistentVolume\n") { + t.Fatalf("dynamic PVC scenario must not precreate PV:\n%s", body) + } +} + +func TestG15d_K8sRunner_AppliesLauncherGeneratedManifest(t *testing.T) { + body := g15dReadFile(t, "scripts", "run-g15d-k8s-dynamic.sh") + for _, want := range []string{ + "generated-blockvolume.yaml", + "SW_BLOCK_LAUNCHER_PVC_OWNER_REF", + "SW_BLOCK_ISCSI_CHAP_USERNAME", + "SW_BLOCK_ISCSI_CHAP_SECRET", + "SW_BLOCK_FRONTEND_PROTOCOL", + "SW_BLOCK_STAGE2_MULTIPATH", + "SW_BLOCK_DYNAMIC_REPLICATION_FACTOR", + "SW_BLOCK_SAME_NODE_LOGICAL_REPLICAS", + "csi.storage.k8s.io/node-stage-secret-name", + `sw-block.seaweedfs.com/protocol: \"nvme\"`, + `protocol: \"nvme\"`, + "frontend_protocol=$FRONTEND_PROTOCOL", + "stage2_multipath=$STAGE2_MULTIPATH", + "dynamic_replication_factor=${DYNAMIC_REPLICATION_FACTOR:-manifest-default}", + "stage2_multipath:", + "same_node_logical_replicas=$SAME_NODE_LOGICAL_REPLICAS", + "--expected-slots-per-volume=${SAME_NODE_LOGICAL_REPLICAS}", + "failed to override dynamic replicationFactor", + "failed to inject --stage2-multipath into", + "failed to pin dynamic pod to same-node NVMe target host", + "expected_git_revision=${EXPECTED_GIT_REVISION:-unknown}", + "blockmaster.version.txt", + "blockcsi.version.txt", + "blockcsi-node.log", + "blockvolume.version.txt", + "kube-system-imageids.txt", + "image revision mismatch", + "delete-storageclass-before-apply.log", + "storageclass.live.yaml", + "live StorageClass missing NVMe protocol parameter", + "lifecycle-volumes.json", + "verified generated blockvolume frontend protocol=nvme", + "generated blockvolume manifest rendered iSCSI args while frontend_protocol=nvme", + "--launcher-iscsi-chap-secret-name", + "BLOCKVOLUME_NAMESPACE=\"kube-system\"", + "--kubernetes-pvc-uid-lookup", + "--launcher-pvc-owner-ref", + "apply iSCSI CHAP Secret", + "kubectl apply -f \"$ARTIFACT_DIR/generated-blockvolume.yaml\"", + "kubectl -n \"$BLOCKVOLUME_NAMESPACE\" wait --for=condition=available deploy -l app=sw-blockvolume", + "kubectl -n \"$BLOCKVOLUME_NAMESPACE\" logs -l sw-block.seaweedfs.com/volume", + "kubectl -n \"$NAMESPACE\" delete pvc sw-block-dynamic-v1", + "wait for launcher manifest cleanup after DeleteVolume", + "delete generated blockvolume Deployment after manifest cleanup", + "wait for Kubernetes GC to delete PVC-owned blockvolume Deployment", + "iscsi-sessions.after-delete.txt", + "nvme-list-subsys.after-delete.json", + "PASS: dynamic PVC create/delete completed checksum write/read and cleanup", + } { + if !strings.Contains(body, want) { + t.Fatalf("runner missing %q", want) + } + } +} + +func TestG15d_K8sRunner_NVMeProtocolWrapper(t *testing.T) { + body := g15dReadFile(t, "scripts", "run-k8s-alpha-nvme.sh") + for _, want := range []string{ + "SW_BLOCK_FRONTEND_PROTOCOL=nvme", + "SW_BLOCK_LAUNCHER_PVC_OWNER_REF", + "run-alpha-k8s-dynamic.sh", + } { + if !strings.Contains(body, want) { + t.Fatalf("nvme alpha wrapper missing %q:\n%s", want, body) + } + } +} + +func TestAlphaCSINode_LoadsBothFrontendKernelModules(t *testing.T) { + body := g15dReadFile(t, "deploy", "k8s", "alpha", "csi-node.yaml") + for _, want := range []string{"modprobe iscsi_tcp", "modprobe nvme_tcp", "modprobe dm_multipath", "modprobe scsi_dh_alua", "/run/udev"} { + if !strings.Contains(body, want) { + t.Fatalf("alpha csi-node missing %q", want) + } + } +} + +func TestAlphaCSIDriver_AppliesFilesystemGroupOwnership(t *testing.T) { + body := g15dReadFile(t, "deploy", "k8s", "alpha", "csi-driver.yaml") + for _, want := range []string{ + "kind: CSIDriver", + "name: block.csi.seaweedfs.com", + "fsGroupPolicy: File", + } { + if !strings.Contains(body, want) { + t.Fatalf("alpha CSIDriver missing %q", want) + } + } +} + +func TestAlphaScripts_Stage2MultipathIsOptIn(t *testing.T) { + for _, script := range []string{"install-k8s-alpha.sh", "run-alpha-app-demo.sh"} { + t.Run(script, func(t *testing.T) { + body := g15dReadFile(t, "scripts", script) + for _, want := range []string{ + "SW_BLOCK_STAGE2_MULTIPATH", + "--stage2-multipath", + "stage2_multipath=$STAGE2_MULTIPATH", + } { + if !strings.Contains(body, want) { + t.Fatalf("%s missing %q", script, want) + } + } + }) + } +} + +func TestNodeLoss_AlphaScriptsCanRenderExplicitMultiNodeSpecs(t *testing.T) { + for _, script := range []string{"install-k8s-alpha.sh", "run-alpha-app-demo.sh"} { + t.Run(script, func(t *testing.T) { + body := g15dReadFile(t, "scripts", script) + for _, want := range []string{ + "SW_BLOCK_ALPHA_NODE_SPECS", + "render_cluster_spec_node_specs", + "server_id|kubernetes_node|host_or_ip|pool_id", + "host_or_ip must be non-loopback", + "data_addr: ${host}:${data_port}", + "ctrl_addr: ${host}:${ctrl_port}", + "kubernetes.io/hostname: ${node_name}", + "expected_slots_per_volume=$EXPECTED_SLOTS_PER_VOLUME", + "node_specs=${NODE_SPECS:-}", + } { + if !strings.Contains(body, want) { + t.Fatalf("%s missing %q", script, want) + } + } + }) + } +} + +func TestNodeLoss_AlphaScriptsExternalISCSIIsOptInWithCHAPSecret(t *testing.T) { + for _, script := range []string{"install-k8s-alpha.sh", "run-alpha-app-demo.sh"} { + t.Run(script, func(t *testing.T) { + body := g15dReadFile(t, "scripts", script) + for _, want := range []string{ + "SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI", + "SW_BLOCK_ISCSI_CHAP_SECRET_NAME", + "--launcher-external-iscsi", + "--launcher-iscsi-chap-secret-name=", + "launcher_external_iscsi=$LAUNCHER_EXTERNAL_ISCSI", + } { + if !strings.Contains(body, want) { + t.Fatalf("%s missing %q", script, want) + } + } + }) + } +} + +func TestNodeLoss_AlphaScriptsCanRejectLoopbackPublishTargets(t *testing.T) { + for _, script := range []string{"install-k8s-alpha.sh", "run-alpha-app-demo.sh"} { + t.Run(script, func(t *testing.T) { + body := g15dReadFile(t, "scripts", script) + for _, want := range []string{ + "SW_BLOCK_REJECT_LOOPBACK_PUBLISH_TARGETS", + "--reject-loopback-publish-targets", + "reject_loopback_publish_targets=$REJECT_LOOPBACK_PUBLISH_TARGETS", + } { + if !strings.Contains(body, want) { + t.Fatalf("%s missing %q", script, want) + } + } + }) + } +} + +// The alpha scripts install the mutual-TLS Secrets before the stack, and +// refuse external status: an authenticated volume's status stays on loopback. +func TestAlphaScriptsInstallTLSAndRefuseExternalStatus(t *testing.T) { + for _, script := range []string{"install-k8s-alpha.sh", "run-alpha-app-demo.sh", "run-g15d-k8s-dynamic.sh", "run-g15b-k8s-static.sh"} { + t.Run(script, func(t *testing.T) { + body := g15dReadFile(t, "scripts", script) + certs := strings.Index(body, "scripts/k8s-alpha-certs.sh") + stack := strings.Index(body, "kubectl apply -f \"$STACK_RENDERED\"") + if stack < 0 { + stack = strings.Index(body, "kubectl apply -f \"$ROOT/deploy/k8s/g15b/block-stack.yaml\"") + } + if certs < 0 || stack < 0 || certs > stack { + t.Fatalf("%s must apply the TLS Secrets before the block stack (certs at %d, stack at %d)", script, certs, stack) + } + if strings.Contains(body, "--launcher-external-status") { + t.Fatalf("%s still renders --launcher-external-status", script) + } + if strings.Contains(body, "SW_BLOCK_LAUNCHER_EXTERNAL_STATUS") && !strings.Contains(body, "SW_BLOCK_LAUNCHER_EXTERNAL_STATUS is not supported") { + t.Fatalf("%s accepts SW_BLOCK_LAUNCHER_EXTERNAL_STATUS without refusing it", script) + } + }) + } +} + +func TestNodeLoss_AppDemoDeliversCHAPSecretToCSI(t *testing.T) { + body := g15dReadFile(t, "scripts", "run-alpha-app-demo.sh") + for _, want := range []string{ + "SW_BLOCK_ISCSI_CHAP_USERNAME", + "SW_BLOCK_ISCSI_CHAP_SECRET", + "inject_node_stage_secret_into_storageclass", + "csi.storage.k8s.io/node-stage-secret-name", + "csi.storage.k8s.io/node-stage-secret-namespace", + "apply iSCSI CHAP Secret", + "--from-literal=chapUsername", + "--from-literal=chapSecret", + "delete secret \"$CHAP_SECRET_NAME\"", + } { + if !strings.Contains(body, want) { + t.Fatalf("run-alpha-app-demo.sh missing %q", want) + } + } +} + +func TestNodeLoss_InstallAppliesCHAPSecretForExternalISCSI(t *testing.T) { + body := g15dReadFile(t, "scripts", "install-k8s-alpha.sh") + for _, want := range []string{ + "SW_BLOCK_ISCSI_CHAP_USERNAME", + "SW_BLOCK_ISCSI_CHAP_SECRET", + "SW_BLOCK_APP_NAMESPACE", + "SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI requires SW_BLOCK_ISCSI_CHAP_USERNAME", + "apply iSCSI CHAP Secret", + "--from-literal=chapUsername", + "--from-literal=chapSecret", + "chap_enabled=$([[ -n \"$CHAP_SECRET\" ]] && echo 1 || echo 0)", + } { + if !strings.Contains(body, want) { + t.Fatalf("install-k8s-alpha.sh missing %q", want) + } + } +} + +func TestStage2ISCSIALUAMultipathScenarioPinsOptInAndClaimBoundary(t *testing.T) { + body := g15dReadFile(t, "testops", "scenarios", "stage2-iscsi-alua-multipath-baseline-chain.yaml") + for _, want := range []string{ + "name: stage2-iscsi-alua-multipath-baseline-chain", + "multipath-prereq.txt", + "module_dm_multipath=loaded", + "module_scsi_dh_alua=loaded", + "SW_BLOCK_STAGE2_MULTIPATH=1", + "SW_BLOCK_ALPHA_LOGICAL_SERVERS=3", + "SW_BLOCK_ALPHA_EXPECTED_SLOTS_PER_VOLUME=3", + "SW_BLOCK_ALPHA_REPLICATION_ACK=sync-quorum", + "demo-app-pvc-writer-hold.yaml", + "SW_BLOCK_DEMO_STOP_AFTER=writer-verified", + "--stage2-multipath", + "--replica-id=r1", + "--replica-id=r2", + "--replica-id=r3", + "unique-iscsi-iqns.txt", + "multipath=true", + "staged transport=iscsi .* portals=.*127.0.0.1:3260", + "staged transport=iscsi .* portals=.*127.0.0.1:3261", + "staged transport=iscsi .* portals=.*127.0.0.1:3262", + "controlled-stop-writer-verified.txt", + "phase=writer-verified", + "iscsi-sessions.writer-mounted.txt", + "multipath.writer-mounted.txt", + "sg-rtpg.writer-mounted.txt", + "asymmetric access state", + "transparent_failover_claimed=false", + "next_required_gate=mounted_writer_primary_failure_without_pod_recreate", + "bounded-waits.txt", + "multipath -f", + } { + if !strings.Contains(body, want) { + t.Fatalf("stage2 multipath scenario missing %q", want) + } + } +} + +func TestStage2ISCSIALUAMultipathFailoverScenarioUsesMountedWriter(t *testing.T) { + body := g15dReadFile(t, "testops", "scenarios", "stage2-iscsi-alua-multipath-failover-chain.yaml") + for _, want := range []string{ + "name: stage2-iscsi-alua-multipath-failover-chain", + "SW_BLOCK_STAGE2_MULTIPATH=1", + "SW_BLOCK_ALPHA_LOGICAL_SERVERS=3", + "SW_BLOCK_ALPHA_REPLICATION_ACK=sync-quorum", + "SW_BLOCK_DEMO_STOP_AFTER=writer-verified", + "SW_BLOCK_DEMO_KEEP_ON_STOP=1", + "pod_recreate_used=false", + "before_primary_replica=", + "target_deployment=", + "scale-primary-zero.log", + "post_failure_primary_count=1", + "timeout 180s kubectl -n default exec sw-block-demo-writer", + "mounted_workload_checksum_passed", + "data_check_after_failover=mounted_workload_checksum_passed", + "multipath-before.txt", + "multipath-after.txt", + "sg-inq.txt", + "sg-vpd83.txt", + "sg-rtpg.before.txt", + "sg-rtpg.after.txt", + "old_primary_stale_io_success_count=0", + "bounded_waits=pass", + } { + if !strings.Contains(body, want) { + t.Fatalf("stage2 multipath failover scenario missing %q", want) + } + } + if strings.Contains(body, "apply-reader") || strings.Contains(body, "demo-app-reader") || strings.Contains(body, "data_check_after_failover=reader") { + t.Fatalf("stage2 mounted failover scenario must not use reader pod recreate") + } +} + +func TestAlphaAppDemo_WriterVerifiedStopCapturesMountedHostPathEvidence(t *testing.T) { + body := g15dReadFile(t, "scripts", "run-alpha-app-demo.sh") + for _, want := range []string{ + `"$DEMO_STOP_AFTER" != "writer-verified"`, + `"$DEMO_STOP_AFTER" == "writer-verified"`, + `capture_stage2_host_path_evidence "writer-mounted"`, + "iscsi-sessions.${label}.txt", + "multipath.${label}.txt", + "sg-rtpg.${label}.txt", + "controlled-stop-writer-verified.txt", + "ops-inventory-writer-verified", + "phase=writer-verified-failed", + "writer_verified=false", + "resources-kept: true", + "trap - EXIT", + } { + if !strings.Contains(body, want) { + t.Fatalf("run-alpha-app-demo.sh missing writer-verified host-path evidence hook %q", want) + } + } +} + +func TestFailureBundleScenarioAssertsProcessHygieneAfterCleanup(t *testing.T) { + body := g15dReadFile(t, "testops", "scenarios", "light-use-first-volume-failure-bundle-chain.yaml") + finalIdx := strings.Index(body, "- name: final_asserts") + cleanupIdx := strings.Index(body, "- name: collect_and_cleanup") + if finalIdx < 0 || cleanupIdx < 0 || finalIdx > cleanupIdx { + t.Fatalf("failure-bundle scenario must have final_asserts before collect_and_cleanup") + } + finalSection := body[finalIdx:cleanupIdx] + if strings.Contains(finalSection, "assert_no_processes") { + t.Fatalf("final_asserts must not assert process hygiene before cleanup; controlled stop leaves live pods:\n%s", finalSection) + } + cleanupSection := body[cleanupIdx:] + for _, want := range []string{ + "scripts/uninstall-k8s-alpha.sh", + "action: assert_no_processes", + "blockmaster,blockvolume,blockcsi,iscsi-target", + } { + if !strings.Contains(cleanupSection, want) { + t.Fatalf("cleanup section missing %q", want) + } + } +} + +func TestAlphaScripts_OwnerRefModeInjectsBothLauncherAndCSILookupFlags(t *testing.T) { + for _, script := range []string{"run-g15d-k8s-dynamic.sh", "run-alpha-app-demo.sh"} { + t.Run(script, func(t *testing.T) { + body := g15dReadFile(t, "scripts", script) + for _, want := range []string{ + "SW_BLOCK_LAUNCHER_PVC_OWNER_REF", + "--launcher-pvc-owner-ref", + "--kubernetes-pvc-uid-lookup", + "BLOCKVOLUME_NAMESPACE=\"$NAMESPACE\"", + } { + if !strings.Contains(body, want) { + t.Fatalf("%s missing %q", script, want) + } + } + }) + } +} + +func TestPublicAlphaWrappers_DefaultToPVCOwnerReferenceCleanup(t *testing.T) { + for _, script := range []string{"run-k8s-alpha.sh", "run-k8s-demo.sh"} { + t.Run(script, func(t *testing.T) { + body := g15dReadFile(t, "scripts", script) + if !strings.Contains(body, `SW_BLOCK_LAUNCHER_PVC_OWNER_REF="${SW_BLOCK_LAUNCHER_PVC_OWNER_REF:-1}"`) { + t.Fatalf("%s must default SW_BLOCK_LAUNCHER_PVC_OWNER_REF to 1", script) + } + }) + } +} + +func TestInstallAlpha_DefaultsToPVCOwnerReferenceCleanup(t *testing.T) { + body := g15dReadFile(t, "scripts", "install-k8s-alpha.sh") + for _, want := range []string{ + `LAUNCHER_PVC_OWNER_REF="${SW_BLOCK_LAUNCHER_PVC_OWNER_REF:-1}"`, + "--launcher-pvc-owner-ref", + "--kubernetes-pvc-uid-lookup", + `log "apply RBAC"`, + } { + if !strings.Contains(body, want) { + t.Fatalf("install script missing %q", want) + } + } +} + +func TestPhase20ActivationScriptPinsInstallToOperateLoop(t *testing.T) { + body := g15dReadFile(t, "scripts", "activate-k8s-alpha.sh") + for _, want := range []string{ + "scripts/preflight-k8s-alpha.sh", + "scripts/build-alpha-images.sh", + "scripts/install-k8s-alpha.sh", + "SW_BLOCK_ACTIVATION_IMAGE_MODE", + "SW_BLOCK_ACTIVATION_IMAGE_MODE must be local or published", + "--local-k3s", + "--ghcr", + "ready_schedulable_node_count", + "first_ready_node_with_internal_ip", + "DAY1_NETWORK_MODE=\"external-iscsi\"", + "SW_BLOCK_ALPHA_NODE_SPECS=\"$ALPHA_NODE_SPECS\"", + "SW_BLOCK_LAUNCHER_EXTERNAL_ISCSI=\"$LAUNCHER_EXTERNAL_ISCSI\"", + "SW_BLOCK_LAUNCHER_EXTERNAL_STATUS=\"$LAUNCHER_EXTERNAL_STATUS\"", + "SW_BLOCK_ISCSI_CHAP_USERNAME=\"$CHAP_USERNAME\"", + "csi.storage.k8s.io/node-stage-secret-name", + "day1_network_mode=$DAY1_NETWORK_MODE", + "phase_skip=build reason=published-images", + "published-images.env", + "image_digest=", + "csi_image_digest=", + "collect_failure_diagnostics", + "diagnostics/failure-context.txt", + "sw-blockmaster.previous.log", + "activation_blocker=image_flag_mismatch", + "remediation=republish the image from this commit or use matching sha- image tags", + "ghcr.io/seaweedfs/seaweed-block:alpha", + "ghcr.io/seaweedfs/seaweed-block-csi:alpha", + "deploy/k8s/alpha/storageclass.yaml", + "storageclass.rendered.yaml", + "activation-summary.txt", + "activation_status=$status", + `write_summary "ok"`, + "failed_phase=", + "image_mode=$IMAGE_MODE", + "master_ready_replicas=", + "csi_controller_ready_replicas=", + "csi_node_ready=", + "storageclass_provider=", + "next_create_volume=kubectl apply -f examples/kubernetes/basic-app/storageclass-pvc.yaml", + "next_status=kubectl -n kube-system port-forward deploy/sw-blockmaster 9333:9333", + "non_claims=alpha_only,no_backup_restore,no_upgrade_safety,no_mutating_dashboard_actions,no_broad_performance_slo", + } { + if !strings.Contains(body, want) { + t.Fatalf("activation script missing %q", want) + } + } +} + +func TestPhase20ActivationScenarioPinsDay1InstallGate(t *testing.T) { + body := g15dReadFile(t, "testops", "scenarios", "activation-day1-install-chain.yaml") + for _, want := range []string{ + "name: activation-day1-install-chain", + "scripts/activate-k8s-alpha.sh", + "activation-summary.txt", + "^activation_status=ok$", + "^master_ready_replicas=1$", + "^csi_controller_ready_replicas=1$", + "^csi_node_ready=[1-9][0-9]*/[1-9][0-9]*$", + "^storageclass_provider=block.csi.seaweedfs.com$", + "next_create_volume=kubectl apply -f examples/kubernetes/basic-app/storageclass-pvc.yaml", + "readiness.txt", + "scripts/uninstall-k8s-alpha.sh", + "delete-storageclass.log", + `pattern: "sw-block-dynamic"`, + } { + if !strings.Contains(body, want) { + t.Fatalf("activation scenario missing %q", want) + } + } +} + +func TestPhase20FirstVolumeScriptPinsUserLoop(t *testing.T) { + body := g15dReadFile(t, "scripts", "run-basic-app-example.sh") + for _, want := range []string{ + "examples/kubernetes/basic-app", + "sw-block-example-pvc", + "sw-block-example-writer", + "sw-block-example-reader", + "first-volume-summary.txt", + "writer_verified=$writer_ok", + "reader_verified=$reader_ok", + "status_evidence=status/cluster-evidence.json,status/inventory", + "cluster_evidence=status/cluster-evidence.json", + "inventory_bundle=status/inventory", + "cleanup_status=$CLEANUP_STATUS", + "failed_phase=$FAILED_PHASE", + "SW_BLOCK_BASIC_APP_CLEANUP", + "SW_BLOCK_BASIC_APP_PROTOCOL", + "sw-block.seaweedfs.com/protocol: \\\"nvme\\\"", + "app_protocol=$BASIC_APP_PROTOCOL", + "inject_node_stage_secret_into_storageclass", + "csi.storage.k8s.io/node-stage-secret-name", + "node_stage_secret=", + "SW_BLOCK_CLI", + "command -v sw-block", + "sw_block_cmd ops cluster --master-api", + "sw_block_cmd ops inventory --namespace", + "PASS: basic app PVC writer/reader loop complete", + } { + if !strings.Contains(body, want) { + t.Fatalf("basic app wrapper missing %q", want) + } + } +} + +func TestPhase107MultiVolumeScriptPinsProtocolAndNodeSelector(t *testing.T) { + body := g15dReadFile(t, "scripts", "run-multi-volume-example.sh") + for _, want := range []string{ + "SW_BLOCK_MULTI_VOLUME_PROTOCOL", + "SW_BLOCK_MULTI_VOLUME_NODE_SELECTOR", + "sw-block.seaweedfs.com/protocol: \\\"nvme\\\"", + "protocol=$MULTI_VOLUME_PROTOCOL", + "app_node_selector=${MULTI_VOLUME_NODE_SELECTOR:-none}", + "kubernetes.io/hostname", + "list_blockvolume_pods", + "list_matching_pvs", + "count_seaweed_nvme_subsystems", + "SW_BLOCK_MULTI_VOLUME_PROTOCOL must be iscsi or nvme", + } { + if !strings.Contains(body, want) { + t.Fatalf("multi-volume wrapper missing %q", want) + } + } +} + +func TestPhase108NVMeLifecycleScenarioAssertsResidueFreeCycles(t *testing.T) { + body := g15dReadFile(t, "testops", "scenarios", "nvme-tcp-cross-node-multivolume-lifecycle-soak-chain.yaml") + for _, want := range []string{ + "phase108_nvme_tcp_multivolume_lifecycle_soak_status=ok", + "cycle_count: \"2\"", + "SW_BLOCK_MULTI_VOLUME_PROTOCOL=nvme", + "SW_BLOCK_MULTI_VOLUME_CLEANUP=1", + "cycle_{cycle}_cleanup_status=ok", + "cycle_{cycle}_nvme_residue_count=0", + "cycle_{cycle}_k8s_residue_count=0", + "cleanup_status=ok", + } { + if !strings.Contains(body, want) { + t.Fatalf("phase108 lifecycle scenario missing %q", want) + } + } +} + +func TestPhase109NVMeStatusSurfaceScenarioChecksCRDAndSupportSurfaces(t *testing.T) { + body := g15dReadFile(t, "testops", "scenarios", "nvme-tcp-status-surface-evidence-chain.yaml") + for _, want := range []string{ + "phase109_nvme_tcp_status_surface_status=ok", + "operatorStatus:", + "lifecycleOwner:", + "crd_nvme_status_count=2", + "report_nvme_status_count=2", + "operator_snapshot_nvme_status_count=2", + "dashboard_nvme_status_count=2", + "explain_nvme_status_count=2", + "publish_target_matches_nvme_addr=true", + "ops','explain','volume','--from-bundle'", + } { + if !strings.Contains(body, want) { + t.Fatalf("phase109 status surface scenario missing %q", want) + } + } +} + +func TestPhase110NVMePathLossScenarioChecksSupportSurfaces(t *testing.T) { + body := g15dReadFile(t, "testops", "scenarios", "nvme-tcp-path-loss-status-surface-chain.yaml") + for _, want := range []string{ + "phase110_nvme_tcp_path_loss_status_surface_status=ok", + "run-nvme-mounted-failover-smoke.sh", + "cluster-after-failover.json", + "product-observation/cluster-evidence.json", + "nvme_multipath_path_missing", + "surface_ready_true_count=0", + "operator_snapshot_reason=nvme_multipath_path_missing", + "dashboard_reason=nvme_multipath_path_missing", + "explain_reason=nvme_multipath_path_missing", + "mutation_allowed=false", + } { + if !strings.Contains(body, want) { + t.Fatalf("phase110 path-loss scenario missing %q", want) + } + } +} + +func TestPhase20FirstVolumeScenarioPinsPublishedUserGate(t *testing.T) { + body := g15dReadFile(t, "testops", "scenarios", "activation-day1-first-volume-chain.yaml") + for _, want := range []string{ + "name: activation-day1-first-volume-chain", + "SW_BLOCK_ACTIVATION_IMAGE_MODE", + "published", + "ghcr.io/seaweedfs/seaweed-block:sha-", + "scripts/activate-k8s-alpha.sh", + "scripts/run-basic-app-example.sh", + "env.SW_BLOCK_BASIC_APP_CLEANUP", + "first-volume-summary.txt", + "^first_volume_status=ok$", + "^pvc=sw-block-example-pvc$", + "^writer_verified=true$", + "^reader_verified=true$", + "^cleanup_status=ok$", + "status/cluster-evidence.json", + "status/inventory/volume-inventory-summary.txt", + "kubectl -n default delete pvc sw-block-example-pvc", + "SW_BLOCK_UNINSTALL_DELETE_ALL_BLOCKVOLUMES", + } { + if !strings.Contains(body, want) { + t.Fatalf("first-volume scenario missing %q", want) + } + } +} + +func TestPhase20AlphaStorageClassManifestIsDynamicPVCDefault(t *testing.T) { + body := g15dReadFile(t, "deploy", "k8s", "alpha", "storageclass.yaml") + for _, want := range []string{ + "kind: StorageClass", + "name: sw-block-dynamic", + "provisioner: block.csi.seaweedfs.com", + `replicationFactor: "1"`, + } { + if !strings.Contains(body, want) { + t.Fatalf("alpha storageclass missing %q", want) + } + } + uninstall := g15dReadFile(t, "scripts", "uninstall-k8s-alpha.sh") + for _, want := range []string{ + `STORAGECLASS_NAME="${SW_BLOCK_STORAGECLASS_NAME:-sw-block-dynamic}"`, + "delete alpha StorageClass", + `kubectl delete storageclass "$STORAGECLASS_NAME"`, + `storageclasses.storage.k8s.io \"$STORAGECLASS_NAME\" not found`, + } { + if !strings.Contains(uninstall, want) { + t.Fatalf("uninstall missing storageclass cleanup contract %q", want) + } + } +} + +func TestAlphaBlockStack_EnablesProductOwnedLauncherApply(t *testing.T) { + body := g15dReadFile(t, "deploy", "k8s", "alpha", "block-stack.yaml") + for _, want := range []string{ + "serviceAccountName: sw-block-master", + "hostNetwork: true", + "dnsPolicy: ClusterFirstWithHostNet", + "--launcher-kubernetes-apply", + "--launcher-status", + } { + if !strings.Contains(body, want) { + t.Fatalf("alpha block stack missing %q", want) + } + } + rbac := g15dReadFile(t, "deploy", "k8s", "alpha", "rbac.yaml") + for _, want := range []string{ + "name: sw-block-master", + "name: sw-block-master-launcher", + `resources: ["deployments"]`, + `verbs: ["get", "list", "watch", "create", "delete", "update", "patch"]`, + } { + if !strings.Contains(rbac, want) { + t.Fatalf("alpha rbac missing %q", want) + } + } +} + +func TestAlphaRBAC_MasterLauncherCanReconcilePVCOwnerNamespaces(t *testing.T) { + rbac := g15dReadFile(t, "deploy", "k8s", "alpha", "rbac.yaml") + for _, want := range []string{ + "kind: ClusterRole", + "kind: ClusterRoleBinding", + "name: sw-block-master-launcher", + `resources: ["deployments"]`, + `verbs: ["get", "list", "watch", "create", "delete", "update", "patch"]`, + "kind: ServiceAccount", + "name: sw-block-master", + "kind: ClusterRole", + "name: sw-block-master-launcher", + } { + if !strings.Contains(rbac, want) { + t.Fatalf("alpha rbac missing %q", want) + } + } + if strings.Contains(rbac, "kind: Role\nmetadata:\n name: sw-block-master-launcher") { + t.Fatalf("master launcher RBAC must not be namespace-local; PVC-owned blockvolumes are reconciled in app namespaces") + } +} + +func TestAlphaUninstall_DoesNotParseUnrenderedBlockStackTemplate(t *testing.T) { + body := g15dReadFile(t, "scripts", "uninstall-k8s-alpha.sh") + if strings.Contains(body, `kubectl delete -f "$ROOT/deploy/k8s/alpha/block-stack.yaml"`) { + t.Fatalf("uninstall must not parse unrendered block-stack.yaml template") + } + for _, want := range []string{ + "delete deploy/sw-blockmaster", + "delete svc/blockmaster", + "delete configmap/sw-block-cluster-spec", + "delete secret \"$CHAP_SECRET_NAME\"", + "delete-block-stack.log", + } { + if !strings.Contains(body, want) { + t.Fatalf("uninstall script missing %q", want) + } + } +} + +func TestApplyAlphaBlockvolumes_WaitsForGeneratedManifestInsteadOfKubeSystem(t *testing.T) { + body := g15dReadFile(t, "scripts", "apply-k8s-alpha-blockvolumes.sh") + if !strings.Contains(body, `kubectl wait -f "$ARTIFACT_DIR/generated-blockvolume.yaml" --for=condition=available`) { + t.Fatalf("apply script must wait using generated manifest:\n%s", body) + } + if strings.Contains(body, "kubectl -n kube-system wait --for=condition=available deploy -l app=sw-blockvolume") { + t.Fatalf("apply script must not hardcode kube-system generated workloads:\n%s", body) + } +} + +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) + path := filepath.Join(append([]string{root}, parts...)...) + raw, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + return string(raw) +} + +// The node-loss gate checks what this release claims: no automatic promotion +// while the primary's node is lost, then the same primary serves again. +func TestNodeLossGateExpectsNoAutomaticPromotion(t *testing.T) { + gate := g15dReadFile(t, "testops", "scenarios", "node-loss-survival-rf3-reattach-chain.yaml") + demo := g15dReadFile(t, "scripts", "run-alpha-app-demo.sh") + for _, want := range []string{"SW_BLOCK_DEMO_EXPECT_NO_AUTO_PROMOTION=1", "failover_status: recovered_same_primary", "auto_promotion_while_node_lost=none"} { + if !strings.Contains(gate, want) { + t.Fatalf("node-loss gate missing %q", want) + } + } + for _, gone := range []string{"failover_status: promoted\"", "SW_BLOCK_LAUNCHER_EXTERNAL_STATUS", "result=promoted"} { + if strings.Contains(gate, gone) { + t.Fatalf("node-loss gate still expects %q", gone) + } + } + for _, want := range []string{"SW_BLOCK_DEMO_EXPECT_NO_AUTO_PROMOTION", "failover_status: unexpected_auto_promotion", "failover_status: no_auto_promotion_unproven", "failover_status: recovered_same_primary", "primary frontend_primary_ready=false", "kubectl uncordon"} { + if !strings.Contains(demo, want) { + t.Fatalf("run-alpha-app-demo.sh missing %q", want) + } + } +} diff --git a/seaweed-block/cmd/blockcsi/main.go b/seaweed-block/cmd/blockcsi/main.go new file mode 100644 index 0000000000..a34a995e41 --- /dev/null +++ b/seaweed-block/cmd/blockcsi/main.go @@ -0,0 +1,241 @@ +// Command blockcsi is the CSI daemon. Current scope is static: it +// consumes already-published frontend target facts from blockmaster +// and mounts them through the node path; it does not create volumes +// or mint authority. +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "net" + "os" + "os/signal" + "path/filepath" + "syscall" + "time" + + csipb "github.com/container-storage-interface/spec/lib/go/csi" + blockcsi "github.com/seaweedfs/seaweed-block/core/csi" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/internal/buildinfo" + "google.golang.org/grpc" + "github.com/seaweedfs/seaweed-block/core/rpc/link" +) + +type flags struct { + endpoint string + masterAddr string + nodeID string + iqnPrefix string + pvcUIDLookup bool + swBlockVolumeCRNamespace string + stage2Multipath bool + nvmeReconnectOwner bool + nvmeReconnectInterval time.Duration + rejectLoopbackPublishTargets bool + version bool + printReadyLine bool + masterTLS link.TLSFiles // mutual TLS to blockmaster (all three or none) +} + +func parseFlags(args []string) (flags, error) { + var f flags + fs := flag.NewFlagSet("blockcsi", flag.ContinueOnError) + fs.StringVar(&f.endpoint, "endpoint", "unix:///var/lib/kubelet/plugins/block.csi.seaweedfs.com/csi.sock", "CSI endpoint, e.g. unix:///path/csi.sock or tcp://127.0.0.1:0") + fs.StringVar(&f.masterAddr, "master", "", "blockmaster gRPC address for read-only publish-target lookup") + fs.StringVar(&f.masterTLS.Cert, "master-tls-cert", "", "certificate presented to blockmaster (mutual TLS; with --master-tls-key and --master-ca)") + fs.StringVar(&f.masterTLS.Key, "master-tls-key", "", "key of --master-tls-cert") + fs.StringVar(&f.masterTLS.CA, "master-ca", "", "CA that blockmaster's certificate must verify against") + fs.StringVar(&f.nodeID, "node-id", "", "CSI node ID; defaults to hostname") + fs.StringVar(&f.iqnPrefix, "iqn-prefix", "iqn.2026-05.io.seaweedfs", "fallback IQN prefix for unstage after plugin restart") + fs.BoolVar(&f.pvcUIDLookup, "kubernetes-pvc-uid-lookup", false, "opt-in: resolve PVC UID through the in-cluster Kubernetes API before CreateVolume is sent to blockmaster") + fs.StringVar(&f.swBlockVolumeCRNamespace, "swblockvolume-cr-namespace", "", "opt-in: create or update SwBlockVolume CR identity objects in this namespace after successful CreateVolume") + fs.BoolVar(&f.stage2Multipath, "stage2-multipath", false, "opt-in: consume multiple iSCSI frontend targets as one host multipath device") + fs.BoolVar(&f.nvmeReconnectOwner, "nvme-reconnect-owner", false, "opt-in: CSI node periodically reconnects missing mounted NVMe paths from refreshed publish evidence") + fs.DurationVar(&f.nvmeReconnectInterval, "nvme-reconnect-interval", 5*time.Second, "interval for --nvme-reconnect-owner") + fs.BoolVar(&f.rejectLoopbackPublishTargets, "reject-loopback-publish-targets", false, "opt-in: reject loopback publish targets for node-loss recovery gates") + fs.BoolVar(&f.version, "version", false, "print build provenance and exit") + fs.BoolVar(&f.printReadyLine, "t0-print-ready", false, "internal test-only: emit one structured JSON ready line after listener bind") + fs.SetOutput(os.Stderr) + if err := fs.Parse(args); err != nil { + return flags{}, err + } + if f.version { + return f, nil + } + if f.endpoint == "" { + return flags{}, fmt.Errorf("--endpoint is required") + } + if f.masterAddr == "" && (f.stage2Multipath || f.nvmeReconnectOwner || f.rejectLoopbackPublishTargets || f.pvcUIDLookup || f.swBlockVolumeCRNamespace != "") { + return flags{}, fmt.Errorf("--stage2-multipath, --nvme-reconnect-owner, --reject-loopback-publish-targets, --kubernetes-pvc-uid-lookup, and --swblockvolume-cr-namespace require --master") + } + if f.masterTLS.Enabled() && f.masterAddr == "" { + return flags{}, fmt.Errorf("--master-tls-cert, --master-tls-key and --master-ca require --master") + } + if err := f.masterTLS.Check(); err != nil { + return flags{}, err + } + if f.nodeID == "" { + host, err := os.Hostname() + if err != nil || host == "" { + return flags{}, fmt.Errorf("--node-id is required when hostname is unavailable") + } + f.nodeID = host + } + return f, nil +} + +func main() { + f, err := parseFlags(os.Args[1:]) + if err != nil { + fmt.Fprintln(os.Stderr, "blockcsi:", err) + os.Exit(2) + } + if f.version { + fmt.Println(buildinfo.Version("blockcsi")) + return + } + os.Exit(run(f)) +} + +type readyLine struct { + Component string `json:"component"` + Phase string `json:"phase"` + Endpoint string `json:"endpoint"` + Network string `json:"network"` + Addr string `json:"addr"` +} + +func run(f flags) int { + network, addr, err := blockcsi.ParseEndpoint(f.endpoint) + if err != nil { + fmt.Fprintln(os.Stderr, "blockcsi:", err) + return 2 + } + cleanup, err := prepareEndpoint(network, addr) + if err != nil { + fmt.Fprintln(os.Stderr, "blockcsi:", err) + return 1 + } + defer cleanup() + + ln, err := net.Listen(network, addr) + if err != nil { + fmt.Fprintln(os.Stderr, "blockcsi: listen:", err) + return 1 + } + defer ln.Close() + + var ( + masterConn *grpc.ClientConn + lookup blockcsi.PublishTargetLookup + reporter blockcsi.EventReporter + provisioner blockcsi.VolumeProvisioner + resolver blockcsi.KubernetesMetadataResolver + registrar blockcsi.VolumeObjectRegistrar + ) + if f.masterAddr != "" { + var tls grpc.DialOption + if f.masterTLS.Enabled() { + if tls, err = link.ClientCredentials(f.masterTLS, ""); err != nil { + fmt.Fprintln(os.Stderr, "blockcsi: master TLS:", err) + return 1 + } + } + masterConn, err = link.DialMaster(f.masterAddr, tls) + if err != nil { + fmt.Fprintln(os.Stderr, "blockcsi: master dial:", err) + return 1 + } + defer masterConn.Close() + evidence := control.NewEvidenceServiceClient(masterConn) + var opts []blockcsi.ControlStatusLookupOption + if f.stage2Multipath { + opts = append(opts, blockcsi.WithMultipathPublishTargets()) + } + if f.rejectLoopbackPublishTargets { + opts = append(opts, blockcsi.WithLoopbackPublishTargetsRejected()) + } + lookup = blockcsi.NewControlStatusLookupWithOptions(evidence, opts...) + reporter = blockcsi.NewControlEventReporter(control.NewObservationServiceClient(masterConn)) + provisioner = blockcsi.NewControlLifecycleProvisioner(control.NewLifecycleServiceClient(masterConn)) + } + if f.pvcUIDLookup && provisioner != nil { + resolver, err = blockcsi.NewInClusterPVCMetadataResolver() + if err != nil { + fmt.Fprintln(os.Stderr, "blockcsi: pvc uid lookup:", err) + return 1 + } + } + if f.swBlockVolumeCRNamespace != "" && provisioner != nil { + registrar, err = blockcsi.NewInClusterSwBlockVolumeRegistrar(f.swBlockVolumeCRNamespace) + if err != nil { + fmt.Fprintln(os.Stderr, "blockcsi: swblockvolume registrar:", err) + return 1 + } + } + + nodeSrv := blockcsi.NewDefaultNodeServerWithLookupAndEventReporter(f.nodeID, f.iqnPrefix, lookup, reporter) + if f.nvmeReconnectOwner { + reconnectCtx, cancelReconnect := context.WithCancel(context.Background()) + defer cancelReconnect() + nodeSrv.StartMountedNVMeReconnectOwner(reconnectCtx, f.nvmeReconnectInterval) + } + + srv := link.NewServer(link.ServerConfig{}) + csipb.RegisterIdentityServer(srv, blockcsi.NewIdentityServer()) + csipb.RegisterControllerServer(srv, blockcsi.NewControllerServerWithProvisionerMetadataAndRegistrar(lookup, provisioner, resolver, registrar)) + csipb.RegisterNodeServer(srv, nodeSrv) + + if f.printReadyLine { + _ = json.NewEncoder(os.Stdout).Encode(readyLine{ + Component: "blockcsi", + Phase: "listening", + Endpoint: f.endpoint, + Network: network, + Addr: ln.Addr().String(), + }) + } + + errCh := make(chan error, 1) + go func() { errCh <- srv.Serve(ln) }() + + sig := make(chan os.Signal, 1) + signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) + select { + case err := <-errCh: + if err != nil && err != grpc.ErrServerStopped { + fmt.Fprintln(os.Stderr, "blockcsi: serve:", err) + return 1 + } + case <-sig: + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + done := make(chan struct{}) + go func() { + srv.GracefulStop() + close(done) + }() + select { + case <-done: + case <-ctx.Done(): + srv.Stop() + } + } + return 0 +} + +func prepareEndpoint(network, addr string) (func(), error) { + if network != "unix" { + return func() {}, nil + } + if err := os.MkdirAll(filepath.Dir(addr), 0o755); err != nil { + return nil, fmt.Errorf("create socket dir: %w", err) + } + if err := os.Remove(addr); err != nil && !os.IsNotExist(err) { + return nil, fmt.Errorf("remove stale socket: %w", err) + } + return func() { _ = os.Remove(addr) }, nil +} diff --git a/seaweed-block/cmd/blockcsi/main_test.go b/seaweed-block/cmd/blockcsi/main_test.go new file mode 100644 index 0000000000..324d0ec270 --- /dev/null +++ b/seaweed-block/cmd/blockcsi/main_test.go @@ -0,0 +1,466 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "net" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + csipb "github.com/container-storage-interface/spec/lib/go/csi" + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +func TestBlockCSI_BinaryStartsAndServesIdentity(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess test; -short skip") + } + bin := buildBlockCSIBinary(t) + logPath := filepath.Join(t.TempDir(), "blockcsi.log") + lf, err := os.Create(logPath) + if err != nil { + t.Fatalf("log file: %v", err) + } + defer lf.Close() + + cmd := exec.Command(bin, + "--endpoint", "tcp://127.0.0.1:0", + "--node-id", "node-a", + "--t0-print-ready", + ) + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatalf("stdout pipe: %v", err) + } + cmd.Stderr = lf + if err := cmd.Start(); err != nil { + t.Fatalf("start blockcsi: %v", err) + } + t.Cleanup(func() { + _ = cmd.Process.Signal(syscall.SIGTERM) + done := make(chan struct{}) + go func() { _ = cmd.Wait(); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + _ = cmd.Process.Kill() + <-done + } + if t.Failed() { + if b, err := os.ReadFile(logPath); err == nil { + t.Logf("=== blockcsi.log ===\n%s", b) + } + } + }) + + var ready readyLine + if err := json.NewDecoder(stdout).Decode(&ready); err != nil { + t.Fatalf("read ready line: %v", err) + } + if ready.Component != "blockcsi" || ready.Phase != "listening" || ready.Addr == "" { + t.Fatalf("ready=%+v", ready) + } + + conn, err := grpc.NewClient(ready.Addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("dial csi: %v", err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + info, err := csipb.NewIdentityClient(conn).GetPluginInfo(ctx, &csipb.GetPluginInfoRequest{}) + if err != nil { + t.Fatalf("GetPluginInfo: %v", err) + } + if info.GetName() != "block.csi.seaweedfs.com" { + t.Fatalf("driver name=%q", info.GetName()) + } +} + +func TestParseFlags_VersionDoesNotRequireEndpoint(t *testing.T) { + f, err := parseFlags([]string{"--version"}) + if err != nil { + t.Fatalf("parseFlags --version: %v", err) + } + if !f.version { + t.Fatal("version flag not set") + } +} + +func TestParseFlags_Stage2MultipathIsExplicitOptIn(t *testing.T) { + f, err := parseFlags([]string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a", "--master", "blockmaster:9333", "--stage2-multipath"}) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !f.stage2Multipath { + t.Fatal("stage2 multipath flag not set") + } +} + +func TestParseFlags_NVMeReconnectOwnerIsExplicitOptIn(t *testing.T) { + f, err := parseFlags([]string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a", "--master", "blockmaster:9333", "--nvme-reconnect-owner", "--nvme-reconnect-interval", "250ms"}) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !f.nvmeReconnectOwner { + t.Fatal("nvme reconnect owner flag not set") + } + if f.nvmeReconnectInterval != 250*time.Millisecond { + t.Fatalf("interval=%v", f.nvmeReconnectInterval) + } + if _, err := parseFlags([]string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a", "--nvme-reconnect-owner"}); err == nil { + t.Fatal("expected --nvme-reconnect-owner without --master to fail") + } +} + +func TestParseFlags_RejectLoopbackPublishTargetsIsExplicitOptIn(t *testing.T) { + f, err := parseFlags([]string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a", "--master", "blockmaster:9333", "--reject-loopback-publish-targets"}) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !f.rejectLoopbackPublishTargets { + t.Fatal("reject loopback publish targets flag not set") + } +} + +func TestParseFlags_SwBlockVolumeCRNamespaceRequiresMaster(t *testing.T) { + f, err := parseFlags([]string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a", "--master", "blockmaster:9333", "--swblockvolume-cr-namespace", "kube-system"}) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if f.swBlockVolumeCRNamespace != "kube-system" { + t.Fatalf("swblockvolume namespace=%q", f.swBlockVolumeCRNamespace) + } + if _, err := parseFlags([]string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a", "--swblockvolume-cr-namespace", "kube-system"}); err == nil { + t.Fatal("expected --swblockvolume-cr-namespace without --master to fail") + } +} + +func TestParseFlags_MasterDependentFlagsRequireMaster(t *testing.T) { + if _, err := parseFlags([]string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a", "--stage2-multipath"}); err == nil { + t.Fatal("expected --stage2-multipath without --master to fail") + } +} + +func TestG15a_BlockCSIControllerPublishUsesMasterFrontendFact(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess test; -short skip") + } + bins := buildG15aBinaries(t) + art := t.TempDir() + + master := startG15aMaster(t, bins.master, art) + primaryData, primaryCtrl := pickTCPAddr(t), pickTCPAddr(t) + replicaData, replicaCtrl := pickTCPAddr(t), pickTCPAddr(t) + iscsiAddr := pickTCPAddr(t) + iqn := "iqn.2026-05.io.seaweedfs:g15a-csi-v1" + + _ = startG15aVolume(t, bins.volume, art, g15aVolumeOpts{ + masterAddr: master.addr, + serverID: "s1", + replicaID: "r1", + dataAddr: primaryData, + ctrlAddr: primaryCtrl, + iscsiAddr: iscsiAddr, + iscsiIQN: iqn, + logTag: "primary", + }) + _ = startG15aVolume(t, bins.volume, art, g15aVolumeOpts{ + masterAddr: master.addr, + serverID: "s2", + replicaID: "r2", + dataAddr: replicaData, + ctrlAddr: replicaCtrl, + logTag: "replica", + }) + csi := startG15aCSI(t, bins.csi, master.addr) + + conn, err := grpc.NewClient(csi.addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("dial blockcsi: %v", err) + } + defer conn.Close() + client := csipb.NewControllerClient(conn) + + var last map[string]string + deadline := time.Now().Add(60 * time.Second) + for time.Now().Before(deadline) { + ctx, cancel := context.WithTimeout(context.Background(), 700*time.Millisecond) + resp, err := client.ControllerPublishVolume(ctx, &csipb.ControllerPublishVolumeRequest{ + VolumeId: "v1", + NodeId: "node-a", + }) + cancel() + if err == nil { + last = resp.GetPublishContext() + if last["iscsiAddr"] == iscsiAddr && last["iqn"] == iqn { + return + } + } + time.Sleep(150 * time.Millisecond) + } + t.Fatalf("ControllerPublish did not return frontend fact; last publish_context=%v", last) +} + +type g15aBins struct { + master string + volume string + csi string +} + +func buildG15aBinaries(t *testing.T) g15aBins { + t.Helper() + dir := t.TempDir() + suf := "" + if os.PathSeparator == '\\' { + suf = ".exe" + } + bins := g15aBins{ + master: filepath.Join(dir, "blockmaster"+suf), + volume: filepath.Join(dir, "blockvolume"+suf), + csi: filepath.Join(dir, "blockcsi"+suf), + } + for _, b := range []struct{ pkg, out string }{ + {"github.com/seaweedfs/seaweed-block/cmd/blockmaster", bins.master}, + {"github.com/seaweedfs/seaweed-block/cmd/blockvolume", bins.volume}, + {"github.com/seaweedfs/seaweed-block/cmd/blockcsi", bins.csi}, + } { + cmd := exec.Command("go", "build", "-o", b.out, b.pkg) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("build %s: %v\n%s", b.pkg, err, out) + } + } + return bins +} + +type g15aProc struct { + cmd *exec.Cmd + logPath string + addr string +} + +func (p *g15aProc) stop(t *testing.T) { + if p.cmd != nil && p.cmd.Process != nil { + _ = p.cmd.Process.Signal(syscall.SIGTERM) + done := make(chan struct{}) + go func() { _ = p.cmd.Wait(); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + _ = p.cmd.Process.Kill() + <-done + } + } + if t.Failed() { + if b, err := os.ReadFile(p.logPath); err == nil { + t.Logf("=== %s ===\n%s", filepath.Base(p.logPath), b) + } + } +} + +func startG15aMaster(t *testing.T, bin, art string) *g15aProc { + t.Helper() + topo := filepath.Join(art, "topology.yaml") + if err := os.WriteFile(topo, []byte(`volumes: + - volume_id: v1 + slots: + - replica_id: r1 + server_id: s1 + - replica_id: r2 + server_id: s2 +`), 0o644); err != nil { + t.Fatalf("topology: %v", err) + } + logPath := filepath.Join(art, "blockmaster.log") + lf, err := os.Create(logPath) + if err != nil { + t.Fatalf("master log: %v", err) + } + cmd := exec.Command(bin, + "--authority-store", filepath.Join(art, "authority-store"), + "--listen", "127.0.0.1:0", + "--topology", topo, + "--expected-slots-per-volume", "2", + "--t0-print-ready", + ) + stdout, err := cmd.StdoutPipe() + if err != nil { + lf.Close() + t.Fatalf("master stdout: %v", err) + } + cmd.Stderr = lf + if err := cmd.Start(); err != nil { + lf.Close() + t.Fatalf("master start: %v", err) + } + p := &g15aProc{cmd: cmd, logPath: logPath} + t.Cleanup(func() { + p.stop(t) + lf.Close() + }) + var ready struct { + Addr string `json:"addr"` + } + if err := json.NewDecoder(stdout).Decode(&ready); err != nil { + t.Fatalf("master ready: %v", err) + } + if ready.Addr == "" { + t.Fatal("master ready missing addr") + } + p.addr = ready.Addr + return p +} + +type g15aVolumeOpts struct { + masterAddr string + serverID string + replicaID string + dataAddr string + ctrlAddr string + iscsiAddr string + iscsiIQN string + logTag string +} + +func startG15aVolume(t *testing.T, bin, art string, o g15aVolumeOpts) *g15aProc { + t.Helper() + logPath := filepath.Join(art, fmt.Sprintf("blockvolume-%s.log", o.logTag)) + lf, err := os.Create(logPath) + if err != nil { + t.Fatalf("volume log: %v", err) + } + cmd := exec.Command(bin, + "--master", o.masterAddr, + "--server-id", o.serverID, + "--volume-id", "v1", + "--replica-id", o.replicaID, + "--data-addr", o.dataAddr, + "--ctrl-addr", o.ctrlAddr, + "--volume-lock-dir-test-only", t.TempDir(), + "--durable-root", filepath.Join(art, "store-"+o.logTag), + "--durable-impl", "walstore", + "--durable-blocks", "256", + "--durable-blocksize", "4096", + "--heartbeat-interval", "200ms", + "--t1-readiness", + ) + // The test override is refused under systemd; do not inherit the test runner's invocation. + for _, kv := range os.Environ() { + if !strings.HasPrefix(kv, "INVOCATION_ID=") { + cmd.Env = append(cmd.Env, kv) + } + } + if o.iscsiAddr != "" { + cmd.Args = append(cmd.Args, + "--iscsi-listen", o.iscsiAddr, + "--iscsi-iqn", o.iscsiIQN, + ) + } + cmd.Stdout = lf + cmd.Stderr = lf + if err := cmd.Start(); err != nil { + lf.Close() + t.Fatalf("volume start: %v", err) + } + p := &g15aProc{cmd: cmd, logPath: logPath} + t.Cleanup(func() { + p.stop(t) + lf.Close() + }) + return p +} + +func startG15aCSI(t *testing.T, bin, masterAddr string) *g15aProc { + t.Helper() + logPath := filepath.Join(t.TempDir(), "blockcsi.log") + lf, err := os.Create(logPath) + if err != nil { + t.Fatalf("csi log: %v", err) + } + cmd := exec.Command(bin, + "--endpoint", "tcp://127.0.0.1:0", + "--master", masterAddr, + "--node-id", "node-a", + "--t0-print-ready", + ) + stdout, err := cmd.StdoutPipe() + if err != nil { + lf.Close() + t.Fatalf("csi stdout: %v", err) + } + cmd.Stderr = lf + if err := cmd.Start(); err != nil { + lf.Close() + t.Fatalf("csi start: %v", err) + } + p := &g15aProc{cmd: cmd, logPath: logPath} + t.Cleanup(func() { + p.stop(t) + lf.Close() + }) + var ready readyLine + if err := json.NewDecoder(stdout).Decode(&ready); err != nil { + t.Fatalf("csi ready: %v", err) + } + if ready.Addr == "" { + t.Fatal("csi ready missing addr") + } + p.addr = ready.Addr + return p +} + +func pickTCPAddr(t *testing.T) string { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("pick addr: %v", err) + } + addr := ln.Addr().String() + _ = ln.Close() + return addr +} + +func buildBlockCSIBinary(t *testing.T) string { + t.Helper() + dir := t.TempDir() + suf := "" + if os.PathSeparator == '\\' { + suf = ".exe" + } + out := filepath.Join(dir, "blockcsi"+suf) + cmd := exec.Command("go", "build", "-o", out, "github.com/seaweedfs/seaweed-block/cmd/blockcsi") + if b, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("build blockcsi: %v\n%s", err, b) + } + return out +} + +// The master TLS flags come as a set, need --master, and every file is read +// at parse time. +func TestParseFlags_MasterTLS(t *testing.T) { + dir := t.TempDir() + ca := authtest.NewCA(t, "ca") + caPath := ca.WriteCA(t, dir) + cert, key := ca.Issue(t, "csi", time.Now().Add(time.Hour)).WriteFiles(t, dir, "csi") + base := []string{"--endpoint", "unix:///tmp/csi.sock", "--node-id", "node-a"} + tlsArgs := []string{"--master-tls-cert", cert, "--master-tls-key", key, "--master-ca", caPath} + + f, err := parseFlags(append(append(base, "--master", "blockmaster:9333"), tlsArgs...)) + if err != nil || !f.masterTLS.Enabled() { + t.Fatalf("full set: %v (enabled=%t)", err, f.masterTLS.Enabled()) + } + if _, err := parseFlags(append(base, tlsArgs...)); err == nil || !strings.Contains(err.Error(), "require --master") { + t.Fatalf("TLS without --master: %v", err) + } + if _, err := parseFlags(append(base, "--master", "blockmaster:9333", "--master-tls-cert", cert)); err == nil { + t.Fatal("a partial TLS set was accepted") + } +} diff --git a/seaweed-block/cmd/blockmaster/README.md b/seaweed-block/cmd/blockmaster/README.md new file mode 100644 index 0000000000..43c639bb8b --- /dev/null +++ b/seaweed-block/cmd/blockmaster/README.md @@ -0,0 +1,19 @@ +# Cluster imports and desired volumes + +With `--lifecycle-store`, authority publication requires a lifecycle VolumeRecord. +A placement intent or a remote chunk catalog `VOLUME` alone is not that record. + +`--cluster-spec` registers each volume with positive `size_bytes` and its +`replication_factor` before importing placement and starting publication. The +registration is durable and idempotent. A different size/RF from an existing +record refuses startup; existing protocol/transport and Kubernetes metadata are +preserved. Volume registration records desired state, not authority or an epoch. + +For a legacy cluster spec without `size_bytes`, call the LifecycleService +`CreateVolume` RPC (the CSI create path also does this) before expecting the +imported placement to publish. `--lifecycle-placement-seed` is placement-only: +it has no capacity field, so the same CreateVolume prerequisite applies. +The master refuses missing records with the volume ID and this instruction; +it does not infer capacity or bypass the publication guard. + +Legacy `--topology` without a lifecycle store keeps its existing behaviour. diff --git a/seaweed-block/cmd/blockmaster/auth.go b/seaweed-block/cmd/blockmaster/auth.go new file mode 100644 index 0000000000..acb5c7aded --- /dev/null +++ b/seaweed-block/cmd/blockmaster/auth.go @@ -0,0 +1,123 @@ +package main + +import ( + "crypto/tls" + "crypto/x509" + "fmt" + "os" + "os/signal" + "syscall" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc" +) + +// authFlags are blockmaster's phase 0 authentication flags: its own TLS +// certificate and key, the CA every client certificate must verify against, +// and the role file (fingerprint -> role, id). All four or none; none is +// development mode (plaintext, loopback only). +type authFlags struct { + tlsCert, tlsKey, tlsClientCA, roleFile string + auditLog string // append-only audit log (optional) + // connectionAge is how long a client connection lives before blockmaster + // asks for a reconnect (a fresh handshake); 24 h, shorter only in tests. + connectionAge time.Duration +} + +func (a authFlags) enabled() bool { + return a.tlsCert != "" || a.tlsKey != "" || a.tlsClientCA != "" || a.roleFile != "" +} + +func (a authFlags) files() link.TLSFiles { + return link.TLSFiles{Cert: a.tlsCert, Key: a.tlsKey, CA: a.tlsClientCA} +} + +// validate refuses a partial set. +func (a authFlags) validate() error { + if a.auditLog != "" && !a.enabled() { + return fmt.Errorf("--audit-log needs authentication (--tls-cert, --tls-key, --tls-client-ca, --role-file)") + } + if !a.enabled() { + return nil + } + if a.tlsCert == "" || a.tlsKey == "" || a.tlsClientCA == "" || a.roleFile == "" { + return fmt.Errorf("authentication needs --tls-cert, --tls-key, --tls-client-ca and --role-file together") + } + if a.auditLog == "" { + return fmt.Errorf("authentication needs --audit-log: every changing call is recorded before it runs, and is refused when it cannot be") + } + return nil +} + +// build returns the authenticator and the server options of an +// authenticated master, or nil and none in development mode. Every file is +// read here, so a wrong one refuses the start. +func (a authFlags) build() (*auth.Authenticator, []grpc.ServerOption, error) { + if !a.enabled() { + return nil, nil, nil + } + creds, err := link.ServerCredentials(a.files()) + if err != nil { + return nil, nil, err + } + table, err := auth.LoadRoleFile(a.roleFile) + if err != nil { + return nil, nil, err + } + authn := auth.NewAuthenticator(table, nil) + if a.auditLog != "" { + l, _, err := auth.OpenAuditLog(a.auditLog) + if err != nil { + return nil, nil, err + } + authn.SetAudit(l) + } + age := a.connectionAge + if age <= 0 { + age = link.MasterConnectionAge + } + return authn, []grpc.ServerOption{creds, link.ConnectionAge(age)}, nil +} + +// certDaysLeft is the days to expiry of the certificate file at path. +func certDaysLeft(certPath, keyPath string, now time.Time) (int, time.Time, error) { + pair, err := tls.LoadX509KeyPair(certPath, keyPath) + if err != nil { + return 0, time.Time{}, err + } + leaf, err := x509.ParseCertificate(pair.Certificate[0]) + if err != nil { + return 0, time.Time{}, err + } + return int(leaf.NotAfter.Sub(now).Hours() / 24), leaf.NotAfter, nil +} + +// reloadRolesOnSIGHUP reloads the role file at every SIGHUP; a malformed or +// unreadable file keeps the current table and says so. Removing a line +// revokes that certificate at the reload (its open streams end). +func reloadRolesOnSIGHUP(a *auth.Authenticator, path string) { + hup := make(chan os.Signal, 1) + signal.Notify(hup, syscall.SIGHUP) + go func() { + for range hup { + if err := a.Reload(path); err != nil { + fmt.Fprintf(os.Stderr, "blockmaster: role file %s NOT reloaded, the previous table stays: %v\n", path, err) + continue + } + fmt.Fprintf(os.Stderr, "blockmaster: role file %s reloaded\n", path) + } + }() +} + +// warnUnauthenticated repeats the development-mode warning once a minute. +func warnUnauthenticated(listen string) { + msg := fmt.Sprintf("blockmaster: UNAUTHENTICATED CONTROL API on %s (development mode)", listen) + fmt.Fprintln(os.Stderr, msg) + go func() { + for range time.Tick(time.Minute) { + fmt.Fprintln(os.Stderr, msg) + } + }() +} diff --git a/seaweed-block/cmd/blockmaster/auth_flags_test.go b/seaweed-block/cmd/blockmaster/auth_flags_test.go new file mode 100644 index 0000000000..70dd846616 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/auth_flags_test.go @@ -0,0 +1,41 @@ +package main + +import ( + "strings" + "testing" +) + +// Phase 0 flags: the four authentication flags go together; with them the +// listener may bind any address; without them the control listener stays +// loopback-only; --insecure-external-bind is refused either way; the +// launcher's node TLS needs blockmaster's own and no external status. +func TestAuthFlags(t *testing.T) { + base := []string{"--authority-store", t.TempDir()} + all := []string{"--tls-cert", "c.pem", "--tls-key", "k.pem", "--tls-client-ca", "ca.pem", "--role-file", "roles", "--audit-log", "audit.log"} + for _, c := range []struct { + name string + args []string + want string // "" = accepted + }{ + {"development mode, loopback", []string{"--listen", "127.0.0.1:9180"}, ""}, + {"development mode, off loopback", []string{"--listen", "192.0.2.5:9180"}, "not a loopback address"}, + {"authenticated, off loopback", append([]string{"--listen", "192.0.2.5:9180"}, all...), ""}, + {"partial: no role file", []string{"--listen", "192.0.2.5:9180", "--tls-cert", "c.pem", "--tls-key", "k.pem", "--tls-client-ca", "ca.pem"}, "together"}, + {"partial: role file only", []string{"--role-file", "roles"}, "together"}, + {"audit log without authentication", []string{"--audit-log", "audit.log"}, "needs authentication"}, + {"authentication without an audit log", []string{"--listen", "192.0.2.5:9180", "--tls-cert", "c.pem", "--tls-key", "k.pem", "--tls-client-ca", "ca.pem", "--role-file", "roles"}, "needs --audit-log"}, + {"authenticated with --insecure-external-bind", append([]string{"--listen", "192.0.2.5:9180", "--insecure-external-bind"}, all...), "no longer accepted"}, + {"development mode with --insecure-external-bind", []string{"--listen", "192.0.2.5:9180", "--insecure-external-bind"}, "no longer accepted"}, + {"launcher node TLS without blockmaster TLS", []string{"--launcher-master-tls-secret-prefix", "sw-block-node-tls"}, "needs blockmaster's own mutual TLS"}, + {"launcher node TLS", append([]string{"--launcher-master-tls-secret-prefix", "sw-block-node-tls"}, all...), ""}, + {"launcher node TLS with external status", append([]string{"--launcher-master-tls-secret-prefix", "sw-block-node-tls", "--launcher-external-status"}, all...), "cannot be combined"}, + } { + _, err := parseFlags(append(append([]string{}, base...), c.args...)) + switch { + case c.want == "" && err != nil: + t.Errorf("%s: %v; want accepted", c.name, err) + case c.want != "" && (err == nil || !strings.Contains(err.Error(), c.want)): + t.Errorf("%s: %v; want an error naming %q", c.name, err, c.want) + } + } +} diff --git a/seaweed-block/cmd/blockmaster/chart_flag_regression_test.go b/seaweed-block/cmd/blockmaster/chart_flag_regression_test.go new file mode 100644 index 0000000000..2ab5c80c2b --- /dev/null +++ b/seaweed-block/cmd/blockmaster/chart_flag_regression_test.go @@ -0,0 +1,25 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestChartOptInLoopbackFlagIsAcceptedByBlockmaster(t *testing.T) { + if os.Getenv("SEAWEED_KNOWN_BUGS") != "1" { + t.Skip("known bug #186 (open): reproduction runs with SEAWEED_KNOWN_BUGS=1; the fix PR removes this skip") + } + raw, err := os.ReadFile(filepath.Join("..", "..", "charts", "seaweed-block", "templates", "blockmaster.yaml")) + if err != nil { + t.Fatal(err) + } + const flag = "--launcher-reject-loopback-publish-targets" + if !strings.Contains(string(raw), flag) { + t.Skip("chart no longer emits this opt-in flag") + } + if _, err := parseFlags([]string{"--authority-store", t.TempDir(), flag}); err != nil { + t.Fatalf("chart opt-in flag rejected by real binary parser: %v", err) + } +} diff --git a/seaweed-block/cmd/blockmaster/chart_state_regression_test.go b/seaweed-block/cmd/blockmaster/chart_state_regression_test.go new file mode 100644 index 0000000000..3c44d819bc --- /dev/null +++ b/seaweed-block/cmd/blockmaster/chart_state_regression_test.go @@ -0,0 +1,35 @@ +package main + +import ( + "gopkg.in/yaml.v3" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestChartDefaultAuthorityStateSurvivesPodReplacement(t *testing.T) { + if os.Getenv("SEAWEED_KNOWN_BUGS") != "1" { + t.Skip("known bug #187 (open): reproduction runs with SEAWEED_KNOWN_BUGS=1; the fix PR removes this skip") + } + var values struct { + Blockmaster struct { + StateHostPath string `yaml:"stateHostPath"` + AuthorityStore string `yaml:"authorityStore"` + } `yaml:"blockmaster"` + } + raw, err := os.ReadFile(filepath.Join("..", "..", "charts", "seaweed-block", "values.yaml")) + if err != nil { + t.Fatal(err) + } + if err := yaml.Unmarshal(raw, &values); err != nil { + t.Fatal(err) + } + template, err := os.ReadFile(filepath.Join("..", "..", "charts", "seaweed-block", "templates", "blockmaster.yaml")) + if err != nil { + t.Fatal(err) + } + if values.Blockmaster.StateHostPath == "" && strings.Contains(string(template), "emptyDir: {}") { + t.Fatalf("default authorityStore=%s uses the chart's emptyDir state branch; a replacement Pod receives an empty store (same-Pod container restart is unaffected)", values.Blockmaster.AuthorityStore) + } +} diff --git a/seaweed-block/cmd/blockmaster/cluster_spec.go b/seaweed-block/cmd/blockmaster/cluster_spec.go new file mode 100644 index 0000000000..5e6c17b2d9 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/cluster_spec.go @@ -0,0 +1,139 @@ +package main + +import ( + "fmt" + "os" + + "github.com/seaweedfs/seaweed-block/core/geometry" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + "gopkg.in/yaml.v3" +) + +type clusterSpecFile struct { + Nodes []clusterSpecNode `yaml:"nodes"` + Volumes []clusterSpecVolume `yaml:"volumes"` +} + +type clusterSpecNode struct { + ServerID string `yaml:"server_id"` + Addr string `yaml:"addr"` + DataAddr string `yaml:"data_addr"` + CtrlAddr string `yaml:"ctrl_addr"` + Labels map[string]string `yaml:"labels"` + Pools []clusterSpecPool `yaml:"pools"` +} + +type clusterSpecPool struct { + PoolID string `yaml:"pool_id"` + TotalBytes uint64 `yaml:"total_bytes"` + FreeBytes uint64 `yaml:"free_bytes"` + BlockSize uint64 `yaml:"block_size"` + Labels map[string]string `yaml:"labels"` +} + +type clusterSpecVolume struct { + ID string `yaml:"id"` + SizeBytes uint64 `yaml:"size_bytes"` + ReplicationFactor int `yaml:"replication_factor"` + Placements []clusterSpecPlacementSlot `yaml:"placements"` +} + +type clusterSpecPlacementSlot struct { + ServerID string `yaml:"server_id"` + ReplicaID string `yaml:"replica_id"` + Source string `yaml:"source"` +} + +type clusterSpecImport struct { + Volumes []lifecycle.VolumeSpec + Topology topologyFile + Nodes []lifecycle.NodeRegistration + Placements []lifecycle.PlacementIntent +} + +func loadClusterSpec(path string) (clusterSpecImport, error) { + raw, err := os.ReadFile(path) + if err != nil { + return clusterSpecImport{}, fmt.Errorf("cluster spec: read %q: %w", path, err) + } + var spec clusterSpecFile + if err := yaml.Unmarshal(raw, &spec); err != nil { + return clusterSpecImport{}, fmt.Errorf("cluster spec: parse %q: %w", path, err) + } + return clusterSpecToImports(spec) +} + +func clusterSpecToImports(spec clusterSpecFile) (clusterSpecImport, error) { + var out clusterSpecImport + for i, node := range spec.Nodes { + if node.ServerID == "" { + return clusterSpecImport{}, fmt.Errorf("cluster spec: node[%d] missing server_id", i) + } + reg := lifecycle.NodeRegistration{ + ServerID: node.ServerID, + Addr: node.Addr, + DataAddr: node.DataAddr, + CtrlAddr: node.CtrlAddr, + Labels: node.Labels, + Pools: make([]lifecycle.StoragePool, 0, len(node.Pools)), + } + for j, pool := range node.Pools { + if pool.PoolID == "" { + return clusterSpecImport{}, fmt.Errorf("cluster spec: node %q pool[%d] missing pool_id", node.ServerID, j) + } + reg.Pools = append(reg.Pools, lifecycle.StoragePool{ + PoolID: pool.PoolID, + TotalBytes: pool.TotalBytes, + FreeBytes: pool.FreeBytes, + BlockSize: pool.BlockSize, + Labels: pool.Labels, + }) + } + out.Nodes = append(out.Nodes, reg) + } + for i, vol := range spec.Volumes { + if vol.ID == "" { + return clusterSpecImport{}, fmt.Errorf("cluster spec: volume[%d] missing id", i) + } + if vol.ReplicationFactor <= 0 { + return clusterSpecImport{}, fmt.Errorf("cluster spec: volume %q replication_factor must be > 0", vol.ID) + } + if len(vol.Placements) != vol.ReplicationFactor { + return clusterSpecImport{}, fmt.Errorf("cluster spec: volume %q placements %d != replication_factor %d", vol.ID, len(vol.Placements), vol.ReplicationFactor) + } + // Placement-only legacy specifications cannot supply a capacity. They + // retain the explicit CreateVolume prerequisite rather than inventing one. + if err := geometry.ValidateNewVolumeSize(vol.SizeBytes); err != nil { + return clusterSpecImport{}, fmt.Errorf("cluster spec: volume %q: %w", vol.ID, err) + } + if vol.SizeBytes > 0 { + out.Volumes = append(out.Volumes, lifecycle.VolumeSpec{VolumeID: vol.ID, SizeBytes: vol.SizeBytes, ReplicationFactor: vol.ReplicationFactor}) + } + topVol := topologyVolume{VolumeID: vol.ID} + intent := lifecycle.PlacementIntent{ + VolumeID: vol.ID, + DesiredRF: vol.ReplicationFactor, + } + for j, slot := range vol.Placements { + if slot.ServerID == "" || slot.ReplicaID == "" { + return clusterSpecImport{}, fmt.Errorf("cluster spec: volume %q placement[%d] missing server_id or replica_id", vol.ID, j) + } + source := slot.Source + if source == "" { + source = lifecycle.PlacementSourceExistingReplica + } + topVol.Slots = append(topVol.Slots, topologySlot{ + ServerID: slot.ServerID, + ReplicaID: slot.ReplicaID, + }) + intent.Slots = append(intent.Slots, lifecycle.PlacementSlotIntent{ + ServerID: slot.ServerID, + ReplicaID: slot.ReplicaID, + Source: source, + }) + } + out.Topology.Volumes = append(out.Topology.Volumes, topVol) + out.Placements = append(out.Placements, intent) + } + return out, nil +} diff --git a/seaweed-block/cmd/blockmaster/cluster_spec_max_size_test.go b/seaweed-block/cmd/blockmaster/cluster_spec_max_size_test.go new file mode 100644 index 0000000000..1994f5807c --- /dev/null +++ b/seaweed-block/cmd/blockmaster/cluster_spec_max_size_test.go @@ -0,0 +1,49 @@ +package main + +import ( + "errors" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/geometry" +) + +// The cluster spec is read before blockmaster starts serving: a volume of +// exactly MaxNewVolumeBytes is imported, one block or one chunk more refuses the start +// with an error naming the volume and the maximum. +func TestClusterSpecRefusesAVolumeAboveTheMaximum(t *testing.T) { + for _, c := range []struct { + name string + size uint64 + ok bool + }{ + {"at the maximum", geometry.MaxNewVolumeBytes, true}, + {"one block above", geometry.MaxNewVolumeBytes + 4096, false}, + {"one chunk above", geometry.MaxNewVolumeBytes + 4<<20, false}, + } { + t.Run(c.name, func(t *testing.T) { + b, err := os.ReadFile(writeClusterSpecForTest(t)) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "spec.yaml") + raw := strings.Replace(string(b), " size_bytes: 1048576\n", " size_bytes: "+strconv.FormatUint(c.size, 10)+"\n", 1) + if err := os.WriteFile(path, []byte(raw), 0o600); err != nil { + t.Fatal(err) + } + imports, err := loadClusterSpec(path) + if c.ok { + if err != nil || len(imports.Volumes) != 1 || imports.Volumes[0].SizeBytes != c.size { + t.Fatalf("volume of %d bytes: %+v, %v", c.size, imports.Volumes, err) + } + return + } + if !errors.Is(err, geometry.ErrVolumeTooLarge) || !strings.Contains(err.Error(), `"v1"`) || !strings.Contains(err.Error(), strconv.FormatUint(geometry.MaxNewVolumeBytes, 10)) { + t.Fatalf("volume of %d bytes: got %v, want ErrVolumeTooLarge naming v1 and the maximum", c.size, err) + } + }) + } +} diff --git a/seaweed-block/cmd/blockmaster/cluster_spec_reserved_test.go b/seaweed-block/cmd/blockmaster/cluster_spec_reserved_test.go new file mode 100644 index 0000000000..52fc9beea1 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/cluster_spec_reserved_test.go @@ -0,0 +1,76 @@ +package main + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +// r4 P2: the cluster-spec import never re-creates (or places) an id a +// volume delete reserved, also after a restart with the original spec; +// unreserved ids keep importing idempotently. +func TestClusterSpecImportSkipsAReservedVolume(t *testing.T) { + cfg := master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir()} + open := func() *master.Host { + t.Helper() + h, err := master.New(cfg) + if err != nil { + t.Fatal(err) + } + return h + } + // Imports run before Start, as in run(); a host is started before Close + // (Close waits on a server that Start launches). + closeHost := func(h *master.Host) { + h.Start() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = h.Close(ctx) + } + specs := []lifecycle.VolumeSpec{ + {VolumeID: "gone", SizeBytes: 1 << 20, ReplicationFactor: 1}, + {VolumeID: "kept", SizeBytes: 1 << 20, ReplicationFactor: 1}, + } + h := open() + if err := importLifecycleVolumes(h, specs); err != nil { + t.Fatal(err) + } + // "gone" is deleted: reservation committed, its record removed by the + // ordinary lifecycle delete. + if _, err := h.Lifecycle().Deletions.Admit("gone", "d1"); err != nil { + t.Fatal(err) + } + if _, err := h.Lifecycle().Deletions.Commit("gone", "d1"); err != nil { + t.Fatal(err) + } + if err := h.Lifecycle().Volumes.DeleteVolume("gone"); err != nil { + t.Fatal(err) + } + closeHost(h) + + h = open() // restart with the original spec + defer closeHost(h) + for i := 0; i < 2; i++ { + if err := importLifecycleVolumes(h, specs); err != nil { + t.Fatalf("import %d: %v", i, err) + } + } + if _, ok := h.Lifecycle().Volumes.GetVolume("gone"); ok { + t.Fatal("the import re-created a reserved id") + } + if _, ok := h.Lifecycle().Volumes.GetVolume("kept"); !ok { + t.Fatal("an unreserved volume was not imported") + } + intents := []lifecycle.PlacementIntent{ + {VolumeID: "gone", DesiredRF: 1, Slots: []lifecycle.PlacementSlotIntent{{ServerID: "s1", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}, + } + if err := importLifecyclePlacementIntents(h, intents); err != nil { + t.Fatal(err) + } + if _, ok := h.Lifecycle().Placements.GetPlacement("gone"); ok { + t.Fatal("the import placed a reserved id") + } +} diff --git a/seaweed-block/cmd/blockmaster/cluster_spec_test.go b/seaweed-block/cmd/blockmaster/cluster_spec_test.go new file mode 100644 index 0000000000..0f4ddc08b4 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/cluster_spec_test.go @@ -0,0 +1,66 @@ +package main + +import ( + "os" + "path/filepath" + "testing" +) + +func TestClusterSpec_ImportsDesiredVolumeNodeAndPlacement(t *testing.T) { + path := writeClusterSpecForTest(t) + imports, err := loadClusterSpec(path) + if err != nil { + t.Fatalf("load cluster spec: %v", err) + } + if len(imports.Topology.Volumes) != 1 || imports.Topology.Volumes[0].VolumeID != "v1" { + t.Fatalf("topology=%+v want one v1 volume", imports.Topology) + } + if len(imports.Nodes) != 1 { + t.Fatalf("nodes=%+v want one node", imports.Nodes) + } + node := imports.Nodes[0] + if node.ServerID != "s2" || node.DataAddr != "10.0.0.2:19080" || node.CtrlAddr != "10.0.0.2:19081" { + t.Fatalf("node=%+v want s2 with data/control addrs", node) + } + if len(node.Pools) != 1 || node.Pools[0].PoolID != "default" || node.Pools[0].FreeBytes != 1048576 { + t.Fatalf("node pools=%+v want default pool", node.Pools) + } + if len(imports.Topology.Volumes[0].Slots) != 1 || imports.Topology.Volumes[0].Slots[0].ReplicaID != "r2" { + t.Fatalf("topology slots=%+v want r2", imports.Topology.Volumes[0].Slots) + } + if len(imports.Placements) != 1 || imports.Placements[0].VolumeID != "v1" || imports.Placements[0].DesiredRF != 1 { + t.Fatalf("placements=%+v want v1 rf=1", imports.Placements) + } + slot := imports.Placements[0].Slots[0] + if slot.ServerID != "s2" || slot.ReplicaID != "r2" || slot.Source != "existing_replica" { + t.Fatalf("placement slot=%+v want s2/r2 existing_replica", slot) + } +} + +func writeClusterSpecForTest(t *testing.T) string { + t.Helper() + path := filepath.Join(t.TempDir(), "m01.yaml") + raw := []byte(` +nodes: + - server_id: s2 + data_addr: 10.0.0.2:19080 + ctrl_addr: 10.0.0.2:19081 + pools: + - pool_id: default + total_bytes: 1048576 + free_bytes: 1048576 + block_size: 4096 +volumes: + - id: v1 + size_bytes: 1048576 + replication_factor: 1 + placements: + - server_id: s2 + replica_id: r2 + source: existing_replica +`) + if err := os.WriteFile(path, raw, 0o644); err != nil { + t.Fatalf("write cluster spec: %v", err) + } + return path +} diff --git a/seaweed-block/cmd/blockmaster/cluster_volume_cli_test.go b/seaweed-block/cmd/blockmaster/cluster_volume_cli_test.go new file mode 100644 index 0000000000..3784e9c8c7 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/cluster_volume_cli_test.go @@ -0,0 +1,235 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "syscall" + "testing" + "time" +) + +func TestClusterVolumeCLIHelper(t *testing.T) { + file := os.Getenv("BLOCKMASTER_IMPORT_ARGS") + if file == "" { + t.Skip("subprocess helper") + } + data, e := os.ReadFile(file) + if e != nil { + t.Fatal(e) + } + var args []string + if e = json.Unmarshal(data, &args); e != nil { + t.Fatal(e) + } + f, e := parseFlags(args) + if e != nil { + t.Fatal(e) + } + os.Exit(run(f)) +} + +type clusterImportProcess struct { + addr, log string + stop func() +} + +func startClusterImportCLI(t *testing.T, root, spec string) *clusterImportProcess { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("native daemon signal control") + } + tmp := t.TempDir() + args := []string{"--authority-store", filepath.Join(root, "authority"), "--lifecycle-store", filepath.Join(root, "lifecycle"), "--cluster-spec", spec, "--listen", "127.0.0.1:0", "--expected-slots-per-volume", "1", "--lifecycle-product-loop-interval", "5ms", "--t0-print-ready"} + argsPath := filepath.Join(tmp, "args.json") + data, _ := json.Marshal(args) + if e := os.WriteFile(argsPath, data, 0600); e != nil { + t.Fatal(e) + } + outPath, logPath := filepath.Join(tmp, "out"), filepath.Join(tmp, "log") + out, e := os.Create(outPath) + if e != nil { + t.Fatal(e) + } + log, e := os.Create(logPath) + if e != nil { + t.Fatal(e) + } + cmd := exec.Command(os.Args[0], "-test.run=^TestClusterVolumeCLIHelper$", "-test.v") + cmd.Env = append(os.Environ(), "BLOCKMASTER_IMPORT_ARGS="+argsPath) + cmd.Stdout = out + cmd.Stderr = log + if e = cmd.Start(); e != nil { + t.Fatal(e) + } + done := make(chan error, 1) + go func() { done <- cmd.Wait() }() + stopped := false + p := &clusterImportProcess{log: logPath} + p.stop = func() { + if stopped { + return + } + _ = cmd.Process.Signal(syscall.SIGTERM) + select { + case <-done: + stopped = true + case <-time.After(5 * time.Second): + _ = cmd.Process.Kill() + select { + case <-done: + stopped = true + case <-time.After(5 * time.Second): + t.Error("blockmaster failed to reap") + } + } + out.Close() + log.Close() + } + t.Cleanup(p.stop) + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + b, _ := os.ReadFile(outPath) + for _, line := range strings.Split(string(b), "\n") { + var ready readyLine + if json.Unmarshal([]byte(line), &ready) == nil && ready.Component == "blockmaster" && ready.Phase == "listening" { + p.addr = ready.Addr + return p + } + } + select { + case e := <-done: + stopped = true + b, _ := os.ReadFile(logPath) + t.Fatalf("blockmaster startup failed: %v %s", e, b) + case <-time.After(5 * time.Millisecond): + } + } + b, _ := os.ReadFile(logPath) + t.Fatalf("blockmaster ready timeout: %s", b) + return nil +} +func importedVolumeClients(t *testing.T, p *clusterImportProcess) (control.ObservationServiceClient, control.EvidenceServiceClient, control.LifecycleServiceClient) { + t.Helper() + c, e := grpc.NewClient(p.addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if e != nil { + t.Fatal(e) + } + t.Cleanup(func() { c.Close() }) + return control.NewObservationServiceClient(c), control.NewEvidenceServiceClient(c), control.NewLifecycleServiceClient(c) +} +func reportImportedVolume(t *testing.T, o control.ObservationServiceClient) { + t.Helper() + ctx, c := context.WithTimeout(context.Background(), 3*time.Second) + defer c() + _, e := o.ReportHeartbeat(ctx, &control.HeartbeatReport{ReadsLevel: 1, ServerId: "s2", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, Slots: []*control.HeartbeatSlot{{VolumeId: "v1", ReplicaId: "r2", DataAddr: "10.0.0.2:19080", CtrlAddr: "10.0.0.2:19081"}}}) + if e != nil { + t.Fatal(e) + } +} +func waitImportedAuthority(t *testing.T, p *clusterImportProcess, evidence control.EvidenceServiceClient) { + t.Helper() + ctx, c := context.WithTimeout(context.Background(), 3*time.Second) + defer c() + for { + s, e := evidence.QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: "v1"}) + if e == nil && s.Assigned && s.Epoch == 1 && s.ReplicaId == "r2" { + return + } + select { + case <-ctx.Done(): + log, _ := os.ReadFile(p.log) + t.Fatalf("cluster-spec volume did not publish authority: %v %v log=%s", s, e, log) + case <-time.After(5 * time.Millisecond): + } + } +} +func TestClusterSpecCLIRegistersVolumeBeforePublication(t *testing.T) { + root := t.TempDir() + spec := writeClusterSpecForTest(t) + p := startClusterImportCLI(t, root, spec) + o, e, l := importedVolumeClients(t, p) + reportImportedVolume(t, o) + waitImportedAuthority(t, p, e) + ctx, c := context.WithTimeout(context.Background(), 3*time.Second) + defer c() + same := &control.CreateVolumeRequest{VolumeId: "v1", SizeBytes: 1048576, ReplicationFactor: 1} + got, err := l.CreateVolume(ctx, same) + if err != nil || got.SizeBytes != 1048576 || got.ReplicationFactor != 1 { + t.Fatalf("imported desired shape changed: %v %v", got, err) + } + if _, err = l.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v1", SizeBytes: 2097152, ReplicationFactor: 1}); status.Code(err) != codes.AlreadyExists { + t.Fatalf("import did not preserve exact capacity: %v", err) + } + p.stop() + p2 := startClusterImportCLI(t, root, spec) + o2, e2, _ := importedVolumeClients(t, p2) + reportImportedVolume(t, o2) + waitImportedAuthority(t, p2, e2) +} +func TestClusterSpecCLIMissingSizeExplainsCreateVolumePrerequisite(t *testing.T) { + spec := writeClusterSpecForTest(t) + b, err := os.ReadFile(spec) + if err != nil { + t.Fatal(err) + } + if err = os.WriteFile(spec, []byte(strings.Replace(string(b), " size_bytes: 1048576\n", "", 1)), 0600); err != nil { + t.Fatal(err) + } + root := t.TempDir() + p := startClusterImportCLI(t, root, spec) + o, e, l := importedVolumeClients(t, p) + reportImportedVolume(t, o) + expected := "no lifecycle VolumeRecord for v1; register it (CreateVolume) before publishing" + deadline := time.Now().Add(3 * time.Second) + for { + log, _ := os.ReadFile(p.log) + if strings.Contains(string(log), expected) { + break + } + if time.Now().After(deadline) { + t.Fatalf("missing actionable CreateVolume prerequisite: %s", log) + } + time.Sleep(5 * time.Millisecond) + } + ctx, c := context.WithTimeout(context.Background(), 3*time.Second) + defer c() + before, err := e.QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: "v1"}) + if err != nil || before.Assigned { + t.Fatal(fmt.Sprint("unregistered volume assigned: ", before, err)) + } + if _, err = l.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v1", SizeBytes: 1048576, ReplicationFactor: 1, Protocol: "nvme", FrontendTransport: "tcp", PvcNamespace: "workspaces", PvcName: "claim-v1"}); err != nil { + t.Fatal(err) + } + reportImportedVolume(t, o) + waitImportedAuthority(t, p, e) + // A later complete spec must not replace fields it does not own. + p.stop() + if err = os.WriteFile(spec, b, 0600); err != nil { + t.Fatal(err) + } + p2 := startClusterImportCLI(t, root, spec) + o2, e2, l2 := importedVolumeClients(t, p2) + reportImportedVolume(t, o2) + waitImportedAuthority(t, p2, e2) + // The earlier RPC budget belongs to the first daemon. Give this distinct + // request the same budget after the restart, without extending either RPC. + replayCtx, replayCancel := context.WithTimeout(context.Background(), 3*time.Second) + defer replayCancel() + got, err := l2.CreateVolume(replayCtx, &control.CreateVolumeRequest{VolumeId: "v1", SizeBytes: 1048576, ReplicationFactor: 1, Protocol: "nvme", FrontendTransport: "tcp"}) + if err != nil || got.Protocol != "nvme" || got.FrontendTransport != "tcp" || got.PvcNamespace != "workspaces" || got.PvcName != "claim-v1" { + t.Fatalf("cluster import changed existing protocol/metadata: %v %v", got, err) + } + +} diff --git a/seaweed-block/cmd/blockmaster/external_bind_test.go b/seaweed-block/cmd/blockmaster/external_bind_test.go new file mode 100644 index 0000000000..71c884bdea --- /dev/null +++ b/seaweed-block/cmd/blockmaster/external_bind_test.go @@ -0,0 +1,56 @@ +package main + +import ( + "os" + "strings" + "testing" +) + +// A plaintext control listener binds loopback only: --listen in development +// mode, and the runtime HTTP listener always when its API is enabled. +// --insecure-external-bind is refused with a cure line. +func TestParseFlags_PlaintextControlListenersStayOnLoopback(t *testing.T) { + base := func(extra ...string) []string { return append([]string{"--authority-store", t.TempDir()}, extra...) } + for _, ok := range []string{"127.0.0.1:9333", "localhost:9333", "[::1]:9333", "127.0.0.1:0"} { + if _, err := parseFlags(base("--listen", ok)); err != nil { + t.Fatalf("--listen %s: %v", ok, err) + } + } + for _, bad := range []string{"0.0.0.0:9333", ":9333", "10.0.0.5:9333", "[::]:9333"} { + _, err := parseFlags(base("--listen", bad)) + if err == nil || !strings.Contains(err.Error(), "not a loopback address") || !strings.Contains(err.Error(), "--tls-cert") { + t.Fatalf("--listen %s in development mode: %v, want a refusal naming mutual TLS", bad, err) + } + if _, err := parseFlags(base("--listen", bad, "--insecure-external-bind")); err == nil || !strings.Contains(err.Error(), "no longer accepted") { + t.Fatalf("--listen %s with --insecure-external-bind: %v, want refused", bad, err) + } + } + if _, err := parseFlags(base("--frontend-publication-runtime-listen", "0.0.0.0:9334")); err != nil { + t.Fatalf("runtime listener disabled: its address is not checked: %v", err) + } + _, err := parseFlags(base("--frontend-publication-runtime-http", "--frontend-publication-runtime-listen", "0.0.0.0:9334")) + if err == nil || !strings.Contains(err.Error(), "frontend-publication-runtime-listen") || !strings.Contains(err.Error(), "always stays on loopback") { + t.Fatalf("enabled runtime listener on 0.0.0.0: %v, want refused", err) + } +} + +// No shipped manifest passes the removed flag or binds blockmaster off +// loopback without mutual TLS. +func TestManifests_NoPlaintextExternalBlockmasterBind(t *testing.T) { + for _, p := range []string{"../../charts/seaweed-block/templates/blockmaster.yaml", "../../deploy/k8s/alpha/block-stack.yaml", "../../deploy/k8s/g15b/block-stack.yaml", "../../deploy/k8s/g15d/block-stack.yaml"} { + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + s := string(b) + if strings.Contains(s, "--insecure-external-bind") { + t.Fatalf("%s passes --insecure-external-bind, which blockmaster refuses", p) + } + if strings.Contains(s, "--listen=0.0.0.0") && !strings.Contains(s, "--tls-cert") { + t.Fatalf("%s binds blockmaster to 0.0.0.0 without mutual TLS", p) + } + if strings.Contains(s, "--tls-cert") && !strings.Contains(s, "--audit-log") { + t.Fatalf("%s runs blockmaster with mutual TLS but without --audit-log, which it refuses", p) + } + } +} diff --git a/seaweed-block/cmd/blockmaster/journal_isolation_flags_test.go b/seaweed-block/cmd/blockmaster/journal_isolation_flags_test.go new file mode 100644 index 0000000000..9bcc6c8dca --- /dev/null +++ b/seaweed-block/cmd/blockmaster/journal_isolation_flags_test.go @@ -0,0 +1,28 @@ +package main + +import ( + "strings" + "testing" +) + +// --strict-journal-isolation and --status-listen are off by default; a +// non-loopback --status-listen is refused at startup with a clear error. +func TestParseFlags_JournalIsolationAndStatusListen(t *testing.T) { + f, err := parseFlags([]string{"--authority-store", t.TempDir()}) + if err != nil { + t.Fatal(err) + } + if f.strictJournalIsolation || f.statusListen != "" { + t.Fatalf("defaults: strict=%v status-listen=%q, want off", f.strictJournalIsolation, f.statusListen) + } + f, err = parseFlags([]string{"--authority-store", t.TempDir(), "--strict-journal-isolation", "--status-listen", "127.0.0.1:9335"}) + if err != nil || !f.strictJournalIsolation || f.statusListen != "127.0.0.1:9335" { + t.Fatalf("set: %+v %v", f, err) + } + for _, bad := range []string{"0.0.0.0:9335", ":9335", "192.168.1.10:9335"} { + _, err := parseFlags([]string{"--authority-store", t.TempDir(), "--status-listen", bad}) + if err == nil || !strings.Contains(err.Error(), "must be a loopback address") { + t.Fatalf("--status-listen %s: %v, want a loopback refusal", bad, err) + } + } +} diff --git a/seaweed-block/cmd/blockmaster/launcher_loop_test.go b/seaweed-block/cmd/blockmaster/launcher_loop_test.go new file mode 100644 index 0000000000..534f70c1cf --- /dev/null +++ b/seaweed-block/cmd/blockmaster/launcher_loop_test.go @@ -0,0 +1,369 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/launcher" + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +func TestG15d_BlockmasterLauncherTickWritesBlockvolumeManifest(t *testing.T) { + h, err := master.New(master.Config{ + AuthorityStoreDir: t.TempDir(), + LifecycleStoreDir: t.TempDir(), + Listen: "127.0.0.1:0", + }) + if err != nil { + t.Fatalf("master.New: %v", err) + } + h.Start() + defer func() { _ = h.Close(context.Background()) }() + stores := h.Lifecycle() + if _, err := stores.Volumes.CreateVolume(lifecycle.VolumeSpec{ + VolumeID: "pvc-a", + SizeBytes: 1 << 20, + ReplicationFactor: 1, + }); err != nil { + t.Fatalf("create volume: %v", err) + } + if _, err := stores.Nodes.RegisterNode(lifecycle.NodeRegistration{ + ServerID: "m02", + DataAddr: "10.0.0.2:9201", + CtrlAddr: "10.0.0.2:9101", + Pools: []lifecycle.StoragePool{{ + PoolID: "default", + TotalBytes: 1 << 30, + FreeBytes: 1 << 30, + BlockSize: 4096, + }}, + }); err != nil { + t.Fatalf("register node: %v", err) + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + + outDir := t.TempDir() + if err := runLifecycleLauncherTick(h, flags{ + launcherManifestDir: outDir, + launcherNamespace: "kube-system", + launcherImage: "sw-block:test", + launcherMasterAddr: "blockmaster.kube-system.svc.cluster.local:9333", + launcherDurableRoot: "/var/lib/sw-block", + launcherISCSIPortBase: 3260, + }); err != nil { + t.Fatalf("launcher tick: %v", err) + } + path := filepath.Join(outDir, "sw-blockvolume-pvc-a-r1.yaml") + raw, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read manifest: %v", err) + } + body := string(raw) + for _, want := range []string{ + "kind: Deployment", + "name: sw-blockvolume-pvc-a-r1", + "--master=blockmaster.kube-system.svc.cluster.local:9333", + "--volume-id=pvc-a", + "--replica-id=r1", + "--iscsi-listen=127.0.0.1:3260", + } { + if !strings.Contains(body, want) { + t.Fatalf("manifest missing %q:\n%s", want, body) + } + } + if _, ok := h.Publisher().VolumeAuthorityLine("pvc-a"); ok { + t.Fatal("launcher tick must not mint authority") + } +} + +func TestG15d_BlockmasterLauncherTickCanRenderHostPathState(t *testing.T) { + h, err := master.New(master.Config{ + AuthorityStoreDir: t.TempDir(), + LifecycleStoreDir: t.TempDir(), + Listen: "127.0.0.1:0", + }) + if err != nil { + t.Fatalf("master.New: %v", err) + } + h.Start() + defer func() { _ = h.Close(context.Background()) }() + stores := h.Lifecycle() + if _, err := stores.Volumes.CreateVolume(lifecycle.VolumeSpec{ + VolumeID: "pvc-a", + SizeBytes: 1 << 20, + ReplicationFactor: 1, + }); err != nil { + t.Fatalf("create volume: %v", err) + } + if _, err := stores.Nodes.RegisterNode(lifecycle.NodeRegistration{ + ServerID: "m02", + DataAddr: "10.0.0.2:9201", + CtrlAddr: "10.0.0.2:9101", + Pools: []lifecycle.StoragePool{{ + PoolID: "default", + TotalBytes: 1 << 30, + FreeBytes: 1 << 30, + BlockSize: 4096, + }}, + }); err != nil { + t.Fatalf("register node: %v", err) + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + + outDir := t.TempDir() + if err := runLifecycleLauncherTick(h, flags{ + launcherManifestDir: outDir, + launcherNamespace: "kube-system", + launcherImage: "sw-block:test", + launcherMasterAddr: "blockmaster.kube-system.svc.cluster.local:9333", + launcherDurableRoot: "/var/lib/sw-block", + launcherStateHostPath: "/var/lib/sw-block", + launcherISCSIPortBase: 3260, + }); err != nil { + t.Fatalf("launcher tick: %v", err) + } + raw, err := os.ReadFile(filepath.Join(outDir, "sw-blockvolume-pvc-a-r1.yaml")) + if err != nil { + t.Fatalf("read manifest: %v", err) + } + body := string(raw) + stateSection := yamlStateVolumeSection(t, body) + for _, want := range []string{ + "hostPath:", + "path: /var/lib/sw-block", + "type: DirectoryOrCreate", + } { + if !strings.Contains(stateSection, want) { + t.Fatalf("state volume missing %q:\n%s", want, stateSection) + } + } + if strings.Contains(stateSection, "emptyDir:") { + t.Fatalf("hostPath state volume must not render emptyDir:\n%s", stateSection) + } +} + +func yamlStateVolumeSection(t *testing.T, body string) string { + t.Helper() + lines := strings.Split(body, "\n") + volumesIndent := -1 + stateStart := -1 + stateIndent := -1 + for i, line := range lines { + trimmed := strings.TrimSpace(line) + indent := len(line) - len(strings.TrimLeft(line, " ")) + if volumesIndent < 0 { + if trimmed == "volumes:" { + volumesIndent = indent + } + continue + } + if indent <= volumesIndent && trimmed != "" { + break + } + if trimmed == "- name: state" { + stateStart = i + stateIndent = indent + break + } + } + if stateStart < 0 { + t.Fatalf("state volume section not found:\n%s", body) + } + stateEnd := len(lines) + for i := stateStart + 1; i < len(lines); i++ { + trimmed := strings.TrimSpace(lines[i]) + indent := len(lines[i]) - len(strings.TrimLeft(lines[i], " ")) + if indent == stateIndent && strings.HasPrefix(trimmed, "- name:") { + stateEnd = i + break + } + if indent < stateIndent && trimmed != "" { + stateEnd = i + break + } + } + return strings.Join(lines[stateStart:stateEnd], "\n") +} + +func TestG15d_BlockmasterLauncherTickRendersNVMeManifestFromLifecycleProtocol(t *testing.T) { + h, err := master.New(master.Config{ + AuthorityStoreDir: t.TempDir(), + LifecycleStoreDir: t.TempDir(), + Listen: "127.0.0.1:0", + }) + if err != nil { + t.Fatalf("master.New: %v", err) + } + h.Start() + defer func() { _ = h.Close(context.Background()) }() + stores := h.Lifecycle() + if _, err := stores.Volumes.CreateVolume(lifecycle.VolumeSpec{ + VolumeID: "pvc-a", + SizeBytes: 1 << 20, + ReplicationFactor: 1, + Protocol: "nvme", + }); err != nil { + t.Fatalf("create volume: %v", err) + } + if _, err := stores.Nodes.RegisterNode(lifecycle.NodeRegistration{ + ServerID: "m02", + DataAddr: "10.0.0.2:9201", + CtrlAddr: "10.0.0.2:9101", + Pools: []lifecycle.StoragePool{{ + PoolID: "default", + TotalBytes: 1 << 30, + FreeBytes: 1 << 30, + BlockSize: 4096, + }}, + }); err != nil { + t.Fatalf("register node: %v", err) + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + + outDir := t.TempDir() + if err := runLifecycleLauncherTick(h, flags{ + launcherManifestDir: outDir, + launcherNamespace: "kube-system", + launcherImage: "sw-block:test", + launcherMasterAddr: "blockmaster.kube-system.svc.cluster.local:9333", + launcherDurableRoot: "/var/lib/sw-block", + launcherNVMePortBase: 4420, + }); err != nil { + t.Fatalf("launcher tick: %v", err) + } + raw, err := os.ReadFile(filepath.Join(outDir, "sw-blockvolume-pvc-a-r1.yaml")) + if err != nil { + t.Fatalf("read manifest: %v", err) + } + body := string(raw) + for _, want := range []string{ + "--nvme-listen=127.0.0.1:4420", + "--nvme-subsysnqn=nqn.2026-05.io.seaweedfs:pvc-a", + "--nvme-ns=1", + } { + if !strings.Contains(body, want) { + t.Fatalf("nvme manifest missing %q:\n%s", want, body) + } + } + if strings.Contains(body, "--iscsi-listen=") || strings.Contains(body, "--iscsi-iqn=") { + t.Fatalf("nvme manifest must not render iscsi args:\n%s", body) + } +} + +func TestG15e_BlockmasterLauncherTickRemovesManifestAfterVolumeDelete(t *testing.T) { + h, err := master.New(master.Config{ + AuthorityStoreDir: t.TempDir(), + LifecycleStoreDir: t.TempDir(), + Listen: "127.0.0.1:0", + }) + if err != nil { + t.Fatalf("master.New: %v", err) + } + h.Start() + defer func() { _ = h.Close(context.Background()) }() + stores := h.Lifecycle() + if _, err := stores.Volumes.CreateVolume(lifecycle.VolumeSpec{ + VolumeID: "pvc-a", + SizeBytes: 1 << 20, + ReplicationFactor: 1, + }); err != nil { + t.Fatalf("create volume: %v", err) + } + if _, err := stores.Nodes.RegisterNode(lifecycle.NodeRegistration{ + ServerID: "m02", + DataAddr: "10.0.0.2:9201", + CtrlAddr: "10.0.0.2:9101", + Pools: []lifecycle.StoragePool{{ + PoolID: "default", + TotalBytes: 1 << 30, + FreeBytes: 1 << 30, + BlockSize: 4096, + }}, + }); err != nil { + t.Fatalf("register node: %v", err) + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + outDir := t.TempDir() + f := flags{ + launcherManifestDir: outDir, + launcherNamespace: "kube-system", + launcherImage: "sw-block:test", + launcherMasterAddr: "blockmaster.kube-system.svc.cluster.local:9333", + launcherDurableRoot: "/var/lib/sw-block", + launcherISCSIPortBase: 3260, + } + path := filepath.Join(outDir, "sw-blockvolume-pvc-a-r1.yaml") + if err := runLifecycleLauncherTick(h, f); err != nil { + t.Fatalf("first launcher tick: %v", err) + } + if _, err := os.Stat(path); err != nil { + t.Fatalf("manifest missing before delete: %v", err) + } + if err := stores.Placements.DeletePlacement("pvc-a"); err != nil { + t.Fatalf("delete placement: %v", err) + } + if err := stores.Volumes.DeleteVolume("pvc-a"); err != nil { + t.Fatalf("delete volume: %v", err) + } + if err := runLifecycleLauncherTick(h, f); err != nil { + t.Fatalf("second launcher tick: %v", err) + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("manifest still exists after delete or stat err=%v", err) + } +} + +func TestLifecycleLauncherKubernetesApplyTracksRenderedNamespaces(t *testing.T) { + rendered := []launcher.RenderedManifest{ + { + Name: "sw-blockvolume-pvc-a-r1", + YAML: []byte(`--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-blockvolume-pvc-a-r1 + namespace: default + labels: + app: sw-blockvolume + sw-block.seaweedfs.com/volume: pvc-a + sw-block.seaweedfs.com/replica: r1 +`), + }, + { + Name: "sw-blockvolume-pvc-b-r1", + YAML: []byte(`--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sw-blockvolume-pvc-b-r1 + namespace: apps + labels: + app: sw-blockvolume + sw-block.seaweedfs.com/volume: pvc-b + sw-block.seaweedfs.com/replica: r1 +`), + }, + } + namespaces, byNamespace := renderedManifestsByNamespace(rendered, "kube-system") + wantNamespaces := []string{"kube-system", "default", "apps"} + if !reflect.DeepEqual(namespaces, wantNamespaces) { + t.Fatalf("namespaces=%v want %v", namespaces, wantNamespaces) + } + defaultRendered := byNamespace["default"] + if len(defaultRendered) != 1 || defaultRendered[0].Name != "sw-blockvolume-pvc-a-r1" { + t.Fatalf("default rendered=%+v", defaultRendered) + } +} diff --git a/seaweed-block/cmd/blockmaster/launcher_replication_ack_flag_test.go b/seaweed-block/cmd/blockmaster/launcher_replication_ack_flag_test.go new file mode 100644 index 0000000000..f40bea4b2d --- /dev/null +++ b/seaweed-block/cmd/blockmaster/launcher_replication_ack_flag_test.go @@ -0,0 +1,23 @@ +package main + +import ( + "strings" + "testing" +) + +// The promotion gate reads every frontier rule from +// --launcher-replication-ack, so blockmaster refuses to start on a profile it +// does not know (as blockvolume refuses its own --replication-ack). +func TestBlockmasterRefusesAnUnknownLauncherReplicationAck(t *testing.T) { + for _, bad := range []string{"bogus", "sync_quorum", ""} { + _, err := parseFlags([]string{"--authority-store", t.TempDir(), "--launcher-replication-ack=" + bad}) + if err == nil || !strings.Contains(err.Error(), "--launcher-replication-ack") { + t.Fatalf("--launcher-replication-ack=%q: err=%v; want a refusal naming the flag", bad, err) + } + } + for _, good := range []string{"best-effort", "sync-quorum", "sync-all"} { + if _, err := parseFlags([]string{"--authority-store", t.TempDir(), "--launcher-replication-ack=" + good}); err != nil { + t.Fatalf("--launcher-replication-ack=%q refused: %v", good, err) + } + } +} diff --git a/seaweed-block/cmd/blockmaster/layout_create.go b/seaweed-block/cmd/blockmaster/layout_create.go new file mode 100644 index 0000000000..c3131e2b32 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/layout_create.go @@ -0,0 +1,73 @@ +package main + +import ( + "context" + "fmt" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +// layoutVolumeCreator writes only the master's initial VOLUME and unclaimed +// HEAD. layout.CreateVolume performs exclusive writes and heals a replay +// stopped between them without minting another identity. +func layoutVolumeCreator(cat *chunkstore.BCatalog) func(context.Context, lifecycle.VolumeSpec) error { + return func(ctx context.Context, spec lifecycle.VolumeSpec) error { + if cat == nil { + return fmt.Errorf("master: layout catalog is unavailable") + } + id, err := layout.ParseVolumeID(spec.LayoutID) + if err != nil { + return err + } + _, err = cat.CreateVolume(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}, layout.Geometry{ + SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes, + }) + return err + } +} + +func layoutVolumeReader(cat *chunkstore.BCatalog) func(context.Context, lifecycle.VolumeSpec) (layout.Volume, error) { + return func(ctx context.Context, spec lifecycle.VolumeSpec) (layout.Volume, error) { + id, err := layout.ParseVolumeID(spec.LayoutID) + if err != nil { + return layout.Volume{}, err + } + return cat.ReadVolume(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}) + } +} + +func layoutHeadReader(cat *chunkstore.BCatalog) func(context.Context, lifecycle.VolumeSpec) (layout.Head, error) { + return func(ctx context.Context, spec lifecycle.VolumeSpec) (layout.Head, error) { + id, err := layout.ParseVolumeID(spec.LayoutID) + if err != nil { + return layout.Head{}, err + } + h, found, err := cat.ReadHead(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}) + if err != nil { + return layout.Head{}, err + } + if !found { + return layout.Head{}, layout.ErrHeadAbsent + } + return h, nil + } +} + +func layoutTargetCreator(cat *chunkstore.BCatalog) func(context.Context, lifecycle.VolumeSpec, lifecycle.VolumeSpec, string) error { + return func(ctx context.Context, source, target lifecycle.VolumeSpec, snapshot string) error { + sid, err := layout.ParseVolumeID(source.LayoutID) + if err != nil { + return err + } + tid, err := layout.ParseVolumeID(target.LayoutID) + if err != nil { + return err + } + _, err = cat.Restore(ctx, + chunkstore.VolumeRef{Name: source.VolumeID, ID: sid}, snapshot, + chunkstore.VolumeRef{Name: target.VolumeID, ID: tid}) + return err + } +} diff --git a/seaweed-block/cmd/blockmaster/layout_create_test.go b/seaweed-block/cmd/blockmaster/layout_create_test.go new file mode 100644 index 0000000000..ed16858a5e --- /dev/null +++ b/seaweed-block/cmd/blockmaster/layout_create_test.go @@ -0,0 +1,125 @@ +package main + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +type failFirstHead struct { + chunkstore.Filer + fail bool +} + +func (f *failFirstHead) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, excl bool) error { + if e.Name == "HEAD" && f.fail { + f.fail = false + return errors.New("fixture: lost filer HEAD create") + } + return f.Filer.CreateEntry(ctx, dir, e, excl) +} + +type noCreateBlobs struct{} + +func (noCreateBlobs) Put(context.Context, []byte) (string, error) { + return "", errors.New("unexpected blob upload") +} +func (noCreateBlobs) Get(context.Context, string) ([]byte, error) { + return nil, errors.New("unexpected blob read") +} + +func TestMasterLayoutCreatorWritesUnclaimedHeadAndReplays(t *testing.T) { + ctx := context.Background() + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), noCreateBlobs{}, "/blocks") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + spec := lifecycle.VolumeSpec{VolumeID: "v", LayoutID: id.String(), SizeBytes: 1 << 20, BlockSize: 4096, ChunkBytes: 4 << 20, ReplicationFactor: 1} + create := layoutVolumeCreator(cat) + var firstGen uint64 + for i := 0; i < 2; i++ { + if err := create(ctx, spec); err != nil { + t.Fatalf("create attempt %d: %v", i, err) + } + h, found, err := cat.ReadHead(ctx, chunkstore.VolumeRef{Name: "v", ID: id}) + if err != nil || !found { + t.Fatalf("read HEAD after attempt %d: found=%t err=%v", i, found, err) + } + if i == 0 { + firstGen = h.Gen + } else if h.Gen != firstGen { + t.Fatalf("replay changed HEAD generation %d -> %d", firstGen, h.Gen) + } + } + st, err := cat.Store(chunkstore.VolumeRef{Name: "v", ID: id}) + if err != nil { + t.Fatal(err) + } + v, found, err := st.ReadVolumeRecord(ctx) + if err != nil || !found || v.Geometry != (layout.Geometry{SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes}) { + t.Fatalf("VOLUME=%+v found=%t err=%v", v, found, err) + } + h, found, err := st.ReadHead(ctx) + if err != nil || !found || h.Epoch != 0 || h.Holder != "" || h.ClaimID != "" || h.Gen == 0 { + t.Fatalf("unclaimed HEAD=%+v found=%t err=%v", h, found, err) + } +} + +func TestMasterLayoutCreatorHealsCrashBetweenVolumeAndHead(t *testing.T) { + ctx := context.Background() + filer := &failFirstHead{Filer: chunkstore.NewMemFiler(), fail: true} + cat, err := chunkstore.NewBCatalog(filer, noCreateBlobs{}, "/blocks") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v", ID: id} + spec := lifecycle.VolumeSpec{VolumeID: ref.Name, LayoutID: id.String(), SizeBytes: 1 << 20, BlockSize: 4096, ChunkBytes: 4 << 20, ReplicationFactor: 1} + create := layoutVolumeCreator(cat) + if err := create(ctx, spec); err == nil { + t.Fatal("first HEAD create did not fail") + } + st, err := cat.Store(ref) + if err != nil { + t.Fatal(err) + } + if _, found, err := st.ReadVolumeRecord(ctx); err != nil || !found { + t.Fatalf("VOLUME after interrupted create: found=%t err=%v", found, err) + } + if _, found, err := st.ReadHead(ctx); err != nil || found { + t.Fatalf("HEAD after interrupted create: found=%t err=%v", found, err) + } + if err := create(ctx, spec); err != nil { + t.Fatalf("retry did not complete HEAD: %v", err) + } + if h, found, err := st.ReadHead(ctx); err != nil || !found || h.Epoch != 0 { + t.Fatalf("healed HEAD=%+v found=%t err=%v", h, found, err) + } +} + +func TestMasterLayoutHeadReaderRefusesAbsentHead(t *testing.T) { + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), noCreateBlobs{}, "/blocks") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + spec := lifecycle.VolumeSpec{VolumeID: "source", LayoutID: id.String()} + if _, err := layoutHeadReader(cat)(context.Background(), spec); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("absent source HEAD: %v; want ErrHeadAbsent", err) + } +} diff --git a/seaweed-block/cmd/blockmaster/log_level_test.go b/seaweed-block/cmd/blockmaster/log_level_test.go new file mode 100644 index 0000000000..772c954a29 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/log_level_test.go @@ -0,0 +1,15 @@ +package main + +import "testing" + +func TestLogLevelFlag(t *testing.T) { + for _, level := range []string{"info", "debug"} { + f, err := parseFlags([]string{"--version", "--log-level=" + level}) + if err != nil || f.logLevel != level { + t.Fatalf("%s: flags=%+v error=%v", level, f, err) + } + } + if _, err := parseFlags([]string{"--version", "--log-level=quiet"}); err == nil { + t.Fatal("invalid log level accepted") + } +} diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go new file mode 100644 index 0000000000..9a6f50eb97 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/main.go @@ -0,0 +1,617 @@ +// Command blockmaster is the block master daemon — the product +// host for authority components + master-volume control RPC. +package main + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "os" + "os/signal" + "syscall" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/launcher" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "github.com/seaweedfs/seaweed-block/internal/buildinfo" + "github.com/seaweedfs/seaweed-block/internal/logging" +) + +type flags struct { + logLevel string + insecureExternalBind bool + authorityStore string + lifecycleStore string + lifecyclePlacementSeed string + clusterSpec string + listen string + topology string + expectedSlotsPerVol int + freshnessWindow time.Duration + pendingGrace time.Duration + lifecycleLoop time.Duration + launcherLoop time.Duration + launcherManifestDir string + launcherNamespace string + launcherImage string + launcherMasterAddr string + launcherDurableRoot string + launcherDurableImpl string + launcherWALMultiBlockRecords bool + launcherWALRecoveryTestDisableFlusher bool + launcherStateHostPath string + launcherReplicationAck string + launcherISCSIPortBase int + launcherNVMePortBase int + launcherNVMeMaxH2CDataLength uint + launcherPVCOwnerRef bool + launcherStatus bool + launcherKubernetesApply bool + launcherExternalISCSI bool + launcherExternalNVMe bool + launcherExternalStatus bool + launcherCHAPSecretName string + launcherMasterTLSSecretPrefix string + launcherCHAPUserKey string + launcherCHAPSecretKey string + failbackRuntimeRPC bool + workspaceMaxClockSkew time.Duration + workspaceRPC bool + chunkFiler string + chunkPath string + chunkCollection string + chunkReplication string + frontendPublicationRuntimeHTTP bool + frontendPublicationRuntimeListen string + strictJournalIsolation bool + statusListen string + version bool + // printReadyLine: test-only flag that emits a single + // structured JSON line to stdout after the gRPC listener is + // bound, so L2 subprocess tests can parse the ready event. + // Not operator-facing; documented in the T0 smoke scenario. + printReadyLine bool + auth authFlags +} + +// errRemovedInV1 refuses a flag that v1 removed, at start: a unit or script +// still passing it fails with the reason and what replaces it, rather than +// starting with the setting silently ignored. +var errRemovedInV1 = errors.New("blockmaster: flag removed in v1") + +func parseFlags(args []string) (flags, error) { + var f flags + fs := flag.NewFlagSet("blockmaster", flag.ContinueOnError) + fs.StringVar(&f.logLevel, "log-level", "info", "log verbosity: info or debug; timestamps are UTC with microseconds") + removedHeadBase := false + fs.Func("workspace-head-base-url", "removed in v1, refused at start: blockmaster reads HEAD through the layout catalog (--chunk-filer, --chunk-path)", func(string) error { + removedHeadBase = true + return nil + }) + fs.StringVar(&f.authorityStore, "authority-store", "", "durable authority store directory (required)") + fs.StringVar(&f.lifecycleStore, "lifecycle-store", "", "optional G9D product lifecycle registration store directory (desired volumes, node inventory, placement intents); read-only with respect to assignment publication") + fs.StringVar(&f.lifecyclePlacementSeed, "lifecycle-placement-seed", "", "placement-only seed JSON; lifecycle volumes must already be registered (CreateVolume)") + fs.StringVar(&f.clusterSpec, "cluster-spec", "", "cluster spec YAML; positive size_bytes imports desired volumes before topology/placement publication") + fs.StringVar(&f.listen, "listen", "127.0.0.1:0", "gRPC listen address (e.g. 127.0.0.1:9180); non-loopback requires mutual TLS (--tls-cert, --tls-key, --tls-client-ca, --role-file)") + fs.StringVar(&f.auth.tlsCert, "tls-cert", "", "blockmaster's TLS certificate (PEM): with --tls-key, --tls-client-ca and --role-file, every gRPC call needs mutual TLS") + fs.StringVar(&f.auth.tlsKey, "tls-key", "", "the key of --tls-cert (PEM)") + fs.StringVar(&f.auth.tlsClientCA, "tls-client-ca", "", "CA (PEM) every client certificate must verify against") + fs.StringVar(&f.auth.auditLog, "audit-log", "", "append-only audit log (JSON lines): every operator and admin call, refused node calls, role-file reloads") + fs.StringVar(&f.auth.roleFile, "role-file", "", "role file: lines 'sha256: '; SIGHUP reloads it") + fs.BoolVar(&f.insecureExternalBind, "insecure-external-bind", false, "removed: refused at start (a non-loopback --listen needs mutual TLS; the runtime HTTP listener stays on loopback)") + fs.StringVar(&f.topology, "topology", "", "path to accepted-topology YAML (required for assignment to mint)") + fs.IntVar(&f.expectedSlotsPerVol, "expected-slots-per-volume", 3, "RF/expected slot count per volume; the controller rejects observation snapshots whose slot count differs (default 3, set to 2 for 2-node smoke clusters)") + fs.DurationVar(&f.freshnessWindow, "freshness-window", 30*time.Second, "observation freshness window before a server's heartbeat expires") + fs.DurationVar(&f.pendingGrace, "pending-grace", 1*time.Second, "bootstrap/missing-observation grace before supportability reports unsupported") + fs.DurationVar(&f.lifecycleLoop, "lifecycle-product-loop-interval", 0, "optional G9G product-loop interval; disabled when 0") + fs.DurationVar(&f.launcherLoop, "launcher-loop-interval", 0, "optional G15d launcher planning/render loop interval; disabled when 0") + fs.StringVar(&f.launcherManifestDir, "launcher-manifest-dir", "", "optional G15d output directory for rendered blockvolume workload manifests") + fs.StringVar(&f.launcherNamespace, "launcher-namespace", "kube-system", "G15d rendered blockvolume manifest namespace") + fs.StringVar(&f.launcherImage, "launcher-image", "sw-block:local", "G15d rendered blockvolume container image") + fs.StringVar(&f.launcherMasterAddr, "launcher-master-addr", "", "G15d master address used in rendered blockvolume args; defaults to listener address after bind") + fs.StringVar(&f.launcherDurableRoot, "launcher-durable-root", "/var/lib/sw-block", "G15d rendered blockvolume durable root base") + fs.StringVar(&f.launcherDurableImpl, "launcher-durable-impl", "walstore", "G15d rendered blockvolume durable implementation: walstore (the only one; the removed experimental engines are refused)") + fs.BoolVar(&f.launcherWALMultiBlockRecords, "launcher-durable-wal-multiblock-records", false, "G15d render opt-in for experimental walstore multi-block WAL records; default false") + fs.BoolVar(&f.launcherWALRecoveryTestDisableFlusher, "launcher-durable-wal-recovery-test-disable-flusher", false, "test-only G15d render opt-in for blockvolume --durable-wal-recovery-test-disable-flusher; default false") + fs.StringVar(&f.launcherStateHostPath, "launcher-state-hostpath", "", "optional hostPath base mounted at the blockvolume durable root; empty keeps generated blockvolume state on throwaway emptyDir") + fs.StringVar(&f.launcherReplicationAck, "launcher-replication-ack", "best-effort", "G15d rendered blockvolume replication ACK profile: best-effort, sync-quorum, or sync-all") + fs.IntVar(&f.launcherISCSIPortBase, "launcher-iscsi-port-base", 3260, "G15d iSCSI port base for generated blockvolume workloads") + fs.IntVar(&f.launcherNVMePortBase, "launcher-nvme-port-base", 4420, "G15d NVMe/TCP port base for generated blockvolume workloads") + fs.UintVar(&f.launcherNVMeMaxH2CDataLength, "launcher-nvme-max-h2c-data-length", 0, "G15d NVMe/TCP MaxH2CDataLength passed to generated blockvolume workloads. 0 preserves target default") + fs.BoolVar(&f.launcherPVCOwnerRef, "launcher-pvc-owner-ref", false, "render generated blockvolume Deployments in the source PVC namespace with a PVC ownerReference; disabled by default for alpha harness compatibility") + fs.BoolVar(&f.launcherStatus, "launcher-status", false, "render loopback-only blockvolume status endpoints in generated workload manifests; intended for TestOps/diagnostics") + fs.BoolVar(&f.launcherKubernetesApply, "launcher-kubernetes-apply", false, "apply/delete generated blockvolume Deployments through the in-cluster Kubernetes API; scoped to app=sw-blockvolume and generated volume/replica labels") + fs.BoolVar(&f.launcherExternalISCSI, "launcher-external-iscsi", false, "render generated iSCSI frontends on node addresses instead of loopback; requires --launcher-iscsi-chap-secret-name") + fs.BoolVar(&f.launcherExternalNVMe, "launcher-external-nvme", false, "render generated NVMe/TCP frontends on node addresses instead of loopback; unauthenticated and intended only for explicit Kubernetes NVMe/TCP gates") + fs.BoolVar(&f.launcherExternalStatus, "launcher-external-status", false, "render blockvolume status endpoints on node addresses instead of loopback; intended for explicit Kubernetes node-loss gates") + fs.StringVar(&f.launcherMasterTLSSecretPrefix, "launcher-master-tls-secret-prefix", "", "generated blockvolume Deployments dial blockmaster with mutual TLS from the Secret - (keys tls.crt, tls.key, ca.crt); needs blockmaster's own mutual TLS") + fs.StringVar(&f.launcherCHAPSecretName, "launcher-iscsi-chap-secret-name", "", "optional Kubernetes Secret name used by generated blockvolume Deployments for target-side iSCSI CHAP") + fs.StringVar(&f.launcherCHAPUserKey, "launcher-iscsi-chap-username-key", "chapUsername", "Kubernetes Secret key for generated blockvolume iSCSI CHAP username") + fs.StringVar(&f.launcherCHAPSecretKey, "launcher-iscsi-chap-secret-key", "chapSecret", "Kubernetes Secret key for generated blockvolume iSCSI CHAP secret") + fs.BoolVar(&f.failbackRuntimeRPC, "failback-runtime-rpc", false, "enable disabled-by-default authority failback RPC; requires expected-current and terminal evidence") + fs.DurationVar(&f.workspaceMaxClockSkew, "workspace-max-clock-skew", 20*time.Second, "maximum workspace clock skew; host lease shortens by half, forced moves wait the full bound") + fs.BoolVar(&f.workspaceRPC, "workspace-rpc", false, "enable RF1 workspace lease/revocation/move RPCs") + chunkstore.RegisterSWFSFlags(fs, &f.chunkFiler, &f.chunkPath, &f.chunkCollection, &f.chunkReplication) + fs.BoolVar(&f.frontendPublicationRuntimeHTTP, "frontend-publication-runtime-http", false, "enable disabled-by-default frontend publication HTTP runtime; confirms post-failback authority publication only") + fs.StringVar(&f.frontendPublicationRuntimeListen, "frontend-publication-runtime-listen", "127.0.0.1:9334", "HTTP listen address for --frontend-publication-runtime-http") + fs.BoolVar(&f.strictJournalIsolation, "strict-journal-isolation", false, "refuse new work on nodes whose durable root shares the authority store's file system (one journal): their heartbeats are refused until they serve a volume, and no placement or move targets them; off = alarm only") + fs.StringVar(&f.statusListen, "status-listen", "", "loopback HTTP address for the read-only GET /status/workspace-lease endpoint; empty = off") + fs.BoolVar(&f.version, "version", false, "print build provenance and exit") + fs.DurationVar(&f.auth.connectionAge, "tls-connection-age-test-only", link.MasterConnectionAge, "internal test-only: how long a client connection lives before a reconnect (a fresh handshake)") + fs.BoolVar(&f.printReadyLine, "t0-print-ready", false, "internal test-only: emit one structured JSON line on stdout after listener bound") + fs.SetOutput(os.Stderr) + if err := fs.Parse(args); err != nil { + return flags{}, err + } + if err := logging.ValidateLevel(f.logLevel); err != nil { + return flags{}, err + } + if removedHeadBase { + return flags{}, fmt.Errorf("%w: --workspace-head-base-url; blockmaster reads HEAD through the layout catalog: set --chunk-filer (and --chunk-path) instead", errRemovedInV1) + } + if f.version { + return f, nil + } + if f.launcherNVMeMaxH2CDataLength > uint(^uint32(0)) { + return flags{}, fmt.Errorf("--launcher-nvme-max-h2c-data-length=%d exceeds uint32", f.launcherNVMeMaxH2CDataLength) + } + if err := nvme.ValidateMaxH2CDataLength(uint32(f.launcherNVMeMaxH2CDataLength)); err != nil { + return flags{}, fmt.Errorf("--launcher-nvme-max-h2c-data-length=%d invalid: %w", f.launcherNVMeMaxH2CDataLength, err) + } + if f.workspaceMaxClockSkew <= 0 || f.workspaceMaxClockSkew >= 60*time.Second { + return flags{}, fmt.Errorf("--workspace-max-clock-skew must be positive and less than 60s") + } + fenceExitBudget := durable.ChunkFenceWatchInterval + volume.WorkspaceDrainTimeout + if f.workspaceMaxClockSkew/2 <= fenceExitBudget { + return flags{}, fmt.Errorf("--workspace-max-clock-skew=%s gives half-skew=%s, which must exceed configured fence-exit budget=%s (watch cadence=%s + drain timeout=%s), assuming normal scheduling; increase --workspace-max-clock-skew above %s", f.workspaceMaxClockSkew, f.workspaceMaxClockSkew/2, fenceExitBudget, durable.ChunkFenceWatchInterval, volume.WorkspaceDrainTimeout, 2*fenceExitBudget) + } + if f.authorityStore == "" { + return flags{}, fmt.Errorf("--authority-store is required") + } + // The promotion gate reads every frontier rule from this profile: an + // unknown one is refused here, as blockvolume refuses its own. + switch f.launcherReplicationAck { + case "best-effort", "sync-quorum", "sync-all": + default: + return flags{}, fmt.Errorf("--launcher-replication-ack=%q invalid; want best-effort, sync-quorum, or sync-all", f.launcherReplicationAck) + } + if err := master.ValidateStatusListen(f.statusListen); err != nil { + return flags{}, err + } + if f.insecureExternalBind { + return flags{}, fmt.Errorf("--insecure-external-bind is no longer accepted: a plaintext control listener stays on loopback; to listen on the node network start blockmaster with mutual TLS (--tls-cert, --tls-key, --tls-client-ca, --role-file) and drop the flag") + } + if err := f.auth.validate(); err != nil { + return flags{}, err + } + if !f.auth.enabled() { + if err := master.ValidateControlListen("listen", f.listen); err != nil { + return flags{}, fmt.Errorf("%w; start blockmaster with mutual TLS (--tls-cert, --tls-key, --tls-client-ca, --role-file) to listen on the node network", err) + } + } + if f.frontendPublicationRuntimeHTTP { + if err := master.ValidateControlListen("frontend-publication-runtime-listen", f.frontendPublicationRuntimeListen); err != nil { + return flags{}, fmt.Errorf("%w; the runtime HTTP API is unauthenticated and always stays on loopback", err) + } + } + if f.launcherMasterTLSSecretPrefix != "" && !f.auth.enabled() { + return flags{}, fmt.Errorf("--launcher-master-tls-secret-prefix needs blockmaster's own mutual TLS (--tls-cert, --tls-key, --tls-client-ca, --role-file)") + } + if f.launcherMasterTLSSecretPrefix != "" && f.launcherExternalStatus { + return flags{}, fmt.Errorf("--launcher-external-status cannot be combined with --launcher-master-tls-secret-prefix: an authenticated volume's status listener stays on loopback") + } + if f.launcherExternalISCSI && f.launcherCHAPSecretName == "" { + return flags{}, fmt.Errorf("cannot enable --launcher-external-iscsi without --launcher-iscsi-chap-secret-name") + } + return f, nil +} + +func main() { + f, err := parseFlags(os.Args[1:]) + if err != nil { + fmt.Fprintln(os.Stderr, "blockmaster:", err) + os.Exit(2) + } + if f.version { + fmt.Println(buildinfo.Version("blockmaster")) + return + } + if err := logging.Configure(f.logLevel); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + os.Exit(run(f)) +} + +type readyLine struct { + Component string `json:"component"` + Phase string `json:"phase"` + Addr string `json:"addr"` +} + +func run(f flags) int { + topo, clusterImport, err := loadProductInputs(f) + if err != nil { + fmt.Fprintln(os.Stderr, "blockmaster:", err) + return 2 + } + if err := requireProductLoop(f.lifecycleLoop, f.expectedSlotsPerVol, clusterImport); err != nil { + fmt.Fprintln(os.Stderr, "blockmaster:", err) + return 2 + } + if len(topo.Volumes) == 0 && len(clusterImport.Nodes) == 0 { + // Without a topology the observation host classifies every + // volume UnknownReplicaClaim; controller can never mint. + // That is a valid "empty cluster" startup state and not an + // error, but operators should know — log a prominent line. + fmt.Fprintln(os.Stderr, "blockmaster: WARNING: --topology not supplied or empty; controller will not mint assignments until topology is provided") + } else if len(topo.Volumes) == 0 { + fmt.Fprintln(os.Stderr, "blockmaster: dynamic lifecycle topology enabled by cluster-spec node inventory; assignments will be derived from verified placement intents") + } + cfg := master.Config{ + AuthorityStoreDir: f.authorityStore, + LifecycleStoreDir: f.lifecycleStore, + Listen: f.listen, + Topology: topo, + Freshness: authority.FreshnessConfig{FreshnessWindow: f.freshnessWindow, PendingGrace: f.pendingGrace}, + ControllerConfig: authority.TopologyControllerConfig{ExpectedSlotsPerVolume: f.expectedSlotsPerVol}, + WorkspaceMaxClockSkew: f.workspaceMaxClockSkew, + FailbackRuntimeRPC: f.failbackRuntimeRPC, + LifecycleProductLoop: f.lifecycleLoop > 0, + FrontendPublicationRuntimeHTTP: f.frontendPublicationRuntimeHTTP, + FrontendPublicationRuntimeListen: f.frontendPublicationRuntimeListen, + StrictJournalIsolation: f.strictJournalIsolation, + StatusListen: f.statusListen, + } + authn, serverOpts, err := f.auth.build() + if err != nil { + fmt.Fprintln(os.Stderr, "blockmaster:", err) + return 1 + } + cfg.Auth, cfg.ServerOptions = authn, serverOpts + // The layout catalog is the master's one HEAD source (create, restore and + // the workspace reader all read through it). + var layoutCat *chunkstore.BCatalog + if f.workspaceRPC { + cat, client, err := chunkstore.DialBCatalog(context.Background(), chunkstore.SWFSConfig{ + FilerGRPC: f.chunkFiler, Collection: f.chunkCollection, + Replication: f.chunkReplication, AssignPath: f.chunkPath, + }) + if err != nil { + fmt.Fprintln(os.Stderr, "blockmaster: layout filer:", err) + return 1 + } + defer client.Close() + cfg.LayoutCreateVolume = layoutVolumeCreator(cat) + cfg.LayoutReadVolume = layoutVolumeReader(cat) + cfg.LayoutReadHead = layoutHeadReader(cat) + cfg.LayoutCreateTarget = layoutTargetCreator(cat) + layoutCat = cat + } + if authn != nil { + if days, until, err := certDaysLeft(f.auth.tlsCert, f.auth.tlsKey, time.Now()); err == nil { + fmt.Fprintln(os.Stderr, fmt.Sprintf("blockmaster: mutual TLS on; role file %s; own certificate expires %s (%d days)", f.auth.roleFile, until.UTC().Format(time.RFC3339), days)) + } + } else { + warnUnauthenticated(f.listen) + } + // New starts no loops: bind h before Start permits any HEAD request. + var h *master.Host + if f.workspaceRPC { + reader, err := master.NewLayoutWorkspaceHEADReader(layoutCat, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) { + return h.WorkspaceLayoutVolume(ctx, name) + }) + if err != nil { + fmt.Fprintln(os.Stderr, "blockmaster:", err) + return 1 + } + cfg.WorkspaceRPC = true + cfg.WorkspaceHeadReader = reader + } + h, err = master.New(cfg) + if err != nil { + fmt.Fprintln(os.Stderr, "blockmaster:", err) + return 1 + } + // Every promotion decides on the probe round's answers: each candidate + // answers a fresh round over its authenticated node stream. + h.SetPromotionEvidenceProvider(h.NewRoundPromotionEvidenceProvider(f.launcherReplicationAck, nil)) + if len(clusterImport.Volumes) > 0 { + if err := importLifecycleVolumes(h, clusterImport.Volumes); err != nil { + fmt.Fprintln(os.Stderr, "blockmaster:", err) + _ = h.Close(context.Background()) + return 1 + } + } + if len(clusterImport.Nodes) > 0 { + if err := importLifecycleNodeInventory(h, clusterImport.Nodes); err != nil { + fmt.Fprintln(os.Stderr, "blockmaster:", err) + _ = h.Close(context.Background()) + return 1 + } + } + if len(clusterImport.Placements) > 0 { + if err := importLifecyclePlacementIntents(h, clusterImport.Placements); err != nil { + fmt.Fprintln(os.Stderr, "blockmaster:", err) + _ = h.Close(context.Background()) + return 1 + } + } + if f.lifecyclePlacementSeed != "" { + if err := importLifecyclePlacementSeed(h, f.lifecyclePlacementSeed); err != nil { + fmt.Fprintln(os.Stderr, "blockmaster:", err) + _ = h.Close(context.Background()) + return 1 + } + } + + if f.printReadyLine { + _ = json.NewEncoder(os.Stdout).Encode(readyLine{ + Component: "blockmaster", + Phase: "listening", + Addr: h.Addr(), + }) + } + + h.Start() + if authn != nil { + reloadRolesOnSIGHUP(authn, f.auth.roleFile) + } + if f.lifecycleLoop > 0 { + go runLifecycleProductLoop(h, f.lifecycleLoop) + } + if f.launcherLoop > 0 { + go runLifecycleLauncherLoop(h, f, f.launcherLoop) + } + + sig := make(chan os.Signal, 1) + signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) + <-sig + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := h.Close(ctx); err != nil { + fmt.Fprintln(os.Stderr, "blockmaster: close:", err) + return 1 + } + return 0 +} + +func loadProductInputs(f flags) (authority.AcceptedTopology, clusterSpecImport, error) { + if f.clusterSpec == "" { + topo, err := loadTopology(f.topology) + return topo, clusterSpecImport{}, err + } + if f.topology != "" { + return authority.AcceptedTopology{}, clusterSpecImport{}, fmt.Errorf("--cluster-spec and --topology are mutually exclusive in this slice") + } + imports, err := loadClusterSpec(f.clusterSpec) + if err != nil { + return authority.AcceptedTopology{}, clusterSpecImport{}, err + } + topo, err := toAcceptedTopology(&imports.Topology) + if err != nil { + return authority.AcceptedTopology{}, clusterSpecImport{}, err + } + return topo, imports, nil +} + +// Import only the geometry/RF that the cluster specification owns. Preserve +// existing protocol and Kubernetes metadata; the store rejects geometry drift. +func importLifecycleVolumes(h *master.Host, volumes []lifecycle.VolumeSpec) error { + stores := h.Lifecycle() + if stores == nil { + return fmt.Errorf("cluster volume import requires --lifecycle-store") + } + for _, spec := range volumes { + if old, ok := stores.Volumes.GetVolume(spec.VolumeID); ok { + merged := old.Spec + merged.SizeBytes = spec.SizeBytes + merged.ReplicationFactor = spec.ReplicationFactor + spec = merged + } + imported, err := h.ImportLifecycleVolume(spec) + if err != nil { + return fmt.Errorf("register lifecycle volume %s: %w", spec.VolumeID, err) + } + if !imported { + // A chunk volume delete reserved this id: it is never created + // again, also when the cluster spec still lists it. + fmt.Fprintf(os.Stderr, "blockmaster: cluster spec volume %s not imported: its id is reserved by a volume delete\n", spec.VolumeID) + } + } + return nil +} + +func importLifecycleNodeInventory(h *master.Host, nodes []lifecycle.NodeRegistration) error { + stores := h.Lifecycle() + if stores == nil { + return fmt.Errorf("lifecycle node import requires --lifecycle-store") + } + for _, node := range nodes { + if _, err := stores.Nodes.RegisterNode(node); err != nil { + return fmt.Errorf("register lifecycle node %s: %w", node.ServerID, err) + } + } + return nil +} + +func importLifecyclePlacementSeed(h *master.Host, path string) error { + stores := h.Lifecycle() + if stores == nil { + return fmt.Errorf("--lifecycle-placement-seed requires --lifecycle-store") + } + raw, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("read lifecycle placement seed %q: %w", path, err) + } + var intents []lifecycle.PlacementIntent + if err := json.Unmarshal(raw, &intents); err != nil { + return fmt.Errorf("parse lifecycle placement seed %q: %w", path, err) + } + return importLifecyclePlacementIntents(h, intents) +} + +func importLifecyclePlacementIntents(h *master.Host, intents []lifecycle.PlacementIntent) error { + stores := h.Lifecycle() + if stores == nil { + return fmt.Errorf("lifecycle placement import requires --lifecycle-store") + } + for _, intent := range intents { + if stores.Deletions.Reserved(intent.VolumeID) { + continue // never placed again (see importLifecycleVolumes) + } + plan := lifecycle.PlacementPlan{ + VolumeID: intent.VolumeID, + DesiredRF: intent.DesiredRF, + Candidates: make([]lifecycle.PlacementCandidate, 0, len(intent.Slots)), + } + for _, slot := range intent.Slots { + plan.Candidates = append(plan.Candidates, lifecycle.PlacementCandidate{ + VolumeID: intent.VolumeID, + ServerID: slot.ServerID, + PoolID: slot.PoolID, + ReplicaID: slot.ReplicaID, + Source: slot.Source, + }) + } + if _, err := stores.Placements.ApplyPlan(plan); err != nil { + return fmt.Errorf("apply lifecycle placement seed %s: %w", intent.VolumeID, err) + } + } + return nil +} + +func runLifecycleProductLoop(h *master.Host, interval time.Duration) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + if _, err := h.RunLifecycleProductTick(); err != nil { + fmt.Fprintln(os.Stderr, "blockmaster: lifecycle product loop:", err) + } + <-ticker.C + } +} + +func runLifecycleLauncherLoop(h *master.Host, f flags, interval time.Duration) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + if err := runLifecycleLauncherTick(h, f); err != nil { + fmt.Fprintln(os.Stderr, "blockmaster: lifecycle launcher loop:", err) + } + <-ticker.C + } +} + +func runLifecycleLauncherTick(h *master.Host, f flags) error { + result, err := h.RunLifecycleWorkloadPlanTick(lifecycle.WorkloadPlanConfig{ + ISCSIPortBase: f.launcherISCSIPortBase, + NVMePortBase: f.launcherNVMePortBase, + }) + if err != nil { + return err + } + if f.launcherManifestDir == "" && !f.launcherKubernetesApply { + return nil + } + masterAddr := f.launcherMasterAddr + if masterAddr == "" { + masterAddr = h.Addr() + } + var rendered []launcher.RenderedManifest + for _, plan := range result.Plans { + manifests, err := launcher.RenderBlockVolumeDeployments(plan, launcher.K8sRenderConfig{ + Namespace: f.launcherNamespace, + Image: f.launcherImage, + MasterAddr: masterAddr, + DurableRootBase: f.launcherDurableRoot, + DurableImpl: f.launcherDurableImpl, + WALMultiBlockRecords: f.launcherWALMultiBlockRecords, + WALRecoveryTestDisableFlusher: f.launcherWALRecoveryTestDisableFlusher, + StateHostPathBase: f.launcherStateHostPath, + ReplicationAck: f.launcherReplicationAck, + OwnerReferenceToPVC: f.launcherPVCOwnerRef, + EnableStatus: f.launcherStatus, + ExternalISCSI: f.launcherExternalISCSI, + ExternalNVMe: f.launcherExternalNVMe, + ExternalStatus: f.launcherExternalStatus, + MasterTLSSecretPrefix: f.launcherMasterTLSSecretPrefix, + NVMeMaxH2CDataLength: uint32(f.launcherNVMeMaxH2CDataLength), + ISCSICHAP: launcher.CHAPSecretRef{ + Name: f.launcherCHAPSecretName, + UsernameKey: f.launcherCHAPUserKey, + SecretKey: f.launcherCHAPSecretKey, + }, + }) + if err != nil { + return err + } + rendered = append(rendered, manifests...) + } + if f.launcherManifestDir != "" { + if err := launcher.SyncRenderedManifests(f.launcherManifestDir, rendered); err != nil { + return err + } + } + if f.launcherKubernetesApply { + client, err := launcher.NewInClusterDeploymentClient() + if err != nil { + return err + } + namespaces, renderedByNamespace := renderedManifestsByNamespace(rendered, f.launcherNamespace) + for _, namespace := range namespaces { + desired := renderedByNamespace[namespace] + existing, err := client.ListBlockVolumeDeployments(context.Background(), namespace) + if err != nil { + return err + } + reconcileResult, err := launcher.ReconcileBlockVolumeDeployments(context.Background(), launcher.ReconcileDeploymentsInput{ + Namespace: namespace, + Desired: desired, + Existing: existing, + Client: client, + }) + if err != nil { + return err + } + fmt.Fprintf(os.Stderr, "blockmaster: launcher kubernetes reconcile namespace=%s applied=%d deleted=%d skipped=%d\n", namespace, reconcileResult.Applied, reconcileResult.Deleted, reconcileResult.Skipped) + } + } + return nil +} + +func renderedManifestsByNamespace(rendered []launcher.RenderedManifest, fallback string) ([]string, map[string][]launcher.RenderedManifest) { + seen := map[string]bool{} + var out []string + byNamespace := map[string][]launcher.RenderedManifest{} + add := func(namespace string) { + if namespace == "" { + namespace = fallback + } + if namespace == "" || seen[namespace] { + return + } + seen[namespace] = true + out = append(out, namespace) + } + add(fallback) + for _, manifest := range rendered { + identity, err := launcher.DecodeRenderedDeploymentIdentity(manifest) + if err != nil { + continue + } + add(identity.Namespace) + byNamespace[identity.Namespace] = append(byNamespace[identity.Namespace], manifest) + } + return out, byNamespace +} diff --git a/seaweed-block/cmd/blockmaster/main_test.go b/seaweed-block/cmd/blockmaster/main_test.go new file mode 100644 index 0000000000..f7e7b0e820 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/main_test.go @@ -0,0 +1,269 @@ +package main + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/host/master" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +func TestParseFlags_LifecycleStoreOptional(t *testing.T) { + f, err := parseFlags([]string{ + "--authority-store", "authority-dir", + "--lifecycle-store", "lifecycle-dir", + }) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if f.lifecycleStore != "lifecycle-dir" { + t.Fatalf("lifecycleStore=%q want lifecycle-dir", f.lifecycleStore) + } +} + +func TestParseFlags_VersionDoesNotRequireStores(t *testing.T) { + f, err := parseFlags([]string{"--version"}) + if err != nil { + t.Fatalf("parseFlags --version: %v", err) + } + if !f.version { + t.Fatal("version flag not set") + } +} + +func TestParseFlags_LifecyclePlacementSeedOptional(t *testing.T) { + f, err := parseFlags([]string{ + "--authority-store", "authority-dir", + "--lifecycle-store", "lifecycle-dir", + "--lifecycle-placement-seed", "seed.json", + }) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if f.lifecyclePlacementSeed != "seed.json" { + t.Fatalf("lifecyclePlacementSeed=%q want seed.json", f.lifecyclePlacementSeed) + } +} + +func TestParseFlags_FailbackRuntimeRPCDisabledByDefault(t *testing.T) { + f, err := parseFlags([]string{ + "--authority-store", "authority-dir", + }) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if f.failbackRuntimeRPC { + t.Fatal("failback runtime RPC must be disabled by default") + } + f, err = parseFlags([]string{ + "--authority-store", "authority-dir", + "--failback-runtime-rpc", + }) + if err != nil { + t.Fatalf("parseFlags with failback runtime RPC: %v", err) + } + if !f.failbackRuntimeRPC { + t.Fatal("failback runtime RPC flag not set") + } +} + +func TestParseFlags_FrontendPublicationRuntimeHTTPDisabledByDefault(t *testing.T) { + f, err := parseFlags([]string{ + "--authority-store", "authority-dir", + }) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if f.frontendPublicationRuntimeHTTP { + t.Fatal("frontend publication runtime HTTP must be disabled by default") + } + f, err = parseFlags([]string{ + "--authority-store", "authority-dir", + "--frontend-publication-runtime-http", + "--frontend-publication-runtime-listen", "127.0.0.1:9334", // unauthenticated: loopback only + }) + if err != nil { + t.Fatalf("parseFlags with frontend publication runtime HTTP: %v", err) + } + if !f.frontendPublicationRuntimeHTTP || f.frontendPublicationRuntimeListen != "127.0.0.1:9334" { + t.Fatalf("frontend publication runtime flags=%+v", f) + } +} + +func TestParseFlags_ClusterSpecOptional(t *testing.T) { + f, err := parseFlags([]string{ + "--authority-store", "authority-dir", + "--lifecycle-store", "lifecycle-dir", + "--cluster-spec", "m01.yaml", + }) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if f.clusterSpec != "m01.yaml" { + t.Fatalf("clusterSpec=%q want m01.yaml", f.clusterSpec) + } +} + +func TestParseFlags_LauncherExternalStatusOptional(t *testing.T) { + f, err := parseFlags([]string{ + "--authority-store", "authority-dir", + "--lifecycle-store", "lifecycle-dir", + "--launcher-status", + "--launcher-external-status", + }) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !f.launcherStatus || !f.launcherExternalStatus { + t.Fatalf("launcher status flags = %v/%v want true/true", f.launcherStatus, f.launcherExternalStatus) + } +} + +func TestParseFlags_LauncherExternalISCSIRequiresCHAP(t *testing.T) { + if _, err := parseFlags([]string{ + "--authority-store", "authority-dir", + "--launcher-external-iscsi", + }); err == nil { + t.Fatal("expected --launcher-external-iscsi without CHAP secret to fail") + } + f, err := parseFlags([]string{ + "--authority-store", "authority-dir", + "--launcher-external-iscsi", + "--launcher-iscsi-chap-secret-name", "sw-block-iscsi-chap", + }) + if err != nil { + t.Fatalf("parseFlags with CHAP: %v", err) + } + if !f.launcherExternalISCSI || f.launcherCHAPSecretName != "sw-block-iscsi-chap" { + t.Fatalf("external iscsi flags = %v/%q", f.launcherExternalISCSI, f.launcherCHAPSecretName) + } +} + +func TestParseFlags_LauncherExternalNVMeOptional(t *testing.T) { + f, err := parseFlags([]string{ + "--authority-store", "authority-dir", + "--launcher-external-nvme", + }) + if err != nil { + t.Fatalf("parseFlags with external NVMe: %v", err) + } + if !f.launcherExternalNVMe { + t.Fatal("launcherExternalNVMe=false") + } +} + +func TestParseFlags_LauncherNVMeMaxH2CDataLength(t *testing.T) { + f, err := parseFlags([]string{ + "--authority-store", "authority-dir", + "--launcher-nvme-max-h2c-data-length", "65536", + }) + if err != nil { + t.Fatalf("parseFlags with launcher NVMe H2C candidate: %v", err) + } + if f.launcherNVMeMaxH2CDataLength != 65536 { + t.Fatalf("launcherNVMeMaxH2CDataLength=%d want 65536", f.launcherNVMeMaxH2CDataLength) + } + + _, err = parseFlags([]string{ + "--authority-store", "authority-dir", + "--launcher-nvme-max-h2c-data-length", "49152", + }) + if err == nil { + t.Fatal("parseFlags succeeded; want invalid launcher NVMe H2C rejected") + } + if !strings.Contains(err.Error(), "--launcher-nvme-max-h2c-data-length=49152 invalid") { + t.Fatalf("error=%v, want invalid launcher NVMe H2C", err) + } +} + +func TestPhase150_ParseFlagsLauncherWALMultiBlockRecords(t *testing.T) { + f, err := parseFlags([]string{ + "--authority-store", "/tmp/a", + "--topology", "topology.yaml", + "--launcher-durable-wal-multiblock-records", + }) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !f.launcherWALMultiBlockRecords { + t.Fatal("launcherWALMultiBlockRecords=false, want true") + } +} + +func TestPhase152_ParseFlagsLauncherWALRecoveryTestDisableFlusher(t *testing.T) { + f, err := parseFlags([]string{ + "--authority-store", "/tmp/a", + "--topology", "topology.yaml", + "--launcher-durable-wal-recovery-test-disable-flusher", + }) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !f.launcherWALRecoveryTestDisableFlusher { + t.Fatal("launcherWALRecoveryTestDisableFlusher=false, want true") + } +} + +func TestBlockmasterBareTopologyRegistersVolumeControlServices(t *testing.T) { + h, err := master.New(master.Config{ + AuthorityStoreDir: t.TempDir(), + Listen: "127.0.0.1:0", + }) + if err != nil { + t.Fatalf("master.New: %v", err) + } + h.Start() + defer func() { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + _ = h.Close(ctx) + }() + + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("grpc.NewClient: %v", err) + } + defer conn.Close() + + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + + _, err = control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{}) + if err == nil { + t.Fatal("ReportHeartbeat with empty report unexpectedly succeeded") + } + if status.Code(err) == codes.Unimplemented || strings.Contains(err.Error(), "unknown service") { + t.Fatalf("ObservationService not registered on bare blockmaster: %v", err) + } + if status.Code(err) == codes.Unavailable || status.Code(err) == codes.DeadlineExceeded { + t.Fatalf("transport error while checking ObservationService registration: %v", err) + } + + stream, err := control.NewAssignmentServiceClient(conn).SubscribeAssignments(ctx, &control.SubscribeRequest{}) + if err == nil { + _, err = stream.Recv() + } + if err == nil { + t.Fatal("SubscribeAssignments with empty request unexpectedly succeeded") + } + if status.Code(err) == codes.Unimplemented || strings.Contains(err.Error(), "unknown service") { + t.Fatalf("AssignmentService not registered on bare blockmaster: %v", err) + } + if status.Code(err) == codes.Unavailable || status.Code(err) == codes.DeadlineExceeded { + t.Fatalf("transport error while checking AssignmentService registration: %v", err) + } + + _, err = control.NewFailbackServiceClient(conn).ExecuteFailback(ctx, &control.FailbackRequest{VolumeId: "vol-a"}) + if status.Code(err) == codes.Unimplemented || strings.Contains(err.Error(), "unknown service") { + t.Fatalf("FailbackService not registered on bare blockmaster: %v", err) + } + if status.Code(err) != codes.FailedPrecondition { + t.Fatalf("ExecuteFailback default-disabled code=%s err=%v", status.Code(err), err) + } +} diff --git a/seaweed-block/cmd/blockmaster/node_registry_guard_test.go b/seaweed-block/cmd/blockmaster/node_registry_guard_test.go new file mode 100644 index 0000000000..77b785079e --- /dev/null +++ b/seaweed-block/cmd/blockmaster/node_registry_guard_test.go @@ -0,0 +1,75 @@ +package main + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "path/filepath" + "sort" + "strings" + "testing" +) + +// The node registry (server id -> registered host) only ever loses entries +// after start: the identity checks (the registered-host refusal beside the +// certificate identity) assume no one adds or rebinds a server id while +// blockmaster serves. Its only adder is the cluster-spec import at start-up. +// Its one remover after start is the operator's host retire, which takes +// only a host that holds no volume: a retired id is then unregistered, so a +// holder RPC under it is refused (refuseWorkspaceHolderHost) and the checks +// only get stricter. This guard fails when any other non-test caller of +// RegisterNode or RemoveNode appears anywhere. +func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) { + root, err := filepath.Abs(filepath.Join("..", "..")) + if err != nil { + t.Fatal(err) + } + var sites []string + fset := token.NewFileSet() + err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + switch d.Name() { + case ".git", "vendor", "node_modules", "testdata": + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + f, err := parser.ParseFile(fset, path, nil, 0) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + for _, decl := range f.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "RegisterNode" || sel.Sel.Name == "RemoveNode") { + sites = append(sites, filepath.ToSlash(rel)+":"+fn.Name.Name+"."+sel.Sel.Name) + } + return true + }) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + sort.Strings(sites) + want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.RegisterNode", "core/host/master/format_gate.go:RetireHost.RemoveNode"} + if strings.Join(sites, ",") != strings.Join(want, ",") { + t.Fatalf("node registry writers = %v, want only %v: an adder after start, or another remover, breaks the identity checks' assumption", sites, want) + } +} diff --git a/seaweed-block/cmd/blockmaster/product_loop_guard.go b/seaweed-block/cmd/blockmaster/product_loop_guard.go new file mode 100644 index 0000000000..cac699e81d --- /dev/null +++ b/seaweed-block/cmd/blockmaster/product_loop_guard.go @@ -0,0 +1,42 @@ +package main + +import ( + "fmt" + "time" +) + +// requireProductLoop refuses a start whose cluster spec holds a replicated +// volume (replication factor above 1) that the master could never decide: +// - one whose replication factor differs from --expected-slots-per-volume: +// the controller validates every replicated volume against that one +// count and refuses the whole decision when one differs, so it would +// stop every replicated volume's assignment and failover; +// - any, while the lifecycle product loop is off: on the cluster-spec path +// that loop alone binds a replicated volume's placement, mints its line +// and runs its promotion gate, so with the loop off it never gets a line. +// +// A static --topology (whose observation controller mints) and +// single-replica volumes are untouched. +func requireProductLoop(interval time.Duration, expectedSlots int, spec clusterSpecImport) error { + // Every cluster-spec volume has a placement intent (a placement-only + // entry, without size_bytes, has no volume spec), so the placements are + // what is read. + for _, p := range spec.Placements { + if p.DesiredRF > 1 && p.DesiredRF != expectedSlots { + return fmt.Errorf("cluster spec volume %s has replication factor %d but --expected-slots-per-volume is %d: "+ + "the master decides replicated volumes of one slot count only (one replicated factor per cluster)", + p.VolumeID, p.DesiredRF, expectedSlots) + } + } + if interval > 0 { + return nil + } + for _, p := range spec.Placements { + if p.DesiredRF > 1 { + return fmt.Errorf("cluster spec volume %s has replication factor %d but --lifecycle-product-loop-interval is 0 (off): "+ + "with --cluster-spec a replicated volume is bound and promoted only by that loop; set --lifecycle-product-loop-interval (for example 100ms)", + p.VolumeID, p.DesiredRF) + } + } + return nil +} diff --git a/seaweed-block/cmd/blockmaster/product_loop_guard_test.go b/seaweed-block/cmd/blockmaster/product_loop_guard_test.go new file mode 100644 index 0000000000..3d201b78c4 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/product_loop_guard_test.go @@ -0,0 +1,164 @@ +package main + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// clusterSpecWithRF writes a cluster spec of three nodes and one volume v1 +// with the given replication factor (placements on the first rf nodes). +func clusterSpecWithRF(t *testing.T, rf int) string { return clusterSpecText(t, rf, true) } + +// clusterSpecText is clusterSpecWithRF with or without size_bytes (without: +// a placement-only entry, which has a placement intent and no volume spec). +func clusterSpecText(t *testing.T, rf int, sized bool) string { + t.Helper() + var b strings.Builder + b.WriteString("nodes:\n") + for i := 1; i <= 3; i++ { + b.WriteString(" - server_id: s" + string(rune('0'+i)) + "\n data_addr: 127.0.0.1:1" + string(rune('0'+i)) + "601\n ctrl_addr: 127.0.0.1:1" + string(rune('0'+i)) + "602\n") + } + b.WriteString("volumes:\n - id: v1\n") + if sized { + b.WriteString(" size_bytes: 268435456\n") + } + b.WriteString(" replication_factor: " + string(rune('0'+rf)) + "\n placements:\n") + for i := 1; i <= rf; i++ { + b.WriteString(" - server_id: s" + string(rune('0'+i)) + "\n replica_id: r" + string(rune('0'+i)) + "\n") + } + p := filepath.Join(t.TempDir(), "cluster-spec.yaml") + if err := os.WriteFile(p, []byte(b.String()), 0o600); err != nil { + t.Fatal(err) + } + return p +} + +// guardHelperEnv carries a blockmaster command line (fields separated by +// guardHelperSep) to the helper process below. +const ( + guardHelperEnv = "SWB_BLOCKMASTER_GUARD_HELPER_ARGS" + guardHelperSep = "\x1f" +) + +// TestGuardHelperProcess is not a test on its own: re-executed by +// TestReplicatedClusterSpecWithTheProductLoopOffIsRefused, it runs +// blockmaster's run with the given arguments and exits with its code. +func TestGuardHelperProcess(t *testing.T) { + args := os.Getenv(guardHelperEnv) + if args == "" { + t.Skip("helper process only") + } + f, err := parseFlags(strings.Split(args, guardHelperSep)) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(64) + } + os.Exit(run(f)) +} + +// A replicated cluster-spec volume with the product loop off is refused at +// start, naming the flag, before anything is opened (exit 2). blockmaster +// runs as a bounded child: without the guard it would start and serve, so +// the child is killed at the deadline and joined (exec closes its pipes). +func TestReplicatedClusterSpecWithTheProductLoopOffIsRefused(t *testing.T) { + args := []string{ + "--authority-store", filepath.Join(t.TempDir(), "authority"), + "--lifecycle-store", filepath.Join(t.TempDir(), "lifecycle"), + "--cluster-spec", clusterSpecWithRF(t, 3), + "--expected-slots-per-volume", "3", + "--listen", "127.0.0.1:0", + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + t.Cleanup(cancel) + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestGuardHelperProcess$") + cmd.Env = append(os.Environ(), guardHelperEnv+"="+strings.Join(args, guardHelperSep)) + cmd.WaitDelay = 5 * time.Second + out, err := cmd.CombinedOutput() // returns once the child exited (or was killed) and its pipes closed + if ctx.Err() != nil { + t.Fatalf("blockmaster started with a replicated cluster spec and the product loop off (killed at the deadline):\n%s", out) + } + var exit *exec.ExitError + if !errors.As(err, &exit) || exit.ExitCode() != 2 || !strings.Contains(string(out), "--lifecycle-product-loop-interval") || !strings.Contains(string(out), "v1") { + t.Fatalf("exit %v, output %q; want exit 2 and the flag named", err, out) + } +} + +// The same spec with the loop on, a single-replica spec with the loop off, +// and no cluster spec (a static topology) all pass the guard. +func TestTheProductLoopGuardPassesWhatItShould(t *testing.T) { + for name, c := range map[string]struct { + rf int + interval time.Duration + }{ + "rf3 with the loop on": {3, 100 * time.Millisecond}, + "rf1 with the loop off": {1, 0}, + } { + spec, err := loadClusterSpec(clusterSpecWithRF(t, c.rf)) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if err := requireProductLoop(c.interval, c.rf, spec); err != nil { + t.Fatalf("%s: refused: %v", name, err) + } + } + if err := requireProductLoop(0, 3, clusterSpecImport{}); err != nil { + t.Fatalf("no cluster spec (static topology): refused: %v", err) + } + spec, err := loadClusterSpec(clusterSpecWithRF(t, 2)) + if err != nil { + t.Fatal(err) + } + if err := requireProductLoop(0, 2, spec); err == nil { + t.Fatal("rf2 with the loop off passed") + } +} + +// A replicated cluster-spec volume whose replication factor differs from +// --expected-slots-per-volume is refused at start, naming the volume and +// both counts, also with the loop on; a matching one passes. +func TestAClusterSpecVolumeOfAnotherReplicationFactorIsRefused(t *testing.T) { + spec, err := loadClusterSpec(clusterSpecWithRF(t, 2)) + if err != nil { + t.Fatal(err) + } + err = requireProductLoop(100*time.Millisecond, 3, spec) + if err == nil || !strings.Contains(err.Error(), "v1") || !strings.Contains(err.Error(), "--expected-slots-per-volume is 3") { + t.Fatalf("an RF2 volume on an expected-3 master: %v; want a refusal naming v1 and both counts", err) + } + if err := requireProductLoop(100*time.Millisecond, 2, spec); err != nil { + t.Fatalf("an RF2 volume on an expected-2 master: refused: %v", err) + } +} + +// A placement-only replicated entry (no size_bytes: no volume spec, only a +// placement intent) is checked the same way: RF2 on an expected-3 master is +// refused, and RF3 with the loop off is refused. +func TestAPlacementOnlyClusterSpecVolumeIsChecked(t *testing.T) { + for _, c := range []struct { + name string + rf int + interval time.Duration + want string + }{ + {"rf2 on expected 3", 2, 100 * time.Millisecond, "--expected-slots-per-volume is 3"}, + {"rf3 with the loop off", 3, 0, "--lifecycle-product-loop-interval is 0"}, + } { + spec, err := loadClusterSpec(clusterSpecText(t, c.rf, false)) + if err != nil { + t.Fatalf("%s: %v", c.name, err) + } + if len(spec.Volumes) != 0 || len(spec.Placements) != 1 { + t.Fatalf("%s: fixture: %d volume specs, %d placements; want a placement-only entry", c.name, len(spec.Volumes), len(spec.Placements)) + } + if err := requireProductLoop(c.interval, 3, spec); err == nil || !strings.Contains(err.Error(), c.want) { + t.Fatalf("%s: %v; want a refusal with %q", c.name, err, c.want) + } + } +} diff --git a/seaweed-block/cmd/blockmaster/removed_flag_test.go b/seaweed-block/cmd/blockmaster/removed_flag_test.go new file mode 100644 index 0000000000..577cb2361f --- /dev/null +++ b/seaweed-block/cmd/blockmaster/removed_flag_test.go @@ -0,0 +1,35 @@ +package main + +import ( + "errors" + "strings" + "testing" +) + +// v1 removed --workspace-head-base-url (blockmaster reads HEAD through the +// layout catalog). A unit or script still passing it is refused at start +// with a typed error that names the replacement, in either flag form; it is +// never accepted and ignored. +func TestRemovedHeadBaseURLFlagIsRefusedAtStart(t *testing.T) { + base := func(extra ...string) []string { + return append([]string{"--authority-store", t.TempDir()}, extra...) + } + if _, err := parseFlags(base()); err != nil { + t.Fatalf("control without the removed flag: %v", err) + } + for name, args := range map[string][]string{ + "name=value": base("--workspace-head-base-url=http://filer:8888/swblock/chunks"), + "name value": base("--workspace-head-base-url", "http://filer:8888/swblock/chunks"), + "empty value": base("--workspace-head-base-url="), + "single dash": base("-workspace-head-base-url=http://filer:8888/swblock/chunks"), + "after others": base("--workspace-rpc", "--workspace-head-base-url=http://filer:8888/swblock/chunks"), + } { + _, err := parseFlags(args) + if !errors.Is(err, errRemovedInV1) { + t.Fatalf("%s: %v; want the removed-in-v1 refusal", name, err) + } + if !strings.Contains(err.Error(), "--workspace-head-base-url") || !strings.Contains(err.Error(), "--chunk-filer") { + t.Fatalf("%s: %q; want it to name the removed flag and its replacement", name, err) + } + } +} diff --git a/seaweed-block/cmd/blockmaster/topology.go b/seaweed-block/cmd/blockmaster/topology.go new file mode 100644 index 0000000000..24b23b0a23 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/topology.go @@ -0,0 +1,96 @@ +package main + +import ( + "fmt" + "os" + + "github.com/seaweedfs/seaweed-block/core/authority" + "gopkg.in/yaml.v3" +) + +// topologyFile is the YAML shape accepted by --topology . +// Example: +// +// volumes: +// - volume_id: v1 +// slots: +// - replica_id: r1 +// server_id: s1 +// - replica_id: r2 +// server_id: s2 +// - replica_id: r3 +// server_id: s3 +// +// This is the operator-supplied accepted topology the +// observation host uses to classify supportability. The master +// host does NOT infer topology from heartbeats; topology is an +// explicit input, matching T0 sketch §3 constraint that +// heartbeats are observation only, never authority or policy. +type topologyFile struct { + Volumes []topologyVolume `yaml:"volumes"` +} + +type topologyVolume struct { + VolumeID string `yaml:"volume_id"` + Slots []topologySlot `yaml:"slots"` +} + +type topologySlot struct { + ReplicaID string `yaml:"replica_id"` + ServerID string `yaml:"server_id"` +} + +// loadTopology reads the topology YAML from path and returns an +// authority.AcceptedTopology. Empty path returns empty topology; +// caller decides whether that's a hard error. +func loadTopology(path string) (authority.AcceptedTopology, error) { + if path == "" { + return authority.AcceptedTopology{}, nil + } + raw, err := os.ReadFile(path) + if err != nil { + return authority.AcceptedTopology{}, fmt.Errorf("topology: read %q: %w", path, err) + } + var f topologyFile + if err := yaml.Unmarshal(raw, &f); err != nil { + return authority.AcceptedTopology{}, fmt.Errorf("topology: parse %q: %w", path, err) + } + return toAcceptedTopology(&f) +} + +func toAcceptedTopology(f *topologyFile) (authority.AcceptedTopology, error) { + out := authority.AcceptedTopology{} + for i, v := range f.Volumes { + if v.VolumeID == "" { + return authority.AcceptedTopology{}, fmt.Errorf("topology: volume[%d] missing volume_id", i) + } + if len(v.Slots) == 0 { + return authority.AcceptedTopology{}, fmt.Errorf("topology: volume %q has no slots", v.VolumeID) + } + slots := make([]authority.ExpectedSlot, 0, len(v.Slots)) + seenRid := make(map[string]struct{}, len(v.Slots)) + seenSid := make(map[string]struct{}, len(v.Slots)) + for j, s := range v.Slots { + if s.ReplicaID == "" || s.ServerID == "" { + return authority.AcceptedTopology{}, fmt.Errorf("topology: volume %q slot[%d] missing replica_id or server_id", v.VolumeID, j) + } + if _, dup := seenRid[s.ReplicaID]; dup { + return authority.AcceptedTopology{}, fmt.Errorf("topology: volume %q duplicate replica_id %q", v.VolumeID, s.ReplicaID) + } + if _, dup := seenSid[s.ServerID]; dup { + return authority.AcceptedTopology{}, fmt.Errorf("topology: volume %q duplicate server_id %q", v.VolumeID, s.ServerID) + } + seenRid[s.ReplicaID] = struct{}{} + seenSid[s.ServerID] = struct{}{} + slots = append(slots, authority.ExpectedSlot{ + ReplicaID: s.ReplicaID, + ServerID: s.ServerID, + }) + } + out.Volumes = append(out.Volumes, authority.VolumeExpected{ + VolumeID: v.VolumeID, + Slots: slots, + }) + } + return out, nil +} diff --git a/seaweed-block/cmd/blockmaster/topology_test.go b/seaweed-block/cmd/blockmaster/topology_test.go new file mode 100644 index 0000000000..8b7cbc99ca --- /dev/null +++ b/seaweed-block/cmd/blockmaster/topology_test.go @@ -0,0 +1,131 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// D5 — --topology flag integration test. Validates the YAML +// loader that feeds cmd/blockmaster. L2 subprocess tests (D1) +// consume topology via this flag, not via master.Config +// directly, so flag parsing must be proven independently. + +func TestCmdBlockmaster_TopologyFlagLoaded(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "topology.yaml") + if err := os.WriteFile(path, []byte(` +volumes: + - volume_id: v1 + slots: + - replica_id: r1 + server_id: s1 + - replica_id: r2 + server_id: s2 + - replica_id: r3 + server_id: s3 +`), 0o644); err != nil { + t.Fatalf("write topology: %v", err) + } + + topo, err := loadTopology(path) + if err != nil { + t.Fatalf("loadTopology: %v", err) + } + if len(topo.Volumes) != 1 { + t.Fatalf("volumes: got %d want 1", len(topo.Volumes)) + } + v := topo.Volumes[0] + if v.VolumeID != "v1" { + t.Fatalf("volume id: got %q want v1", v.VolumeID) + } + if len(v.Slots) != 3 { + t.Fatalf("slots: got %d want 3", len(v.Slots)) + } + want := []struct{ replica, server string }{ + {"r1", "s1"}, {"r2", "s2"}, {"r3", "s3"}, + } + for i, w := range want { + if v.Slots[i].ReplicaID != w.replica || v.Slots[i].ServerID != w.server { + t.Fatalf("slot[%d]: got %+v want %+v", i, v.Slots[i], w) + } + } +} + +func TestCmdBlockmaster_TopologyFlag_RejectsDuplicateReplica(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "bad.yaml") + if err := os.WriteFile(path, []byte(` +volumes: + - volume_id: v1 + slots: + - replica_id: r1 + server_id: s1 + - replica_id: r1 + server_id: s2 +`), 0o644); err != nil { + t.Fatalf("write: %v", err) + } + _, err := loadTopology(path) + if err == nil { + t.Fatal("expected error on duplicate replica_id") + } + if !strings.Contains(err.Error(), "duplicate replica_id") { + t.Fatalf("error must name the violation; got: %v", err) + } +} + +func TestCmdBlockmaster_TopologyFlag_RejectsDuplicateServer(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "bad.yaml") + if err := os.WriteFile(path, []byte(` +volumes: + - volume_id: v1 + slots: + - replica_id: r1 + server_id: s1 + - replica_id: r2 + server_id: s1 +`), 0o644); err != nil { + t.Fatalf("write: %v", err) + } + _, err := loadTopology(path) + if err == nil { + t.Fatal("expected error on duplicate server_id") + } + if !strings.Contains(err.Error(), "duplicate server_id") { + t.Fatalf("error must name the violation; got: %v", err) + } +} + +func TestCmdBlockmaster_TopologyFlag_EmptyIsValid(t *testing.T) { + // Empty topology is a valid startup state (empty cluster); + // master logs a warning but loadTopology itself succeeds. + topo, err := loadTopology("") + if err != nil { + t.Fatalf("empty path: unexpected error %v", err) + } + if len(topo.Volumes) != 0 { + t.Fatalf("empty path must yield zero volumes; got %d", len(topo.Volumes)) + } +} + +func TestCmdBlockmaster_TopologyFlag_MissingFileRejected(t *testing.T) { + _, err := loadTopology(filepath.Join(t.TempDir(), "nonexistent.yaml")) + if err == nil { + t.Fatal("expected error on missing file") + } +} + +func TestCmdBlockmaster_TopologyFlag_MalformedRejected(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "bad.yaml") + if err := os.WriteFile(path, []byte("not: [valid yaml"), 0o644); err != nil { + t.Fatalf("write: %v", err) + } + _, err := loadTopology(path) + if err == nil { + t.Fatal("expected error on malformed YAML") + } +} diff --git a/seaweed-block/cmd/blockmaster/workspace_layout_head_test.go b/seaweed-block/cmd/blockmaster/workspace_layout_head_test.go new file mode 100644 index 0000000000..c20811c87d --- /dev/null +++ b/seaweed-block/cmd/blockmaster/workspace_layout_head_test.go @@ -0,0 +1,63 @@ +package main + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "path/filepath" + "reflect" + "strings" + "testing" +) + +// The runtime uses the master-bound reader; the legacy constructor is not a +// fallback. Every constructor/resolver caller is a classified production site. +func TestWorkspaceLayoutHEADReaderWiring(t *testing.T) { + want := map[string]int{"cmd/blockmaster/main.go run -> NewLayoutWorkspaceHEADReader": 1, "cmd/blockmaster/main.go run -> WorkspaceLayoutVolume": 1} + found := map[string]int{} + root := filepath.Join("..", "..") + for _, top := range []string{"core", "cmd"} { + err := filepath.WalkDir(filepath.Join(root, top), func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { + return err + } + f, err := parser.ParseFile(token.NewFileSet(), p, nil, 0) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, p) + for _, d := range f.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + c, ok := n.(*ast.CallExpr) + if !ok { + return true + } + name := "" + switch x := c.Fun.(type) { + case *ast.Ident: + name = x.Name + case *ast.SelectorExpr: + name = x.Sel.Name + } + switch name { + case "NewLayoutWorkspaceHEADReader", "WorkspaceLayoutVolume": + found[filepath.ToSlash(rel)+" "+fn.Name.Name+" -> "+name]++ + } + return true + }) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + if !reflect.DeepEqual(want, found) { + t.Fatalf("HEAD reader wiring changed; classify and probe the new site: want %v, got %v", want, found) + } +} diff --git a/seaweed-block/cmd/blockmaster/workspace_skew_test.go b/seaweed-block/cmd/blockmaster/workspace_skew_test.go new file mode 100644 index 0000000000..ed02745c61 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/workspace_skew_test.go @@ -0,0 +1,45 @@ +package main + +import ( + "strings" + "testing" + "time" +) + +func TestWorkspaceClockSkewFlag(t *testing.T) { + for _, v := range []string{"0s", "-1s", "60s", "90s"} { + if _, err := parseFlags([]string{"--authority-store", "unused", "--workspace-max-clock-skew", v}); err == nil { + t.Errorf("accepted %s", v) + } + } + for _, v := range []string{"10.2s", "11s", "20s", "59s"} { + f, err := parseFlags([]string{"--authority-store", "unused", "--workspace-max-clock-skew", v}) + want, _ := time.ParseDuration(v) + if err != nil || f.workspaceMaxClockSkew != want { + t.Fatal(v, f.workspaceMaxClockSkew, err) + } + } + f, err := parseFlags([]string{"--authority-store", "unused"}) + if err != nil || f.workspaceMaxClockSkew != 20*time.Second { + t.Fatal("default", err) + } +} + +func TestWorkspaceSkewMustExceedFenceExitBound(t *testing.T) { + for _, tc := range []struct{ skew, half string }{{"8s", "4s"}, {"10.1s", "5.05s"}} { + t.Run(tc.skew, func(t *testing.T) { + _, err := parseFlags([]string{"--authority-store", "unused", "--workspace-max-clock-skew", tc.skew}) + if err == nil { + t.Fatalf("accepted skew %s whose half does not exceed fence exit", tc.skew) + } + for _, want := range []string{"--workspace-max-clock-skew=" + tc.skew, "half-skew=" + tc.half, "configured fence-exit budget=5.05s", "watch cadence=50ms", "drain timeout=5s", "assuming normal scheduling", "increase", "10.1s"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("refusal %q lacks %q", err, want) + } + } + }) + } + if _, err := parseFlags([]string{"--authority-store", "unused"}); err != nil { + t.Fatalf("20s default refused: %v", err) + } +} diff --git a/seaweed-block/cmd/blockvolume/blockmaster_skew_refusal_test.go b/seaweed-block/cmd/blockvolume/blockmaster_skew_refusal_test.go new file mode 100644 index 0000000000..4e0fa77c16 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/blockmaster_skew_refusal_test.go @@ -0,0 +1,47 @@ +//go:build subprocess + +package main_test + +import ( + "context" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// The operator guide's clock-safety rule, run on the real binary: blockmaster +// refuses to start when half of --workspace-max-clock-skew does not exceed its +// fence-exit budget, and the refusal names the bound to use (above 10.1 s). +func TestBlockmasterRefusesASkewBoundAtOrBelowTheFenceExit(t *testing.T) { + bins := buildG54Binaries(t) + art := t.TempDir() + topo := writeSingleSlotTopology(t, art) + for _, skew := range []string{"8s", "10.1s"} { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + out, err := exec.CommandContext(ctx, bins.master, + "--authority-store", filepath.Join(art, "master-"+skew), + "--listen", "127.0.0.1:0", "--topology", topo, "--expected-slots-per-volume", "1", + "--workspace-max-clock-skew", skew).CombinedOutput() + timedOut := ctx.Err() != nil + cancel() + var exit *exec.ExitError + if timedOut || !errorsAsExit(err, &exit) || exit.ExitCode() == 0 { + t.Fatalf("skew %s: blockmaster did not refuse to start (err %v, timed out %v):\n%s", skew, err, timedOut, out) + } + for _, want := range []string{"--workspace-max-clock-skew=" + skew, "10.1s"} { + if !strings.Contains(string(out), want) { + t.Fatalf("skew %s: the refusal does not name %q:\n%s", skew, want, out) + } + } + } +} + +func errorsAsExit(err error, exit **exec.ExitError) bool { + e, ok := err.(*exec.ExitError) + if ok { + *exit = e + } + return ok +} diff --git a/seaweed-block/cmd/blockvolume/c3_graceful_stop_integration_test.go b/seaweed-block/cmd/blockvolume/c3_graceful_stop_integration_test.go new file mode 100644 index 0000000000..cfe964dc4e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/c3_graceful_stop_integration_test.go @@ -0,0 +1,41 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "syscall" + "testing" + "time" +) + +// The graceful-stop procedure: the driver applies the same pre-create disk cap +// and measured neighbour as C3. No SIGKILL is sent until this cell has ended. +func TestC3GracefulStopWithReclaimPressure(t *testing.T) { + env := startHandoffEnvWith(t, 1, nil) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + d := env.start(t, "blockvolume-graceful", "s1") + env.adopt(t, d, "s1") + var chunks []uint64 + for c := uint64(0); c < 32; c++ { + chunks = append(chunks, c) + } + env.writeImage(t, "s1", denseImage("graceful-pressure", chunks)) + began := time.Now() + t.Logf("GRACEFUL_BEGIN time=%s", began.UTC().Format(time.RFC3339Nano)) + if err := d.proc.Signal(syscall.SIGTERM); err != nil { + t.Fatal(err) + } + select { + case <-d.done: + keepFullLog(t, d) + t.Logf("GRACEFUL_PHASES log tail:\n%s", d.tail(80)) + t.Logf("GRACEFUL_END elapsed=%s err=%v", time.Since(began), d.err) + if d.err != nil { + t.Fatalf("graceful exit: %v", d.err) + } + case <-time.After(5 * time.Minute): + keepFullLog(t, d) + logTaskState(t, d, "graceful driver ceiling") + t.Skip("UNKNOWN: graceful driver ceiling expired; classify from phase/progress and kernel evidence, not elapsed time alone") + } +} diff --git a/seaweed-block/cmd/blockvolume/c3_progress_wait_integration_test.go b/seaweed-block/cmd/blockvolume/c3_progress_wait_integration_test.go new file mode 100644 index 0000000000..b90c47ab6c --- /dev/null +++ b/seaweed-block/cmd/blockvolume/c3_progress_wait_integration_test.go @@ -0,0 +1,60 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "encoding/json" + "fmt" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "net/http" + "testing" + "time" +) + +func waitC3RecoveryPrimary(t *testing.T, d *daemon, addr, target string) { + t.Helper() + w := newRecoveryPrimaryWait(time.Now()) + client := &http.Client{Timeout: time.Second} + needle := fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at r1@", target) + for { + var s volume.RecoveryProgressStatus + resp, err := client.Get("http://" + addr + "/status/recovery-progress?volume=" + target) + if err == nil { + if resp.StatusCode != http.StatusOK { + err = fmt.Errorf("recovery observer HTTP %d", resp.StatusCode) + } else { + err = json.NewDecoder(resp.Body).Decode(&s) + } + resp.Body.Close() + if err == nil && s.ProcessID == "" { + err = fmt.Errorf("recovery observer lacks process identity") + } + } + now := time.Now() + if err == nil { + t.Logf("C3_RECOVERY volume=%s status=%+v", target, s) + } else { + t.Logf("C3_RECOVERY volume=%s unavailable=%v", target, err) + } + + state, waitErr := w.observe(now, s, d.line(needle) != "" && err == nil, err == nil) + if state == "unknown" { + if now.Sub(w.began) >= 15*time.Minute { + t.Skip("UNKNOWN: C3 recovery exceeded15min experiment ceiling") + } + t.Skipf("UNKNOWN: recovery observation lacks timely counter/exit evidence or was unavailable for30s: %v", err) + } + if waitErr != nil { + t.Fatalf("%s: %v; log tail:\n%s", d.name, waitErr, d.tail(40)) + } + if state == "primary" { + return + } + select { + case <-d.done: + t.Fatalf("%s exited before PRIMARY: %v", d.name, d.err) + default: + } + time.Sleep(time.Second) + } +} diff --git a/seaweed-block/cmd/blockvolume/capture_floor_test.go b/seaweed-block/cmd/blockvolume/capture_floor_test.go new file mode 100644 index 0000000000..b653eb446e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/capture_floor_test.go @@ -0,0 +1,38 @@ +package main + +import ( + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" +) + +// The capture floor is durable.MinCaptureInterval: 5 minutes by default, +// so 60 s is refused; a program that sets it to 30 s before parsing flags +// accepts 30 s and refuses 29 s. The refusal names the floor in force. +func TestCaptureIntervalFloor(t *testing.T) { + base := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1") + parse := func(iv string) error { + _, err := parseFlags(append(append([]string{}, base...), "--chunk-capture-interval="+iv)) + return err + } + if durable.MinCaptureInterval != 5*time.Minute { + t.Fatalf("default floor %s, want 5m", durable.MinCaptureInterval) + } + if err := parse("60s"); err == nil || !strings.Contains(err.Error(), "at least 5m0s") { + t.Fatalf("60 s under the default floor: %v", err) + } + if err := parse("5m"); err != nil { + t.Fatalf("5m refused: %v", err) + } + old := durable.MinCaptureInterval + durable.MinCaptureInterval = 30 * time.Second + defer func() { durable.MinCaptureInterval = old }() + if err := parse("30s"); err != nil { + t.Fatalf("30 s under a 30 s floor: %v", err) + } + if err := parse("29s"); err == nil || !strings.Contains(err.Error(), "at least 30s") { + t.Fatalf("29 s under a 30 s floor: %v", err) + } +} diff --git a/seaweed-block/cmd/blockvolume/chunk_lease_required_test.go b/seaweed-block/cmd/blockvolume/chunk_lease_required_test.go new file mode 100644 index 0000000000..5ea71e7644 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/chunk_lease_required_test.go @@ -0,0 +1,23 @@ +package main + +import ( + "strings" + "testing" +) + +func TestChunkVolumeRequiresWorkspaceLeaseBeforeStart(t *testing.T) { + base := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore-chunk", "--chunk-filer=filer:18888") + for _, extra := range [][]string{nil, {"--workspace-lease=false"}} { + _, err := parseFlags(append(append([]string{}, base...), extra...)) + if err == nil || !strings.Contains(err.Error(), "--workspace-lease is required") || !strings.Contains(err.Error(), "forced move") { + t.Fatalf("unleased chunk start: %v", err) + } + } + if _, err := parseFlags(append(base, "--workspace-lease")); err != nil { + t.Fatalf("leased chunk start: %v", err) + } + plain := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore") + if _, err := parseFlags(plain); err != nil { + t.Fatalf("plain walstore unexpectedly requires a workspace lease: %v", err) + } +} diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance.go b/seaweed-block/cmd/blockvolume/chunk_maintenance.go new file mode 100644 index 0000000000..975d3fa189 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance.go @@ -0,0 +1,72 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" +) + +// errNoLayoutHolder: the process has no holder identity for the volume yet +// (it is not attached, or Start has not returned), so it does not clean. +var errNoLayoutHolder = errors.New("blockvolume: no layout holder identity for the volume") + +// newChunkMaintenance is the holder's periodic pass over its one volume ref: +// retention, then, when collect is set, the cleaning through the holder's +// own layout remote (remote.Clean with the catalog's removal step), the one +// cleaning entry: a cut or a stop cancels it through the remote's state. +// cleanerOf returns the remote Start established; its Begin refuses unless +// HEAD is still that holder's at its epoch, so a process that lost the +// volume removes nothing. Automatic cleaning is on by default (--chunk-maintenance-gc); +// retention runs either way. +// layoutCleaner is the holder's layout remote as the maintenance cleans +// through it (chunkstore.LayoutRemote). +type layoutCleaner interface { + Clean(ctx context.Context, run func(ctx context.Context, me layout.HolderID, session string) error) error +} + +func newChunkMaintenance(cat *chunkstore.BCatalog, ref chunkstore.VolumeRef, cleanerOf func(context.Context) (layoutCleaner, error), collect bool, now func() time.Time) func(context.Context, string) error { + return func(ctx context.Context, vol string) error { + if cat == nil || vol != ref.Name || ref.ID.IsZero() { + return fmt.Errorf("%w: maintenance of %q, process holds %q", layout.ErrIdentity, vol, ref.Name) + } + if _, err := cat.Retain(ctx, ref, now(), false); err != nil { + return fmt.Errorf("retain: %w", err) + } + if !collect { + return nil + } + remote, err := cleanerOf(ctx) + if err != nil { + return err + } + var res chunkstore.CleanResult + var session string + err = remote.Clean(ctx, func(ctx context.Context, me layout.HolderID, s string) error { + session = s + // This generation is diagnostic only; it does not authorize removal. + head, found, readErr := cat.ReadHead(ctx, ref) + diagnostic := "" + if readErr != nil { + diagnostic = fmt.Sprintf("HEAD generation not read: %v", readErr) + } else if !found { + diagnostic = "HEAD generation not read: HEAD absent" + } + defer func() { + durable.ReportMaintenance(ctx, durable.MaintenancePassStatus{SkipReason: head.ListRetirementSkipReason(), Planned: int64(res.Planned), Removed: int64(res.Removed), PlannedChunks: int64(res.PlannedChunks), PlannedRoots: int64(res.PlannedRoots), PlannedSegments: int64(res.PlannedSegments), RemovedChunks: int64(res.Removed - res.Roots - res.Segments - res.Lists), RemovedRoots: int64(res.Roots), RemovedSegments: int64(res.Segments), PlannedLists: int64(res.PlannedLists), RemovedLists: int64(res.Lists), HeadGen: head.Gen, HeadGenError: diagnostic}) + }() + var rerr error + res, rerr = cat.RemoveUnreachableAll(ctx, ref, me, s) + return rerr + }) + log.Printf("blockvolume: maintenance volume=%s clean=%s shards=%d planned=%d removed=%d removedChunks=%d removedRoots=%d removedSegments=%d plannedChunks=%d plannedRoots=%d plannedSegments=%d plannedLists=%d removedLists=%d", vol, session, res.Shards, res.Planned, res.Removed, res.Removed-res.Roots-res.Segments-res.Lists, res.Roots, res.Segments, res.PlannedChunks, res.PlannedRoots, res.PlannedSegments, res.PlannedLists, res.Lists) + // A cleaning refused because HEAD moved away from this holder is + // the same fence a cut would see: classified so the provider latches. + return chunkstore.LayoutErr(err) + } +} diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go b/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go new file mode 100644 index 0000000000..31dc651484 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go @@ -0,0 +1,189 @@ +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "path" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// maintenanceBlobs is an in-memory needle store. +type maintenanceBlobs struct { + mu sync.Mutex + n int + d map[string][]byte +} + +func (b *maintenanceBlobs) Put(_ context.Context, data []byte) (string, error) { + b.mu.Lock() + defer b.mu.Unlock() + b.n++ + fid := fmt.Sprintf("1,%x", b.n) + b.d[fid] = append([]byte(nil), data...) + return fid, nil +} + +func (b *maintenanceBlobs) Get(_ context.Context, fid string) ([]byte, error) { + b.mu.Lock() + defer b.mu.Unlock() + d, ok := b.d[fid] + if !ok { + return nil, chunkstore.ErrBlobNotFound + } + return append([]byte(nil), d...), nil +} + +// failingLookups fails every entry lookup once armed (a filer gone away). +type failingLookups struct { + *chunkstore.MemFiler + armed bool +} + +func (f *failingLookups) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if f.armed { + return nil, errors.New("filer: unavailable") + } + return f.MemFiler.LookupEntry(ctx, dir, name) +} + +type okLease struct{} + +func (okLease) OldLeaseEnded(context.Context, uint64) error { return nil } + +var maintenanceHolder = layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + +// maintenanceFixture is volume v1 started by maintenanceHolder, with one +// orphan chunk in shard 0 that no root names. +func maintenanceFixture(t *testing.T) (*chunkstore.BCatalog, chunkstore.VolumeRef, *failingLookups, *chunkstore.LayoutStore, layout.ChunkName) { + t.Helper() + ctx := context.Background() + f := &failingLookups{MemFiler: chunkstore.NewMemFiler()} + cat, err := chunkstore.NewBCatalog(f, &maintenanceBlobs{d: map[string][]byte{}}, "/blocks") + if err != nil { + t.Fatal(err) + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + s, err := cat.Store(ref) + if err != nil { + t.Fatal(err) + } + if _, err := layout.Start(ctx, s, okLease{}, layout.HolderID{Epoch: 1, Holder: "s/r"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k", Fresh: true, CanStartFrom: anyStart}); err != nil { + t.Fatal(err) + } + data := bytes.Repeat([]byte{9}, 4096) + orphan := layout.NameChunk(3, data) + if err := layout.EnsureObject(ctx, s, orphan.Path(), data, "dead-session"); err != nil { + t.Fatal(err) + } + // A real filer lists the shard directory it created; the in-memory one + // keeps only entries. + if err := f.CreateEntry(ctx, path.Join("/blocks", ref.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); err != nil { + t.Fatal(err) + } + return cat, ref, f, s, orphan +} + +func orphanPresent(t *testing.T, s *chunkstore.LayoutStore, n layout.ChunkName) bool { + t.Helper() + _, found, err := s.Stat(context.Background(), n.Path()) + if err != nil { + t.Fatal(err) + } + return found +} + +// holderCalls is the attachment's layout remote for holder me (or err when +// the process has no holder identity yet), counting the calls. +func holderCalls(cat *chunkstore.BCatalog, ref chunkstore.VolumeRef, me layout.HolderID, err error) (func(context.Context) (layoutCleaner, error), *int) { + n := 0 + return func(context.Context) (layoutCleaner, error) { + n++ + if err != nil { + return nil, err + } + return chunkstore.NewLayoutRemote(cat, ref, me) + }, &n +} + +// Default-off: the pass retains and never asks for a holder or removes. +func TestMaintenanceDefaultRetainsAndDoesNotClean(t *testing.T) { + cat, ref, _, s, orphan := maintenanceFixture(t) + holder, calls := holderCalls(cat, ref, maintenanceHolder, nil) + pass := newChunkMaintenance(cat, ref, holder, false, time.Now) + if err := pass(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + if *calls != 0 || !orphanPresent(t, s, orphan) { + t.Fatalf("default pass: holder asked %d times, orphan present %v; want 0, true", *calls, orphanPresent(t, s, orphan)) + } +} + +// With collect on, the holder's pass removes the orphan; a process with +// another claim, or with no holder identity yet, removes nothing. +func TestMaintenanceCleansOnlyAsTheHolder(t *testing.T) { + ctx := context.Background() + for name, tc := range map[string]struct { + me layout.HolderID + err error + removed bool + }{ + "holder": {me: maintenanceHolder, removed: true}, + "other claim": {me: layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "old"}}, + "next epoch": {me: layout.HolderID{Epoch: 2, Holder: "s/r", ClaimID: "k"}}, + "no identity": {err: errNoLayoutHolder}, + } { + t.Run(name, func(t *testing.T) { + cat, ref, _, s, orphan := maintenanceFixture(t) + holder, _ := holderCalls(cat, ref, tc.me, tc.err) + err := newChunkMaintenance(cat, ref, holder, true, time.Now)(ctx, "v1") + if gone := !orphanPresent(t, s, orphan); gone != tc.removed || (err == nil) != tc.removed { + t.Fatalf("pass: err %v, orphan removed %v; want removed %v", err, gone, tc.removed) + } + if tc.err != nil && !errors.Is(err, tc.err) { + t.Fatalf("pass: %v; want %v", err, tc.err) + } + // HEAD is another claim's or epoch's: the refusal is the fence a + // cut would see, so the provider latches the layer on it. + if (name == "other claim" || name == "next epoch") && !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("pass refused as %v; want it classified as the fence", err) + } + }) + } +} + +// A failed retention ends the pass before the cleaning starts. +func TestMaintenanceRetentionFailureNeverStartsCleaning(t *testing.T) { + cat, ref, f, s, orphan := maintenanceFixture(t) + holder, calls := holderCalls(cat, ref, maintenanceHolder, nil) + f.armed = true + err := newChunkMaintenance(cat, ref, holder, true, time.Now)(context.Background(), "v1") + f.armed = false + if err == nil || *calls != 0 || !orphanPresent(t, s, orphan) { + t.Fatalf("pass with retention failing: err %v, holder asked %d, orphan present %v", err, *calls, orphanPresent(t, s, orphan)) + } +} + +// The pass serves only the volume the process was started for. +func TestMaintenanceRefusesAnotherVolume(t *testing.T) { + cat, ref, _, _, _ := maintenanceFixture(t) + holder, _ := holderCalls(cat, ref, maintenanceHolder, nil) + if err := newChunkMaintenance(cat, ref, holder, true, time.Now)(context.Background(), "v2"); !errors.Is(err, layout.ErrIdentity) { + t.Fatalf("pass for another volume: %v; want ErrIdentity", err) + } +} diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go new file mode 100644 index 0000000000..71ad6c9496 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -0,0 +1,259 @@ +package main + +// --durable-impl=walstore-chunk: walstore with the chunk layer publishing +// the volume to SeaweedFS (opt-in proof of concept). Each volume's HEAD and +// chunk key bindings live under <--chunk-path>/ on the filer +// given by --chunk-filer; chunk bytes are needles on its volume servers. + +import ( + "context" + "errors" + "fmt" + "path" + "strconv" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "google.golang.org/grpc" +) + +const ( + defaultChunkPath = chunkstore.DefaultChunkPath + // Periodic HEAD publication bounds the host-loss recovery point. Scheduled + // named snapshots are set by --chunk-snapshot-schedule. + defaultChunkCaptureInterval = 0 + defaultChunkMaintenanceInterval = time.Hour + defaultChunkCutTimeout = 5 * time.Minute + defaultChunkMaintenanceTimeout = time.Minute + // The holder's cleaning (removal of chunks no root names) is on by + // default; --chunk-maintenance-gc=false turns it off. + defaultChunkMaintenanceGC = true +) + +type chunkFlags struct { + detachPrecopy bool + hostLimit hostlimit.Config + filer string + path string + collection string + replication string + captureInterval time.Duration + maintenanceInterval time.Duration + snapshotSchedule snapshotSchedule + automaticGC bool + uploadConcurrency int + hydrationWorkers int + hydrationQueueDepth int + // controlEndpoint mounts the /chunk/* routes on the status listener. + controlEndpoint bool +} + +func validateChunkFlags(f flags) error { + c := f.chunk + if c.detachPrecopy { + return errors.New("--chunk-detach-precopy is not supported in this release") + } + if c.hostLimit.Directory != "" { + if err := c.hostLimit.Validate(); err != nil { + return err + } + } else if c.hostLimit != (hostlimit.Config{}) && c.hostLimit != hostlimit.DefaultConfig("") { + return errors.New("--host-limit-* settings require --host-limit-dir") + } + if f.durableImpl != "walstore-chunk" { + if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath || + c.captureInterval != defaultChunkCaptureInterval || c.maintenanceInterval != defaultChunkMaintenanceInterval || c.snapshotSchedule != defaultSnapshotSchedule || c.automaticGC != defaultChunkMaintenanceGC || + c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint || c.detachPrecopy || c.hostLimit.Directory != "" { + return errors.New("--chunk-* flags require --durable-impl=walstore-chunk") + } + return nil + } + if c.controlEndpoint && f.statusAddr == "" { + return errors.New("--chunk-control-endpoint requires --status-addr") + } + if f.replicationAck != "" && f.replicationAck != "best-effort" { + return fmt.Errorf("--durable-impl=walstore-chunk is single-replica: --replication-ack=%q needs replica peers (%s)", f.replicationAck, chunkRF1Reason) + } + if f.durableRoot == "" { + return errors.New("--durable-impl=walstore-chunk requires --durable-root") + } + if c.filer == "" { + return errors.New("--durable-impl=walstore-chunk requires --chunk-filer") + } + if !path.IsAbs(c.path) || path.Clean(c.path) != c.path || c.path == "/" { + return fmt.Errorf("--chunk-path=%q must be a clean absolute filer directory other than /", c.path) + } + if c.maintenanceInterval < 0 { + return errors.New("--chunk-maintenance-interval must not be negative") + } + if c.captureInterval > 0 && c.captureInterval < durable.MinCaptureInterval { + return fmt.Errorf("--chunk-capture-interval must be 0 or at least %s", durable.MinCaptureInterval) + } + if c.captureInterval < 0 { + return fmt.Errorf("--chunk-capture-interval=%s must not be negative", c.captureInterval) + } + if c.uploadConcurrency < 1 || c.uploadConcurrency > 64 { + return errors.New("--chunk-upload-concurrency must be between 1 and 64") + } + if c.hydrationWorkers < 1 || c.hydrationWorkers > 64 { + return errors.New("--chunk-hydration-workers must be between 1 and 64") + } + if c.hydrationQueueDepth < 1 || c.hydrationQueueDepth > 65536 { + return errors.New("--chunk-hydration-queue-depth must be between 1 and 65536") + } + return nil +} + +// chunkRF1Reason is why a walstore-chunk volume refuses replication, at start +// and on every assignment with replica slots: a chunk cut takes its LSN from the +// local WAL head, which no replica is guaranteed to hold, so a published HEAD +// could be ahead of every replica. The master's workspace RPCs enforce RF1; this +// is the same rule on the volume server, for a direct start. +const chunkRF1Reason = "chunk snapshots take the cut LSN from the local WAL, which replicas may not hold; walstore-chunk is RF1 only" + +// chunkWiring is what --durable-impl=walstore-chunk dials once: the +// provider's per-volume remotes, the catalog under the same base (VOLUME +// entries, snapshots) and the client's closer. +// snapshotSchedule is --chunk-snapshot-schedule: "daily:N", "weekly:N" +// (one scheduled snapshot per period at a per-volume offset, the newest N +// kept) or "off". +type snapshotSchedule struct { + period time.Duration + keep int +} + +var defaultSnapshotSchedule = snapshotSchedule{period: 24 * time.Hour, keep: 7} + +func (s *snapshotSchedule) String() string { + switch s.period { + case 0: + return "off" + case 24 * time.Hour: + return fmt.Sprintf("daily:%d", s.keep) + case 7 * 24 * time.Hour: + return fmt.Sprintf("weekly:%d", s.keep) + } + return fmt.Sprintf("%s:%d", s.period, s.keep) +} + +func (s *snapshotSchedule) Set(v string) error { + if v == "off" { + *s = snapshotSchedule{} + return nil + } + name, count, ok := strings.Cut(v, ":") + periods := map[string]time.Duration{"daily": 24 * time.Hour, "weekly": 7 * 24 * time.Hour} + keep, err := strconv.Atoi(count) + if !ok || periods[name] == 0 || err != nil || keep < 1 || keep > 1000 { + return fmt.Errorf("%q: want daily:N, weekly:N (N from 1 to 1000) or off", v) + } + *s = snapshotSchedule{period: periods[name], keep: keep} + return nil +} + +type chunkWiring struct { + bCatalog *chunkstore.BCatalog + close func() error +} + +// newChunkWiring dials the filer and refuses unless it is the only filer of +// its group (chunkstore.CheckSingleFiler). +func newChunkWiring(c chunkFlags, masterTLS grpc.DialOption, master ...string) (chunkWiring, error) { + bcat, client, err := chunkstore.DialBCatalog(context.Background(), chunkstore.SWFSConfig{ + FilerGRPC: c.filer, + Collection: c.collection, + Replication: c.replication, + AssignPath: c.path, + }) + if err != nil { + return chunkWiring{}, err + } + return chunkWiring{ + bCatalog: bcat, + close: client.Close, + }, nil +} + +// chunkAttachCheck admits only a volume the master already created in the +// store. Starting a holder never creates VOLUME or HEAD. +func chunkAttachCheck(cat *chunkstore.BCatalog, ref chunkstore.VolumeRef) func(context.Context, string, durable.ChunkGeometry) error { + return func(ctx context.Context, name string, g durable.ChunkGeometry) error { + if cat == nil || name != ref.Name || ref.ID.IsZero() { + return layout.ErrIdentity + } + st, err := cat.Store(ref) + if err != nil { + return err + } + v, found, err := st.ReadVolumeRecord(ctx) + if err != nil { + return err + } + if !found { + return fmt.Errorf("%w: volume %s not created in the store", layout.ErrMissing, name) + } + want := layout.Geometry{SizeBytes: g.NumBlocks * uint64(g.BlockSize), BlockSize: g.BlockSize, ChunkBytes: uint64(g.ChunkBlocks) * uint64(g.BlockSize)} + if v.Geometry != want { + return fmt.Errorf("%w: local %+v differs from VOLUME %+v", layout.ErrGeometryMismatch, want, v.Geometry) + } + _, found, err = cat.ReadHead(ctx, ref) + if err != nil { + return err + } + if !found { + return fmt.Errorf("%w: volume %s not created in the store", layout.ErrHeadAbsent, name) + } + return nil + } +} + +// exitGeometryRefused ends the process with no restart (the shipped units' +// RestartPreventExitStatus=78): a geometry flag that disagrees with the +// volume record stays wrong until the operator changes the flag. +const exitGeometryRefused = 78 + +// geometryFlagsRefusal reads only the immutable size_bytes, block_size and +// chunk_bytes of VOLUME before creating a local store. An unreadable record +// is unknown (75); corrupt bytes or a mismatch are final refusals (78). +func geometryFlagsRefusal(ctx context.Context, cat *chunkstore.BCatalog, ref chunkstore.VolumeRef, numBlocks uint64, blockSize uint32, chunkBlocks uint32) (string, int) { + if numBlocks == 0 { + return "", 0 + } + st, err := cat.Store(ref) + if err != nil { + return fmt.Sprintf("blockvolume: invalid volume identity: %v", err), exitGeometryRefused + } + v, found, err := st.ReadVolumeRecord(ctx) + if err != nil { + if errors.Is(err, layout.ErrMalformed) || errors.Is(err, layout.ErrCorrupt) || errors.Is(err, layout.ErrIdentity) { + return fmt.Sprintf("blockvolume: the volume record of %s is unreadable (corrupt: %v); no local store was created; restore or recreate the record", ref.Name, err), exitGeometryRefused + } + return fmt.Sprintf("blockvolume: the volume record of %s could not be read (%v); no local store was created; retrying", ref.Name, err), exitWorkspaceRetry + } + if !found { + return fmt.Sprintf("blockvolume: volume %s was not created in the store; no local store was created; retry the master CreateVolume operation", ref.Name), exitGeometryRefused + } + if v.SizeBytes == numBlocks*uint64(blockSize) && v.BlockSize == blockSize && v.ChunkBytes == uint64(chunkBlocks)*uint64(blockSize) { + return "", 0 + } + return fmt.Sprintf("blockvolume: geometry_mismatch: --durable-blocks %d --durable-blocksize %d --chunk-blocks %d disagree with the volume record of %s (%d blocks of %d bytes, chunk_bytes %d); no local store was created; start it with the record's geometry", numBlocks, blockSize, chunkBlocks, ref.Name, v.SizeBytes/uint64(v.BlockSize), v.BlockSize, v.ChunkBytes), exitGeometryRefused +} + +// chunkHolder is how this host names itself in HEAD: / +// (B9 W2 appendix). The replica id alone is not enough: +// two hosts that both serve replica r1 would look like the same holder +// returning, and the later one would not be fenced. +func chunkHolder(f flags) string { return f.serverID + "/" + f.replicaID } + +// chunkVolumeRoot is /; the volume ID must be one plain +// path element so no volume can reach another volume's directory. +func chunkVolumeRoot(base, volumeID string) (string, error) { + if volumeID == "" || volumeID == "." || volumeID == ".." || strings.ContainsAny(volumeID, "/\\") { + return "", fmt.Errorf("blockvolume: volume id %q is not a plain path element", volumeID) + } + return path.Join(base, volumeID), nil +} diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go new file mode 100644 index 0000000000..ad7c1ead84 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -0,0 +1,317 @@ +package main + +import ( + "context" + "errors" + "path" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" +) + +func TestWALStoreChunkFlags(t *testing.T) { + base := func(extra ...string) []string { + return append(phase150RequiredBlockvolumeArgs(), extra...) + } + f, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", + "--chunk-filer=127.0.0.1:18888", "--chunk-capture-interval=5m")) + if err != nil { + t.Fatalf("walstore-chunk with a filer: %v", err) + } + if f.chunk.filer != "127.0.0.1:18888" || f.chunk.path != defaultChunkPath || f.chunk.captureInterval != 5*time.Minute || f.chunk.controlEndpoint { + t.Fatalf("parsed chunk flags = %+v", f.chunk) + } + f, err = parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", + "--status-addr=127.0.0.1:0", "--chunk-control-endpoint")) + if err != nil || !f.chunk.controlEndpoint { + t.Fatalf("walstore-chunk with the control endpoint: %+v %v", f.chunk, err) + } + d, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1")) + if err != nil { + t.Fatal(err) + } + if d.chunk.captureInterval != 0 || d.chunk.maintenanceInterval != time.Hour || !d.chunk.automaticGC { + t.Fatalf("scheduler defaults: capture %s, maintenance %s, cleaning %v; want capture off (0), maintenance 1h and the cleaning on", d.chunk.captureInterval, d.chunk.maintenanceInterval, d.chunk.automaticGC) + } + // The cleaning is on by default; the one way to turn it off is explicit. + noClean, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-maintenance-gc=false")) + if err != nil || noClean.chunk.automaticGC || noClean.chunk.maintenanceInterval != time.Hour { + t.Fatalf("turning the cleaning off: %+v %v", noClean.chunk, err) + } + on, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-capture-interval=15m")) + if err != nil || on.chunk.captureInterval != 15*time.Minute { + t.Fatalf("opting in to a 15m periodic cut: %+v %v", on.chunk, err) + } + off, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", + "--chunk-capture-interval=0")) + if err != nil || off.chunk.captureInterval != 0 { + t.Fatalf("disabling the timer: %+v %v", off.chunk, err) + } + if _, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore")); err != nil { + t.Fatalf("walstore with the chunk defaults untouched: %v", err) + } + refused := map[string][]string{ + "no filer": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease"), + "no durable root": base("--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=127.0.0.1:18888"), + "relative path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-path=swblock"), + "root path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-path=/"), + "below OSS capture floor": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-capture-interval=4m59s"), + "60 s in an OSS build": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-capture-interval=60s"), + "negative maintenance": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-maintenance-interval=-1s"), + "negative interval": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-capture-interval=-1s"), + "chunk flag on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-filer=x:1"), + "chunk path on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-path=/other"), + "control endpoint on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--status-addr=127.0.0.1:0", + "--chunk-control-endpoint"), + "control endpoint without a status listener": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", + "--chunk-filer=x:1", "--chunk-control-endpoint"), + "zero upload concurrency": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-upload-concurrency=0"), + "too many uploads": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-upload-concurrency=65"), + "interval on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-capture-interval=5s"), + } + for name, args := range refused { + _, err := parseFlags(args) + if err == nil { + t.Errorf("%s: parseFlags succeeded; want an error", name) + } else if name == "no filer" && !strings.Contains(err.Error(), "requires --chunk-filer") { + t.Errorf("missing filer refused for wrong reason: %v", err) + } + } +} + +// --chunk-detach-precopy stays defined but is refused at flag validation, so +// a process started with it fails with a clear message instead of running the +// pre-copy detach; without it the same flags parse as before. +func TestChunkDetachPrecopyFlagRefused(t *testing.T) { + base := func(extra ...string) []string { + return append(phase150RequiredBlockvolumeArgs(), extra...) + } + valid := []string{"--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", + "--status-addr=127.0.0.1:0", "--chunk-control-endpoint"} + f, err := parseFlags(base(valid...)) + if err != nil || f.chunk.detachPrecopy { + t.Fatalf("valid chunk flags without --chunk-detach-precopy: %+v %v", f.chunk, err) + } + const want = "--chunk-detach-precopy is not supported in this release" + for name, args := range map[string][]string{ + "walstore-chunk": base(append(valid, "--chunk-detach-precopy")...), + "explicit true": base(append(valid, "--chunk-detach-precopy=true")...), + "without a chunk": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-detach-precopy"), + } { + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%s: parseFlags error = %v, want %q", name, err, want) + } + } + if _, err := parseFlags(base(append(valid, "--chunk-detach-precopy=false")...)); err != nil { + t.Errorf("explicit false: %v", err) + } +} + +func TestChunkVolumeRootStaysInsideBase(t *testing.T) { + root, err := chunkVolumeRoot(defaultChunkPath, "v1") + if err != nil || root != defaultChunkPath+"/v1" { + t.Fatalf("chunkVolumeRoot(v1) = %q, %v", root, err) + } + for _, id := range []string{"", ".", "..", "a/b", "../v2", `a\b`} { + if r, err := chunkVolumeRoot(defaultChunkPath, id); err == nil { + t.Errorf("volume id %q mapped to %q; want refusal", id, r) + } else if !strings.Contains(err.Error(), "plain path element") { + t.Errorf("volume id %q: unexpected error %v", id, err) + } + } +} + +// Before any local store is created, a geometry flag that disagrees with the +// volume record is refused with a line naming both (78); a record the filer +// could not deliver is refused as retryable (75), never taken as "absent"; +// a record that is there but does not decode is refused for good (78); +// a missing record is also refused (78), while matching geometry proceeds. +func TestGeometryFlagsRefusalComparesTheRecord(t *testing.T) { + ctx := context.Background() + + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + mem := chunkstore.NewMemFiler() + blobs := &maintenanceBlobs{d: map[string][]byte{}} + cat, err := chunkstore.NewBCatalog(mem, blobs, defaultChunkPath) + if err != nil { + t.Fatal(err) + } + if got, code := geometryFlagsRefusal(ctx, cat, ref, 32768, 4096, 1024); code != exitGeometryRefused || !strings.Contains(got, "not created in the store") { + t.Fatal("missing VOLUME must refuse attach", got, code) + } + g := layout.Geometry{SizeBytes: 65536 * 4096, BlockSize: 4096, ChunkBytes: 1024 * 4096} + if _, err := cat.CreateVolume(ctx, ref, g); err != nil { + t.Fatal(err) + } + if got, code := geometryFlagsRefusal(ctx, cat, ref, 65536, 4096, 1024); got != "" || code != 0 { + t.Fatal(got, code) + } + for _, g := range []struct { + blocks uint64 + size, chunk uint32 + }{{32768, 4096, 1024}, {65536, 512, 1024}, {65536, 4096, 512}} { + got, code := geometryFlagsRefusal(ctx, cat, ref, g.blocks, g.size, g.chunk) + if code != exitGeometryRefused || !strings.Contains(got, "geometry_mismatch") || !strings.Contains(got, "65536 blocks of 4096 bytes") { + t.Fatalf("mismatch: %q %d", got, code) + } + } + if got, code := geometryFlagsRefusal(ctx, cat, ref, 0, 0, 0); got != "" || code != 0 { + t.Fatal(got, code) + } + failing := &lookupFailFiler{MemFiler: mem, fail: true} + failCat, err := chunkstore.NewBCatalog(failing, blobs, defaultChunkPath) + if err != nil { + t.Fatal(err) + } + if got, code := geometryFlagsRefusal(ctx, failCat, ref, 65536, 4096, 1024); code != exitWorkspaceRetry || !strings.Contains(got, "could not be read") || failing.reads == 0 { + t.Fatal(got, code, failing.reads) + } + dir := path.Join(defaultChunkPath, ref.Dir()) + e, err := mem.LookupEntry(ctx, dir, "VOLUME") + if err != nil { + t.Fatal(err) + } + e.Content = []byte("{") + if err := mem.UpdateEntry(ctx, dir, e, nil); err != nil { + t.Fatal(err) + } + if got, code := geometryFlagsRefusal(ctx, cat, ref, 65536, 4096, 1024); code != exitGeometryRefused || !strings.Contains(got, "unreadable (corrupt:") { + t.Fatal(got, code) + } + +} + +// lookupFailFiler is a MemFiler whose LookupEntry fails once fail is set; it +// counts the lookups. +type lookupFailFiler struct { + *chunkstore.MemFiler + fail bool + reads int +} + +func (f *lookupFailFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + f.reads++ + if f.fail { + return nil, errors.New("filer unavailable") + } + return f.MemFiler.LookupEntry(ctx, dir, name) +} + +// Attach only reads the master's identified VOLUME and HEAD. +func TestChunkAttachCheckAppliesVolumeRules(t *testing.T) { + ctx := context.Background() + f := &layoutAttachFiler{MemFiler: chunkstore.NewMemFiler()} + cat, err := chunkstore.NewBCatalog(f, f, defaultChunkPath) + if err != nil { + t.Fatal(err) + } + id, _ := layout.ParseVolumeID("00112233445566778899aabbccddeeff") + ref := chunkstore.VolumeRef{Name: "v1", ID: id} + check := chunkAttachCheck(cat, ref) + g := durable.ChunkGeometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} + if err := check(ctx, "v1", g); !errors.Is(err, layout.ErrMissing) { + t.Fatal("attach created a missing volume", err) + } + if _, found, err := cat.ReadHead(ctx, ref); err != nil || found { + t.Fatal("attach created a missing HEAD", found, err) + } + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 8 * 4096}); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if err := check(ctx, "v1", g); err != nil { + t.Fatal(err) + } + } + h, found, err := cat.ReadHead(ctx, ref) + if err != nil || !found || h.VolumeID != id || h.Epoch != 0 || h.Holder != "" || h.Current != nil { + t.Fatalf("unclaimed HEAD: %+v %v", h, err) + } + if err := check(ctx, "other", g); !errors.Is(err, layout.ErrIdentity) { + t.Fatalf("wrong name: %v", err) + } + if err := chunkAttachCheck(cat, chunkstore.VolumeRef{Name: "v1"})(ctx, "v1", g); !errors.Is(err, layout.ErrIdentity) { + t.Fatalf("missing master id: %v", err) + } + if found, err := f.LookupEntry(ctx, defaultChunkPath+"/v1", "VOLUME"); err == nil || found != nil { + t.Fatalf("legacy directory created: %v", err) + } +} + +type layoutAttachFiler struct{ *chunkstore.MemFiler } + +func (*layoutAttachFiler) Put(context.Context, []byte) (string, error) { + return "", errors.New("attach must not upload data") +} +func (*layoutAttachFiler) Get(context.Context, string) ([]byte, error) { + return nil, errors.New("attach must not read data") +} + +// HEAD names a host as /: two servers serving the same +// replica id are different holders (B9 W2 appendix). +func TestChunkHolderIsServerAndReplica(t *testing.T) { + f, err := parseFlags(append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", + "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1")) + if err != nil { + t.Fatal(err) + } + if got := chunkHolder(f); got != "m02/r1" { + t.Fatalf("chunk holder %q, want m02/r1", got) + } +} + +// --chunk-dirty-threshold is gone: a cut stages by the +// copy-on-write budget (M5 Stage), so the flag never had an effect. A unit +// that still passes it fails at start. +func TestChunkDirtyThresholdFlagIsGone(t *testing.T) { + args := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-dirty-threshold=512") + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "flag provided but not defined") { + t.Fatalf("--chunk-dirty-threshold: %v; want flag provided but not defined", err) + } +} + +// --chunk-snapshot-schedule: daily:7 by default; daily:N, weekly:N and off +// are accepted; anything else is refused; setting it without walstore-chunk +// is refused like the other chunk flags. +func TestChunkSnapshotScheduleFlag(t *testing.T) { + base := func(extra ...string) []string { + return append(phase150RequiredBlockvolumeArgs(), extra...) + } + chunk := func(extra ...string) []string { + return base(append([]string{"--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1"}, extra...)...) + } + d, err := parseFlags(chunk()) + if err != nil || d.chunk.snapshotSchedule != (snapshotSchedule{period: 24 * time.Hour, keep: 7}) { + t.Fatalf("default schedule %+v %v; want daily, keep 7", d.chunk.snapshotSchedule, err) + } + for v, want := range map[string]snapshotSchedule{ + "daily:3": {period: 24 * time.Hour, keep: 3}, + "weekly:4": {period: 7 * 24 * time.Hour, keep: 4}, + "off": {}, + } { + f, err := parseFlags(chunk("--chunk-snapshot-schedule=" + v)) + if err != nil || f.chunk.snapshotSchedule != want { + t.Fatalf("%s: %+v %v; want %+v", v, f.chunk.snapshotSchedule, err, want) + } + if got := f.chunk.snapshotSchedule.String(); got != v { + t.Fatalf("%s prints as %q", v, got) + } + } + for _, v := range []string{"hourly:7", "daily", "daily:0", "daily:x", "weekly:-1", "daily:1001", ""} { + if _, err := parseFlags(chunk("--chunk-snapshot-schedule=" + v)); err == nil { + t.Fatalf("%q accepted", v) + } + } + if _, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-snapshot-schedule=weekly:4")); err == nil { + t.Fatal("--chunk-snapshot-schedule accepted without walstore-chunk") + } +} diff --git a/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go b/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go new file mode 100644 index 0000000000..1d24f4395a --- /dev/null +++ b/seaweed-block/cmd/blockvolume/chunk_rf1_guard_test.go @@ -0,0 +1,77 @@ +package main + +import ( + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A walstore-chunk volume is RF1 only: a chunk cut takes its LSN from the local +// WAL head, which replicas may not hold. A direct start must refuse replication +// (the master's workspace RPCs already do). +func TestChunkVolumeRefusesReplicationAckAtStart(t *testing.T) { + base := []string{"--master", "127.0.0.1:1", "--server-id", "node-a", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:9100", "--ctrl-addr", "127.0.0.1:9101"} + chunk := append(append([]string{}, base...), "--durable-root", t.TempDir(), "--durable-impl", "walstore-chunk", "--workspace-lease", "--chunk-filer", "127.0.0.1:18888") + for _, ack := range []string{"sync-quorum", "sync-all"} { + _, err := parseFlags(append(append([]string{}, chunk...), "--replication-ack", ack)) + if err == nil || !strings.Contains(err.Error(), "single-replica") || !strings.Contains(err.Error(), "RF1 only") { + t.Fatalf("walstore-chunk with --replication-ack=%s: %v", ack, err) + } + } + if _, err := parseFlags(append(append([]string{}, chunk...), "--replication-ack", "best-effort")); err != nil { + t.Fatalf("walstore-chunk best-effort refused: %v", err) + } + if _, err := parseFlags(append(append([]string{}, base...), "--durable-root", t.TempDir(), "--durable-impl", "walstore", "--replication-ack", "sync-quorum")); err != nil { + t.Fatalf("walstore sync-quorum refused: %v", err) + } +} + +// The replication factor arrives with the master's assignment. The host refuses +// roles with replica slots (core/host/volume RF1Only, from hostConfig); the +// ingress gate refuses them again and opens neither inbound lane (legacy and +// dual-lane ports). A primary role without peers (RF1) is admitted. +func TestChunkVolumeIngressRefusesReplicaSlots(t *testing.T) { + for _, row := range []struct{ impl, mode string }{{"walstore", "legacy"}, {"walstore", "dual-lane"}, {"walstore-chunk", "legacy"}, {"walstore-chunk", "dual-lane"}} { + impl, dualLane := row.impl, row.mode == "dual-lane" + t.Run(row.impl+"/"+row.mode, func(t *testing.T) { + addr, dual := ingressPair(t) + f := flags{dataAddr: addr, volumeID: "v1", durableImpl: impl, recoveryMode: row.mode} + if got, want := hostConfig(f, nil).RF1Only, map[string]string{"walstore": "", "walstore-chunk": chunkRF1Reason}[impl]; got != want { + t.Fatalf("host config RF1Only = %q, want %q", got, want) + } + r := newReplicationIngress(f, storage.NewBlockStore(4, 4096)) + defer r.Stop() + admitErr := r.AdmitAsReplica(1) + if impl == "walstore" { + if admitErr != nil || r.listener == nil || (r.dual != nil) != dualLane { + t.Fatalf("walstore replica role (%s): %v", row.mode, admitErr) + } + return + } + if admitErr == nil || !strings.Contains(admitErr.Error(), "refuses a replica role") || !strings.Contains(admitErr.Error(), "RF1 only") { + t.Fatalf("replica role admitted: %v", admitErr) + } + if err := r.FenceAsPrimaryWithPeers(2, true); err == nil || !strings.Contains(err.Error(), "refuses a primary role with replica peers") { + t.Fatalf("primary with peers admitted: %v", err) + } + if err := r.FenceAsPrimary(3); err == nil { + t.Fatal("legacy primary fence (peers assumed) admitted") + } + if r.listener != nil || r.dual != nil { + t.Fatal("an inbound listener was created") + } + for _, a := range []string{addr, dual} { + if err := ingressPortReleased(a); err != nil { + t.Fatal(err) + } + } + if err := r.FenceAsPrimaryWithPeers(4, false); err != nil { + t.Fatalf("RF1 primary refused: %v", err) + } + if r.listener != nil || r.dual != nil { + t.Fatal("the RF1 primary role opened an inbound listener") + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/cleaning_default_test.go b/seaweed-block/cmd/blockvolume/cleaning_default_test.go new file mode 100644 index 0000000000..1e617dfac4 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cleaning_default_test.go @@ -0,0 +1,193 @@ +package main + +import ( + "bytes" + "context" + "fmt" + "path" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" + "github.com/seaweedfs/seaweed-block/core/host/volume" +) + +type cleaningView struct{} + +func (cleaningView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1, Healthy: true} +} + +// With the shipped defaults (no cleaning flag, the hour-long maintenance +// interval), rolling writes with one snapshot kept: after each snapshot +// delete through the holder's control route, the holder's cleaning removes +// the deleted snapshot's chunks, so the pool returns to the chunks the +// current root names and stops growing. +func TestDefaultConfigCleansAfterEachSnapshotDelete(t *testing.T) { + ctx := context.Background() + d, err := parseFlags(append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1")) + if err != nil { + t.Fatal(err) + } + const blocks, chunkBlocks = 256, 16 + const chunks = blocks / chunkBlocks + fixture := testutil.NewLayoutFixture(t, "v1", blocks, chunkBlocks) + pool := path.Join("/provider-test", fixture.Ref.Dir(), layout.PoolDir) + // A real filer lists the shard directory it created for the chunks; the + // in-memory filer keeps only the entries, so add it. + if err := fixture.Filer.CreateEntry(ctx, pool, &filerpb.Entry{Name: "0", IsDirectory: true}, false); err != nil { + t.Fatal(err) + } + cfg := durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: blocks, ChunkBlocks: chunkBlocks, + ChunkMaintenanceInterval: d.chunk.maintenanceInterval, + } + fixture.Configure(&cfg) + var dp *durable.DurableProvider + cfg.ChunkMaintenance = newChunkMaintenance(fixture.Catalog, fixture.Ref, func(ctx context.Context) (layoutCleaner, error) { + r, err := dp.LayoutRemote(ctx, "v1") + if err != nil { + return nil, err + } + return r.(layoutCleaner), nil + }, d.chunk.automaticGC, time.Now) + dp, err = durable.NewDurableProvider(cfg, cleaningView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dp.Close() }) + s, err := dp.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err := dp.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + ctl := volume.NewChunkControl(dp, fixture.Catalog, fixture.Ref) + poolObjects := func() int { + t.Helper() + es, err := fixture.Filer.ListEntries(ctx, pool+"/0", "", "", 100000) + if err != nil { + t.Fatal(err) + } + return len(es) + } + prev := "" + for round := 0; round < 4; round++ { + // Every chunk changes: the new snapshot names none of the old chunks. + for c := uint64(0); c < chunks; c++ { + if _, err := s.Write(uint32(c*chunkBlocks), bytes.Repeat([]byte{byte(round*chunks + int(c) + 1)}, 4096)); err != nil { + t.Fatal(err) + } + } + name := fmt.Sprintf("s%d", round) + if _, err := ctl.Snapshot(ctx, "v1", volume.ChunkSnapshotRequest{Name: name}); err != nil { + t.Fatalf("round %d: snapshot: %v", round, err) + } + if prev != "" { + // The kept snapshot and the current root name the new chunks; + // the one about to be deleted alone names the old ones. + if before := poolObjects(); before != 2*chunks { + t.Fatalf("round %d: %d pool objects before deleting %s; want %d (old and new chunks)", round, before, prev, 2*chunks) + } + if _, err := ctl.DeleteSnapshot(ctx, "v1", prev); err != nil { + t.Fatalf("round %d: delete %s: %v", round, prev, err) + } + deadline := time.Now().Add(10 * time.Second) + for poolObjects() != chunks && time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + } + if got := poolObjects(); got != chunks { + t.Fatalf("round %d: %d pool objects 10 s after deleting %s; want the %d the current root names", round, got, prev, chunks) + } + } + prev = name + } +} + +// A cut through the holder's control route while the holder's cleaning runs +// on the same remote: the cut cancels the cleaning (its run sees its context +// end) and completes; HEAD carries the cut and no open cleaning. +func TestCutDuringTheHoldersCleaningCancelsIt(t *testing.T) { + ctx := context.Background() + fixture := testutil.NewLayoutFixture(t, "v1", 256, 16) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16} + fixture.Configure(&cfg) + dp, err := durable.NewDurableProvider(cfg, cleaningView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dp.Close() }) + s, err := dp.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err := dp.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if _, err := s.Write(1, bytes.Repeat([]byte{7}, 4096)); err != nil { + t.Fatal(err) + } + r, err := dp.LayoutRemote(ctx, "v1") + if err != nil { + t.Fatal(err) + } + cleaner := r.(layoutCleaner) + // The cleaning runs under its own context: cleanup cancels it and joins + // it, so a failure below never leaves it running. + cleanCtx, cleanCancel := context.WithCancel(ctx) + started, cancelled := make(chan struct{}), make(chan struct{}) + cleaned, joined := make(chan error, 1), make(chan struct{}) + go func() { + defer close(joined) + cleaned <- cleaner.Clean(cleanCtx, func(ctx context.Context, _ layout.HolderID, _ string) error { + close(started) + <-ctx.Done() // a cleaning pass in progress until the cut ends it + close(cancelled) + return ctx.Err() + }) + }() + t.Cleanup(func() { + cleanCancel() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("the cleaning did not end after its context was cancelled") + } + }) + select { + case <-started: + case err := <-cleaned: + t.Fatalf("the cleaning ended before it ran: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("the cleaning did not start") + } + ctl := volume.NewChunkControl(dp, fixture.Catalog, fixture.Ref) + cutCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + res, err := ctl.Cut(cutCtx, "v1", 0) + if err != nil { + t.Fatalf("the cut during the cleaning: %v", err) + } + select { + case <-cancelled: + case <-time.After(5 * time.Second): + t.Fatal("the cut did not cancel the cleaning") + } + select { + case err := <-cleaned: + if err != nil { + t.Fatalf("the cancelled cleaning ended with %v; want a clean end", err) + } + case <-time.After(5 * time.Second): + t.Fatal("the cancelled cleaning did not return") + } + h, _, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil || h.Activity.Kind != layout.ActIdle || h.Position < res.CutLSN { + t.Fatalf("HEAD after the cut: %+v (cut to %d) %v; want idle at the cut", h.Activity, res.CutLSN, err) + } +} diff --git a/seaweed-block/cmd/blockvolume/cpuprofile.go b/seaweed-block/cmd/blockvolume/cpuprofile.go new file mode 100644 index 0000000000..24656f7b47 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cpuprofile.go @@ -0,0 +1,75 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "runtime/pprof" + "sync" +) + +// cpuProfileEnv names the directory for on-demand CPU profiles (diagnostics). +// Empty (the default) leaves blockvolume unchanged: no signal handler is +// installed and nothing is written. Set, SIGUSR1 starts a CPU profile into +// /blockvolume--.pprof and the next SIGUSR1 stops it, so a +// harness can profile a running volume without a port or a restart. +const cpuProfileEnv = "SWBLOCK_CPU_PROFILE_DIR" + +// cpuProfiler toggles one CPU profile at a time. +type cpuProfiler struct { + dir string + mu sync.Mutex + f *os.File + n int +} + +// toggle starts a profile when none runs, else stops the running one. It +// returns the profile's path and whether a profile now runs. +func (p *cpuProfiler) toggle() (string, bool, error) { + p.mu.Lock() + defer p.mu.Unlock() + if p.f != nil { + path := p.f.Name() + pprof.StopCPUProfile() + err := p.f.Close() + p.f = nil + return path, false, err + } + p.n++ + path := filepath.Join(p.dir, fmt.Sprintf("blockvolume-%d-%d.pprof", os.Getpid(), p.n)) + f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) + if err != nil { + return path, false, err + } + if err := pprof.StartCPUProfile(f); err != nil { + _ = f.Close() + _ = os.Remove(path) + return path, false, err + } + p.f = f + return path, true, nil +} + +// stop ends a running profile (at shutdown), keeping what it recorded. +func (p *cpuProfiler) stop() { + p.mu.Lock() + defer p.mu.Unlock() + if p.f != nil { + pprof.StopCPUProfile() + _ = p.f.Close() + p.f = nil + } +} + +// checkCPUProfileDir refuses a profile directory that is not an existing +// directory, at startup rather than at the first signal. +func checkCPUProfileDir(dir string) error { + fi, err := os.Stat(dir) + if err != nil { + return fmt.Errorf("--cpu-profile-dir %s: %w", dir, err) + } + if !fi.IsDir() { + return fmt.Errorf("--cpu-profile-dir %s: not a directory", dir) + } + return nil +} diff --git a/seaweed-block/cmd/blockvolume/cpuprofile_other.go b/seaweed-block/cmd/blockvolume/cpuprofile_other.go new file mode 100644 index 0000000000..b90c365ff1 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cpuprofile_other.go @@ -0,0 +1,15 @@ +//go:build !unix + +package main + +import "errors" + +// cpuProfileSupported: no SIGUSR1 on this platform. +const cpuProfileSupported = false + +func startCPUProfileSignal(dir string) (stop func(), err error) { + if dir == "" { + return func() {}, nil + } + return nil, errors.New("--cpu-profile-dir needs SIGUSR1 (unix only)") +} diff --git a/seaweed-block/cmd/blockvolume/cpuprofile_test.go b/seaweed-block/cmd/blockvolume/cpuprofile_test.go new file mode 100644 index 0000000000..aac5a77d11 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cpuprofile_test.go @@ -0,0 +1,58 @@ +package main + +import ( + "os" + "path/filepath" + "testing" +) + +// The profile directory comes from --cpu-profile-dir, defaulting to +// $SWBLOCK_CPU_PROFILE_DIR; unset means off. +func TestCPUProfileDirFlagDefaultsFromEnv(t *testing.T) { + base := []string{"--master", "127.0.0.1:1", "--server-id", "h1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:2", "--ctrl-addr", "127.0.0.1:3"} + t.Setenv(cpuProfileEnv, "") + if f, err := parseFlags(base); err != nil || f.cpuProfileDir != "" { + t.Fatalf("default: %q %v; want off", f.cpuProfileDir, err) + } + dir := t.TempDir() + t.Setenv(cpuProfileEnv, dir) + f, err := parseFlags(base) + other := t.TempDir() + fx, errx := parseFlags(append(append([]string{}, base...), "--cpu-profile-dir", other)) + if !cpuProfileSupported { + // No SIGUSR1 here: a set directory is refused in flag parsing. + if err == nil || errx == nil { + t.Fatalf("unsupported platform accepted a profile dir: env %v, flag %v", err, errx) + } + return + } + if err != nil || f.cpuProfileDir != dir { + t.Fatalf("from env: %q %v; want %q", f.cpuProfileDir, err, dir) + } + if errx != nil || fx.cpuProfileDir != other { + t.Fatalf("explicit flag: %q %v; want %q", fx.cpuProfileDir, errx, other) + } +} + +// A profile directory that is not an existing directory is refused before +// any signal arrives. +func TestCPUProfileDirMustBeAnExistingDirectory(t *testing.T) { + if err := checkCPUProfileDir(filepath.Join(t.TempDir(), "missing")); err == nil { + t.Fatal("a missing directory was accepted") + } + file := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(file, nil, 0o644); err != nil { + t.Fatal(err) + } + if err := checkCPUProfileDir(file); err == nil { + t.Fatal("a file was accepted as the profile directory") + } + if err := checkCPUProfileDir(t.TempDir()); err != nil { + t.Fatalf("an existing directory was refused: %v", err) + } + // The refusal happens in parseFlags, before run() activates anything. + base := []string{"--master", "127.0.0.1:1", "--server-id", "h1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:2", "--ctrl-addr", "127.0.0.1:3"} + if _, err := parseFlags(append(append([]string{}, base...), "--cpu-profile-dir", file)); err == nil { + t.Fatal("parseFlags accepted a file as the profile directory") + } +} diff --git a/seaweed-block/cmd/blockvolume/cpuprofile_unix.go b/seaweed-block/cmd/blockvolume/cpuprofile_unix.go new file mode 100644 index 0000000000..6d182b80ce --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cpuprofile_unix.go @@ -0,0 +1,56 @@ +//go:build unix + +package main + +import ( + "log" + "os" + "os/signal" + "syscall" +) + +// cpuProfileSupported: SIGUSR1 exists here. +const cpuProfileSupported = true + +// startCPUProfileSignal makes SIGUSR1 toggle a CPU profile into dir. The +// returned stop removes the handler, stops and joins the worker (so no +// buffered signal can start a profile after it), then writes out a running +// profile. dir "" installs nothing. +func startCPUProfileSignal(dir string) (stop func(), err error) { + if dir == "" { + return func() {}, nil + } + if err := checkCPUProfileDir(dir); err != nil { + return nil, err + } + p := &cpuProfiler{dir: dir} + sig := make(chan os.Signal, 1) + signal.Notify(sig, syscall.SIGUSR1) + quit, done := make(chan struct{}), make(chan struct{}) + go func() { + defer close(done) + for { + select { + case <-quit: + return + case <-sig: + path, running, err := p.toggle() + switch { + case err != nil: + log.Printf("blockvolume: cpu profile %s: %v", path, err) + case running: + log.Printf("blockvolume: cpu profile started: %s (SIGUSR1 again stops it)", path) + default: + log.Printf("blockvolume: cpu profile written: %s", path) + } + } + } + }() + log.Printf("blockvolume: SIGUSR1 toggles a CPU profile into %s", dir) + return func() { + signal.Stop(sig) + close(quit) + <-done + p.stop() + }, nil +} diff --git a/seaweed-block/cmd/blockvolume/cpuprofile_unix_test.go b/seaweed-block/cmd/blockvolume/cpuprofile_unix_test.go new file mode 100644 index 0000000000..1c965f79d4 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cpuprofile_unix_test.go @@ -0,0 +1,144 @@ +//go:build unix + +package main + +import ( + "bytes" + "compress/gzip" + "io" + "os" + "path/filepath" + "runtime/pprof" + "sort" + "syscall" + "testing" + "time" +) + +func profiles(t *testing.T, dir string) []string { + t.Helper() + m, err := filepath.Glob(filepath.Join(dir, "blockvolume-*.pprof")) + if err != nil { + t.Fatal(err) + } + sort.Strings(m) + return m +} + +func waitUntil(t *testing.T, what string, ok func() bool) { + t.Helper() + end := time.Now().Add(10 * time.Second) + for !ok() { + if time.Now().After(end) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(20 * time.Millisecond) + } +} + +func burn(d time.Duration) { + x := 0 + for end := time.Now().Add(d); time.Now().Before(end); { + x++ + } + _ = x +} + +// complete reports whether path holds a whole gzip stream (a written-out +// pprof profile): a truncated or still-open profile fails to decompress. +func complete(path string) bool { + b, err := os.ReadFile(path) + if err != nil || len(b) == 0 { + return false + } + zr, err := gzip.NewReader(bytes.NewReader(b)) + if err != nil { + return false + } + out, err := io.ReadAll(zr) + return err == nil && len(out) > 0 +} + +// noProfileRunning reports whether no CPU profile is active in this process. +func noProfileRunning(t *testing.T) bool { + t.Helper() + if err := pprof.StartCPUProfile(io.Discard); err != nil { + return false + } + pprof.StopCPUProfile() + return true +} + +func usr1(t *testing.T) { + t.Helper() + if err := syscall.Kill(os.Getpid(), syscall.SIGUSR1); err != nil { + t.Fatal(err) + } +} + +// With a profile directory, SIGUSR1 starts a CPU profile and the next +// SIGUSR1 writes it out as a complete pprof; a second pair writes a second +// file. stop writes out a profile still running. +func TestCPUProfileSIGUSR1TogglesAProfile(t *testing.T) { + dir := t.TempDir() + stop, err := startCPUProfileSignal(dir) + if err != nil { + t.Fatal(err) + } + stopped := false + defer func() { + if !stopped { + stop() + } + }() + for cycle := 1; cycle <= 2; cycle++ { + usr1(t) + waitUntil(t, "profile file created", func() bool { return len(profiles(t, dir)) == cycle }) + burn(200 * time.Millisecond) + usr1(t) + path := profiles(t, dir)[cycle-1] + waitUntil(t, "profile "+path+" written", func() bool { return complete(path) }) + } + usr1(t) + waitUntil(t, "third profile file created", func() bool { return len(profiles(t, dir)) == 3 }) + burn(100 * time.Millisecond) + stop() + stopped = true + if p := profiles(t, dir)[2]; !complete(p) { + t.Fatalf("stop did not write out the running profile %s", p) + } + if !noProfileRunning(t) { + t.Fatal("a CPU profile is still running after stop") + } +} + +// A SIGUSR1 delivered just before stop cannot leave a profile running after +// it: stop joins the worker before the final write-out. +func TestCPUProfileStopJoinsTheWorker(t *testing.T) { + for i := 0; i < 20; i++ { + dir := t.TempDir() + stop, err := startCPUProfileSignal(dir) + if err != nil { + t.Fatal(err) + } + usr1(t) + stop() + if !noProfileRunning(t) { + t.Fatalf("round %d: a profile was running after stop returned", i) + } + for _, p := range profiles(t, dir) { + if !complete(p) { + t.Fatalf("round %d: %s left incomplete after stop", i, p) + } + } + } +} + +// Off (no directory): nothing is installed and nothing is written. +func TestCPUProfileOffInstallsNothing(t *testing.T) { + stop, err := startCPUProfileSignal("") + if err != nil || stop == nil { + t.Fatalf("off: %v", err) + } + stop() +} diff --git a/seaweed-block/cmd/blockvolume/creation_gap_integration_test.go b/seaweed-block/cmd/blockvolume/creation_gap_integration_test.go new file mode 100644 index 0000000000..b2c1bd79dc --- /dev/null +++ b/seaweed-block/cmd/blockvolume/creation_gap_integration_test.go @@ -0,0 +1,103 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// TestAVolumeThatServedBeforeItsFirstGateTickFailsOver is the creation +// phase's gap, through the production binaries: an RF3 sync-quorum volume +// whose primary serves and acknowledges a write right after its stores are +// attested, and dies before the master's next product tick could read a +// ready answer from it. The volume served, so its creation ended (the +// survivors hold the write): the gate fails it over, and the write reads +// back on the new primary. A master that ended creation only at the +// primary's ready answer would hold this volume as creating for good. +// +// The product loop ticks every 30 s, so the tick that binds the line and the +// next one leave a window the test uses (and checks it did). +func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) { + bins := buildG54Binaries(t) + h := &plannedHandoffHarness{dir: t.TempDir(), t: t} + h.masterAddr = handoffAddress(t) + type host struct { + id, rid, data, ctrl, status, nvme, root string + d *daemon + } + hosts := make([]*host, 3) + var nodes, placements strings.Builder + for i := range hosts { + id := fmt.Sprintf("s%d", i+1) + hosts[i] = &host{id: id, rid: fmt.Sprintf("r%d", i+1), data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t), root: filepath.Join(h.dir, "vol-"+id)} + fmt.Fprintf(&nodes, " - server_id: %s\n data_addr: %s\n ctrl_addr: %s\n", id, hosts[i].data, hosts[i].ctrl) + fmt.Fprintf(&placements, " - server_id: %s\n replica_id: %s\n", id, hosts[i].rid) + } + spec := filepath.Join(h.dir, "cluster-spec.yaml") + if err := os.WriteFile(spec, []byte("nodes:\n"+nodes.String()+"volumes:\n - id: v1\n size_bytes: 268435456\n replication_factor: 3\n placements:\n"+placements.String()), 0o644); err != nil { + t.Fatal(err) + } + master := h.start(t, "blockmaster", bins.master, + "--authority-store", filepath.Join(h.dir, "master", "authority"), "--lifecycle-store", filepath.Join(h.dir, "master", "lifecycle"), + "--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", "30s", + "--freshness-window", "2s", "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr) + master.waitLog(t, 30*time.Second, "blockmaster: lock acquired") + for _, b := range hosts { + lockDir := b.root + ".locks" + if err := os.MkdirAll(lockDir, 0o700); err != nil { + t.Fatal(err) + } + b.d = h.start(t, "blockvolume-"+b.id, bins.volume, "--volume-lock-dir-test-only", lockDir, "--master", h.masterAddr, + "--server-id", b.id, "--volume-id", "v1", "--replica-id", b.rid, "--data-addr", b.data, "--ctrl-addr", b.ctrl, + "--status-addr", b.status, "--durable-root", b.root, "--durable-impl", "walstore", "--durable-blocks", "65536", + "--durable-blocksize", "4096", "--heartbeat-interval", "200ms", "--t1-readiness", "--replication-ack", "sync-quorum", + "--nvme-listen", b.nvme, "--nvme-subsysnqn", plannedHandoffNQN) + } + ended := func() bool { return master.has("blockmaster: volume=v1 creation complete") } + + // 1. r1 serves at epoch 1 with both replicas counted (its stores are + // attested); block A is written and flushed (acknowledged by the quorum). + p1, survivors := hosts[0], hosts[1:] + h.waitPrimaryAt(t, p1.status, 1) + waitPeersHealthyAt(t, p1.status, 1, survivors[0].rid, survivors[1].rid) + acked := bytes.Repeat([]byte{0xa1}, 4096) + c := dialNVMe(t, p1.nvme, plannedHandoffNQN) + c.write(t, 0, acked) + c.flush(t) // the acknowledgement + c.close() + + // 2. r1 dies before any tick read a ready answer from it. + if ended() { + t.Fatal("fixture: a tick ended creation before the primary died (the window this test needs did not occur)") + } + p1.d.kill(t) + + // 3. The next tick reads the survivors' write: creation ended, and the + // gate fails the volume over. + var p2 *host + poll(t, 120*time.Second, "no survivor became primary at epoch 2 (the volume held as creating?)", func() bool { + for _, b := range survivors { + if statusIsPrimaryAt(b.status, 2) { + p2 = b + return true + } + } + return false + }) + if !master.has("creation complete: survivor") { + t.Fatal("creation did not end on the survivors' write") + } + + // 4. The acknowledged write reads back on the new primary. + r := dialNVMe(t, p2.nvme, plannedHandoffNQN) + defer r.close() + if got := r.read(t, 0, len(acked)); !bytes.Equal(got, acked) { + t.Fatalf("the acknowledged write did not read back on %s", p2.rid) + } +} diff --git a/seaweed-block/cmd/blockvolume/cutover_end_to_end_integration_test.go b/seaweed-block/cmd/blockvolume/cutover_end_to_end_integration_test.go new file mode 100644 index 0000000000..4fa83dfe20 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cutover_end_to_end_integration_test.go @@ -0,0 +1,89 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "syscall" + "testing" + "time" +) + +// TestCutoverCreateFromSnapshot pins the public master create contract: one +// request creates the target identity and its restored image together. +func TestCutoverCreateFromSnapshot(t *testing.T) { + env := startCutoverLayoutEnv(t, false) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + source := startCutoverVolume(t, env, "restore-source", "s1") + env.adopt(t, source, "s1") + env.writeBlock(t, "s1", 5, pattern("restore-seam-A!!")) + env.snapshot(t, "s1", "v1", "restore-seam") + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "restore-seam", "--target", "v2", + "--master", env.h.masterAddr) + target := startCutoverVolume(t, env, "restored-target", "n-v2") + target.waitLog(t, 60*time.Second, "blockvolume: volume v2 adopted as PRIMARY at r1@") + poll(t, 60*time.Second, "restored target never ready", func() bool { return volumeFrontendReady(env.hosts["n-v2"].status, "v2") }) + env.requireBlocks(t, "n-v2", 0, ladderLastBlock+1, map[uint64][]byte{5: pattern("restore-seam-A!!")}) +} + +// TestCutoverWriteSnapshotKillRestartRestore follows the public path through +// real binaries, a stock filer and the NVMe frontend. The guest is quiescent +// at snapshot and kill; process kill is not a power-loss durability claim. +func TestCutoverWriteSnapshotKillRestartRestore(t *testing.T) { + env := startCutoverLayoutEnv(t, false) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + source := startCutoverVolume(t, env, "source-before-kill", "s1") + env.adopt(t, source, "s1") + a, b, c := pattern("cutover-block-A!"), pattern("cutover-block-B!"), pattern("cutover-block-C!") + before := map[uint64][]byte{5: a, 2*ladderChunkBlocks + 7: b} + env.writeBlock(t, "s1", 5, a) + env.writeBlock(t, "s1", 2*ladderChunkBlocks+7, b) + env.snapshot(t, "s1", "v1", "before-kill") + // A later synced write must survive restart but must not enter the snapshot. + env.writeBlock(t, "s1", 4*ladderChunkBlocks+9, c) + source.kill(t) + if err := source.proc.Signal(syscall.Signal(0)); err == nil { + t.Fatal("the killed source process still exists") + } + restarted := startCutoverVolume(t, env, "source-after-kill", "s1") + env.adopt(t, restarted, "s1") + after := map[uint64][]byte{5: a, 2*ladderChunkBlocks + 7: b, 4*ladderChunkBlocks + 9: c} + env.requireBlocks(t, "s1", 0, ladderLastBlock+1, after) + env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "before-kill", "--target", "v2", + "--master", env.h.masterAddr) + target := startCutoverVolume(t, env, "restored-target", "n-v2") + target.waitLog(t, 60*time.Second, "blockvolume: volume v2 adopted as PRIMARY at r1@") + poll(t, 60*time.Second, "restored target never ready", func() bool { return volumeFrontendReady(env.hosts["n-v2"].status, "v2") }) + env.requireBlocks(t, "n-v2", 0, ladderLastBlock+1, before) + env.requireBlocks(t, "s1", 0, ladderLastBlock+1, after) +} + +// The initiator's deadline bounds each command, not the connection's life: a +// full-volume read loop on a slow host outlasts any fixed bound set at dial. +// A connection idle for longer than the deadline still reads. +func TestNVMeInitiatorDeadlineBoundsEachCommand(t *testing.T) { + env := startCutoverLayoutEnv(t, false) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + source := startCutoverVolume(t, env, "deadline-source", "s1") + env.adopt(t, source, "s1") + env.writeBlock(t, "s1", 5, pattern("deadline-block-A")) + old := nvmeIODeadline + nvmeIODeadline = 2 * time.Second + t.Cleanup(func() { nvmeIODeadline = old }) + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + defer c.close() + time.Sleep(2500 * time.Millisecond) + if got := c.read(t, 5, 4096); !bytes.Equal(got, pattern("deadline-block-A")) { + t.Fatal("the block read after the idle period differs") + } +} + +func startCutoverLayoutEnv(t *testing.T, precreateTarget bool) *handoffEnv { + t.Helper() + return startHandoffEnvConfigured(t, 1, []string{"v2"}, procedureTLSConfig(), precreateTarget) +} + +func startCutoverVolume(t *testing.T, env *handoffEnv, label, host string) *daemon { + t.Helper() + return env.h.start(t, label, env.h.volume, env.volArgs(host)...) +} diff --git a/seaweed-block/cmd/blockvolume/delete_output_contract_test.go b/seaweed-block/cmd/blockvolume/delete_output_contract_test.go new file mode 100644 index 0000000000..4a5f98e4c2 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/delete_output_contract_test.go @@ -0,0 +1,45 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestDeleteNoRevokeKeepsTheTypedStdoutSeparate(t *testing.T) { + for _, tc := range []struct { + name, stdout, stderr string + code int + completed bool + }{ + {"completed-with-diagnostics", `{"volume":"v3-12345678","state":"deleted"}`, "layout: HEAD write level=INFO", 0, true}, + {"completed-retry-with-diagnostics", `{"volume":"v3-12345678","state":"deleted","already_deleted_roots":["old"]}`, "layout: HEAD write level=INFO", 0, true}, + {"malformed-success-is-not-completed", `not JSON`, "layout: HEAD write level=INFO", 0, false}, + {"refusal-retains-diagnostics", ``, "not_admitted: live until 2026-11-29T05:12:42Z", 1, false}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + cli := filepath.Join(dir, "answer-cli") + script := fmt.Sprintf("#!/bin/sh\nprintf '%%s\\n' '%s'\nprintf '%%s\\n' '%s' >&2\nexit %d\n", tc.stdout, tc.stderr, tc.code) + if err := os.WriteFile(cli, []byte(script), 0700); err != nil { + t.Fatal(err) + } + env := &handoffEnv{h: &plannedHandoffHarness{dir: dir, cli: cli, t: t}, cluster: &w4WeedCluster{}} + out, code := env.deleteNoRevoke(context.Background(), "v3", "del-v3") + if code != tc.code || handoffDeleteCompleted(out) != tc.completed { + t.Fatalf("exit%d completed%v; want exit%d completed%v: %s", code, handoffDeleteCompleted(out), tc.code, tc.completed, out) + } + if code == 0 && strings.TrimSpace(out) != tc.stdout { + t.Fatalf("successful typed answer includes diagnostics: %q", out) + } + if code != 0 && !strings.Contains(out, tc.stderr) { + t.Fatalf("refusal lost its reason: %q", out) + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/diskfull_verdict_test.go b/seaweed-block/cmd/blockvolume/diskfull_verdict_test.go new file mode 100644 index 0000000000..ff8eebb9a7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/diskfull_verdict_test.go @@ -0,0 +1,42 @@ +package main_test + +import ( + "fmt" + "strings" + "testing" +) + +// diskFullVerdict decides a defect row. A known defect that still reproduces +// passes; an unknown one fails; a known one that no longer reproduces fails +// too, so the list cannot go stale and hide a later regression. +func diskFullVerdict(known map[int]bool, issue int, bad bool, msg string) (fail bool, line string) { + switch { + case bad && known[issue]: + return false, fmt.Sprintf("KNOWN FINDING #%d: %s", issue, msg) + case bad: + return true, fmt.Sprintf("FINDING #%d: %s", issue, msg) + case known[issue]: + return true, fmt.Sprintf("FIXED #%d: no longer reproduces; remove it from knownDiskFullFindings so this row is strict", issue) + } + return false, "" +} + +func TestDiskFullVerdict(t *testing.T) { + known := map[int]bool{1: true} + for _, c := range []struct { + issue int + bad bool + fail bool + line string + }{ + {1, true, false, "KNOWN FINDING #1"}, + {1, false, true, "FIXED #1"}, + {2, true, true, "FINDING #2"}, + {2, false, false, ""}, + } { + fail, line := diskFullVerdict(known, c.issue, c.bad, "m") + if fail != c.fail || !strings.HasPrefix(line, c.line) || (c.line == "" && line != "") { + t.Errorf("issue %d bad %v: fail=%v line=%q", c.issue, c.bad, fail, line) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/double_failover_integration_test.go b/seaweed-block/cmd/blockvolume/double_failover_integration_test.go new file mode 100644 index 0000000000..e87c5d19d5 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/double_failover_integration_test.go @@ -0,0 +1,219 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// TestDoubleFailoverReadsBackEveryAckedWrite runs two failovers of an RF3 +// sync-quorum volume through the production binaries and reads back every +// acknowledged write on the last primary: +// +// 1. r1 serves at epoch 1; block A is written and flushed (acknowledged). +// 2. r1 is killed. The gate fences the two survivors at 2 and promotes one +// of them (P2); block B is written and flushed on P2. +// 3. r1 restarts and rejoins P2 at epoch 2 as a healthy replica. At RF3 +// sync_quorum a fenced decision needs two survivors, so without the +// rejoin the second failover could not be decided. +// 4. P2 is killed. The gate fences the two survivors at 3 and promotes one +// of them (P3); block C is written and flushed on P3. +// 5. A, B and C all read back on P3. +func TestDoubleFailoverReadsBackEveryAckedWrite(t *testing.T) { + bins := buildG54Binaries(t) + h := &plannedHandoffHarness{dir: t.TempDir(), t: t} + h.masterAddr = handoffAddress(t) + type host struct { + id, rid, data, ctrl, status, nvme, root string + d *daemon + args []string + } + hosts := make([]*host, 3) + var nodes, placements strings.Builder + for i := range hosts { + id := fmt.Sprintf("s%d", i+1) + hosts[i] = &host{id: id, rid: fmt.Sprintf("r%d", i+1), data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t), root: filepath.Join(h.dir, "vol-"+id)} + fmt.Fprintf(&nodes, " - server_id: %s\n data_addr: %s\n ctrl_addr: %s\n", id, hosts[i].data, hosts[i].ctrl) + fmt.Fprintf(&placements, " - server_id: %s\n replica_id: %s\n", id, hosts[i].rid) + } + spec := filepath.Join(h.dir, "cluster-spec.yaml") + if err := os.WriteFile(spec, []byte("nodes:\n"+nodes.String()+"volumes:\n - id: v1\n size_bytes: 268435456\n replication_factor: 3\n placements:\n"+placements.String()), 0o644); err != nil { + t.Fatal(err) + } + master := h.start(t, "blockmaster", bins.master, + "--authority-store", filepath.Join(h.dir, "master", "authority"), "--lifecycle-store", filepath.Join(h.dir, "master", "lifecycle"), + "--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", "200ms", + "--freshness-window", "2s", "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr) + master.waitLog(t, 30*time.Second, "blockmaster: lock acquired") + for _, b := range hosts { + lockDir := b.root + ".locks" + if err := os.MkdirAll(lockDir, 0o700); err != nil { + t.Fatal(err) + } + b.args = []string{"--volume-lock-dir-test-only", lockDir, "--master", h.masterAddr, "--server-id", b.id, "--volume-id", "v1", + "--replica-id", b.rid, "--data-addr", b.data, "--ctrl-addr", b.ctrl, "--status-addr", b.status, + "--durable-root", b.root, "--durable-impl", "walstore", "--durable-blocks", "65536", "--durable-blocksize", "4096", + "--heartbeat-interval", "200ms", "--t1-readiness", "--replication-ack", "sync-quorum", + "--nvme-listen", b.nvme, "--nvme-subsysnqn", plannedHandoffNQN} + b.d = h.start(t, "blockvolume-"+b.id, bins.volume, b.args...) + } + rids := func(hs []*host) []string { + var out []string + for _, b := range hs { + out = append(out, b.rid) + } + return out + } + others := func(p *host) []*host { + var out []*host + for _, b := range hosts { + if b != p { + out = append(out, b) + } + } + return out + } + // gateSawReady waits until the gate's probe of a ready primary p has + // seen both other replicas ready on the stores p attested. + gateSawReady := func(p *host) { + o := others(p) + poll(t, 60*time.Second, fmt.Sprintf("the gate never saw %s and %s ready behind %s", o[0].rid, o[1].rid, p.rid), func() bool { + data, _ := os.ReadFile(master.log) + for _, l := range strings.Split(string(data), "\n") { + if strings.Contains(l, "promotion gate volume=v1 current="+p.rid) && strings.Contains(l, "{"+o[0].rid+" true") && strings.Contains(l, "{"+o[1].rid+" true") { + return true + } + } + return false + }) + } + // promotedAmong waits for one of cands to serve as primary at epoch. + promotedAmong := func(epoch uint64, cands []*host) *host { + var got *host + poll(t, 120*time.Second, fmt.Sprintf("no survivor became primary at epoch %d", epoch), func() bool { + for _, b := range cands { + if statusIsPrimaryAt(b.status, epoch) { + got = b + return true + } + } + return false + }) + return got + } + writeAcked := func(p *host, lba uint64, fill byte) []byte { + data := bytes.Repeat([]byte{fill}, 4096) + c := dialNVMe(t, p.nvme, plannedHandoffNQN) + defer c.close() + c.write(t, lba, data) + c.flush(t) // the acknowledgement + return data + } + readBack := func(p *host, want []byte, what string) { + c := dialNVMe(t, p.nvme, plannedHandoffNQN) + defer c.close() + if got := c.read(t, 0, len(want)); !bytes.Equal(got, want) { + t.Fatalf("%s did not read back on %s", what, p.rid) + } + } + + // 1. r1 serves at epoch 1 with both replicas healthy; A is acknowledged. + p1 := hosts[0] + h.waitPrimaryAt(t, p1.status, 1) + waitPeersHealthyAt(t, p1.status, 1, rids(others(p1))...) + acked := writeAcked(p1, 0, 0xa1) + readBack(p1, acked, "block A") + gateSawReady(p1) + + // 2. r1 is killed: a survivor is promoted at 2 on a fenced round; B. + p1.d.kill(t) + p2 := promotedAmong(2, others(p1)) + // sync_quorum: B is acknowledged only with the other survivor counted. + for _, b := range others(p1) { + if b != p2 { + waitPeersHealthyAt(t, p2.status, 2, b.rid) + } + } + acked = append(acked, writeAcked(p2, 1, 0xb2)...) + readBack(p2, acked, "blocks A and B") + + // 3. r1 restarts and rejoins P2 at epoch 2 (two survivors are needed + // for the next fenced decision). + p1.d = h.start(t, "blockvolume-"+p1.id+"-restart", bins.volume, p1.args...) + waitPeersHealthyAt(t, p2.status, 2, rids(others(p2))...) + gateSawReady(p2) + + // 4. P2 is killed: a survivor is promoted at 3 on a fenced round; C. + p2.d.kill(t) + p3 := promotedAmong(3, others(p2)) + for _, b := range others(p2) { + if b != p3 { + waitPeersHealthyAt(t, p3.status, 3, b.rid) + } + } + acked = append(acked, writeAcked(p3, 2, 0xc3)...) + + // 5. Every acknowledged write reads back on the last primary. + readBack(p3, acked, "blocks A, B and C") +} + +// statusIsPrimaryAt reports whether the host at statusAddr serves as a +// healthy primary at epoch (an unreachable host is not). +func statusIsPrimaryAt(statusAddr string, epoch uint64) bool { + resp, err := (&http.Client{Timeout: 2 * time.Second}).Get("http://" + statusAddr + "/status?volume=v1") + if err != nil { + return false + } + defer resp.Body.Close() + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + return statusPrimary(b, epoch) +} + +// waitPeersHealthyAt waits until the primary's /status/peers lists every +// replica in rids healthy at epoch: the primary ships to them and counts them. +func waitPeersHealthyAt(t *testing.T, statusAddr string, epoch uint64, rids ...string) { + t.Helper() + c := &http.Client{Timeout: 5 * time.Second} + var last string + end := time.Now().Add(120 * time.Second) + for time.Now().Before(end) { + if resp, err := c.Get("http://" + statusAddr + "/status/peers?volume=v1"); err == nil { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + resp.Body.Close() + last = string(body) + var st struct { + Peers []struct { + ReplicaID string + State string + Epoch uint64 + } + } + if json.Unmarshal(body, &st) == nil { + healthy := map[string]bool{} + for _, p := range st.Peers { + if p.State == "healthy" && p.Epoch == epoch { + healthy[p.ReplicaID] = true + } + } + all := true + for _, r := range rids { + all = all && healthy[r] + } + if all { + return + } + } + } + time.Sleep(200 * time.Millisecond) + } + t.Fatalf("the primary at %s never had %v healthy at epoch %d; last: %s", statusAddr, rids, epoch, last) +} diff --git a/seaweed-block/cmd/blockvolume/dual_lane_addr_test.go b/seaweed-block/cmd/blockvolume/dual_lane_addr_test.go new file mode 100644 index 0000000000..3a62297312 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/dual_lane_addr_test.go @@ -0,0 +1,39 @@ +package main + +import "testing" + +// TestDeriveDualLaneAddr pins the port+1 deployment convention +// (docs/recovery-wiring-plan.md §4 Option A). Production daemons MUST +// agree on this offset until AssignmentFact carries an explicit +// dual-lane field. +func TestDeriveDualLaneAddr(t *testing.T) { + cases := []struct { + in string + want string + wantErr bool + }{ + {"127.0.0.1:9220", "127.0.0.1:9221", false}, + {"127.0.0.1:0", "127.0.0.1:1", false}, + {"[::1]:9220", "[::1]:9221", false}, + {"192.168.1.10:65534", "192.168.1.10:65535", false}, + {"192.168.1.10:65535", "", true}, // overflow + {"no-port-here", "", true}, + {"127.0.0.1:notanumber", "", true}, + } + for _, tc := range cases { + got, err := deriveDualLaneAddr(tc.in) + if tc.wantErr { + if err == nil { + t.Errorf("deriveDualLaneAddr(%q): want error, got %q", tc.in, got) + } + continue + } + if err != nil { + t.Errorf("deriveDualLaneAddr(%q): unexpected err %v", tc.in, err) + continue + } + if got != tc.want { + t.Errorf("deriveDualLaneAddr(%q): got %q want %q", tc.in, got, tc.want) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/durable_impl_default_test.go b/seaweed-block/cmd/blockvolume/durable_impl_default_test.go new file mode 100644 index 0000000000..d1583e4a83 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/durable_impl_default_test.go @@ -0,0 +1,51 @@ +package main + +import ( + "errors" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" +) + +// --durable-impl defaults to empty (auto): new volumes are walstore, and an +// existing volume opens with its on-disk format. +func TestBlockvolumeDurableImplDefaultIsAuto(t *testing.T) { + f, err := parseFlags(phase150RequiredBlockvolumeArgs()) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if f.durableImpl != "" { + t.Fatalf("durableImpl default=%q, want empty (auto)", f.durableImpl) + } +} + +func TestBlockvolumeDurableImplExplicitValues(t *testing.T) { + for _, impl := range []string{"walstore"} { + args := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl="+impl) + f, err := parseFlags(args) + if err != nil { + t.Fatalf("--durable-impl=%s: %v", impl, err) + } + if f.durableImpl != impl { + t.Fatalf("durableImpl=%q, want %q", f.durableImpl, impl) + } + } + args := append(phase150RequiredBlockvolumeArgs(), "--durable-impl=bogus") + if _, err := parseFlags(args); err == nil { + t.Fatal("--durable-impl=bogus accepted") + } +} + +// The removed experimental engines' names are refused typed, with the advice +// an operator acts on; nothing selects them any more. +func TestBlockvolumeRefusesRemovedEngineNames(t *testing.T) { + for _, impl := range []string{"smartwal", "parallel-walstore"} { + args := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl="+impl) + _, err := parseFlags(args) + var removed *durable.RemovedEngineError + if !errors.As(err, &removed) || string(removed.Engine) != impl || !strings.Contains(err.Error(), durable.RemovedEngineAdvice) { + t.Fatalf("--durable-impl=%s: err=%v, want the typed removed-engine refusal", impl, err) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/durable_startup.go b/seaweed-block/cmd/blockvolume/durable_startup.go new file mode 100644 index 0000000000..5aad1df110 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/durable_startup.go @@ -0,0 +1,71 @@ +package main + +import ( + "context" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// durableStartup is the part of the durable provider the startup open +// and replay step uses. +type durableStartup interface { + EnsureStorage(volumeID string) (storage.LogicalStorage, error) + RecoverVolume(ctx context.Context, volumeID string) (durable.RecoveryReport, error) +} + +// localRecoveryHost is the part of the volume host the startup step +// reports to. +type localRecoveryHost interface { + BlockLocalReadiness(reason string) + ClearLocalReadinessBlock() + ReportLocalRecoveryFailure(err error) string +} + +type durableStartupOutcome int + +const ( + durableStartupReady durableStartupOutcome = iota // storage open and replayed + durableStartupFaulted // fail closed, keep serving status and heartbeats + durableStartupFatal // unclassified open failure: exit as before +) + +// openAndRecoverDurable opens the volume's durable storage and replays it +// at startup (#133). On a classifiable failure in either step (open or +// replay), it blocks local readiness, records the typed reason +// (wal_corrupt / io_error) through ReportLocalRecoveryFailure, and returns +// durableStartupFaulted: the process stays up fail-closed, with frontend +// I/O refused, and a primary assignment reports the reason at once. A +// replay failure that cannot be classified is faulted too, as before, and +// is covered by the recovery_stalled fallback. An open failure that +// cannot be classified returns durableStartupFatal, keeping the earlier +// exit. +func openAndRecoverDurable(dp durableStartup, h localRecoveryHost, volumeID string, _ time.Duration) (durableStartupOutcome, string, error) { + if _, err := dp.EnsureStorage(volumeID); err != nil { + if volume.LocalRecoveryHealthReason(err) == "" { + return durableStartupFatal, "", err + } + evidence := "durable storage open failed: " + err.Error() + h.BlockLocalReadiness(evidence) + h.ReportLocalRecoveryFailure(err) + return durableStartupFaulted, evidence, err + } + // The host owns the shared inactivity clock. Volume-sized local replay + // must not consume an attach operation's fixed deadline. + ctx := context.Background() + if progress, ok := h.(interface { + ReportRecoveryProgress(storage.RecoveryPhase, uint64) + }); ok { + ctx = storage.WithRecoveryProgress(ctx, progress.ReportRecoveryProgress) + } + report, err := dp.RecoverVolume(ctx, volumeID) + if err != nil { + h.BlockLocalReadiness(report.Evidence) + h.ReportLocalRecoveryFailure(err) + return durableStartupFaulted, report.Evidence, err + } + h.ClearLocalReadinessBlock() + return durableStartupReady, report.Evidence, nil +} diff --git a/seaweed-block/cmd/blockvolume/durable_startup_budget_test.go b/seaweed-block/cmd/blockvolume/durable_startup_budget_test.go new file mode 100644 index 0000000000..b5f9886f15 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/durable_startup_budget_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// This counting provider represents local map replay without disk throughput or +// wall-clock sleeps. It probes the production startup boundary, not a widened +// deadline: a per-volume walk must not inherit the attach operation's timer. +type countingLocalRecovery struct { + entries int + visited int + underDeadline int +} + +func (p *countingLocalRecovery) EnsureStorage(string) (storage.LogicalStorage, error) { + return nil, nil +} +func (p *countingLocalRecovery) RecoverVolume(ctx context.Context, id string) (durable.RecoveryReport, error) { + for i := 0; i < p.entries; i++ { + p.visited++ + if _, timed := ctx.Deadline(); timed { + p.underDeadline++ + } + } + return durable.RecoveryReport{VolumeID: id, Evidence: "local replay completed"}, nil +} + +func TestDurableStartup_LocalRecoveryWorkIsOutsideFixedDeadline(t *testing.T) { + for _, entries := range []int{1, 262144} { + t.Run(map[int]string{1: "one", 262144: "one_tib_chunk_count"}[entries], func(t *testing.T) { + p := &countingLocalRecovery{entries: entries} + outcome, _, err := openAndRecoverDurable(p, &spyHost{}, "v1", 10*time.Second) + if err != nil || outcome != durableStartupReady || p.visited != entries { + t.Fatalf("startup=%v err=%v visited=%d want=%d", outcome, err, p.visited, entries) + } + if p.underDeadline != 0 { + t.Fatalf("volume-sized local recovery visited %d/%d entries under a fixed deadline; growing replay must precede the bounded attach operation", p.underDeadline, entries) + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go b/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go new file mode 100644 index 0000000000..60e60c1c58 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go @@ -0,0 +1,78 @@ +package main + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func startAfterCorruption(t *testing.T, cfg durable.ProviderConfig) (durableStartupOutcome, *spyHost) { + t.Helper() + dp, err := durable.NewDurableProvider(cfg, healthyView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dp.Close() }) + h := &spyHost{} + outcome, evidence, err := openAndRecoverDurable(dp, h, "v1", 5*time.Second) + t.Logf("outcome=%v reported=%v evidence=%q err=%v", outcome, h.reported, evidence, err) + return outcome, h +} + +// V3 replaces the legacy warning-only recovery policy with nonce-bound, +// contiguous WAL recovery. Corruption below strict W must block readiness. +func TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness(t *testing.T) { + const childEnv = "SWBLOCK_V3_STARTUP_CRASH_PATH" + if path := os.Getenv(childEnv); path != "" { + s, err := storage.CreateWALStoreWithOptions(path, 16, 4096, storage.WALStoreOptions{WMode: storage.WModeStrict}) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 4; i++ { + data := make([]byte, 4096) + data[0] = byte(0xd0 + i) + if _, err := s.Write(i, data); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + os.Exit(0) // deliberately no Close/checkpoint; OS releases the owner lock + } + root := t.TempDir() + path := filepath.Join(root, "v1.bin") + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness$") + cmd.Env = append(os.Environ(), childEnv+"="+path) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("crash fixture: %v\n%s", err, out) + } + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + at := int64(8192 + (70 + 4096) + 62 + 100) // v3 second record payload + b := make([]byte, 1) + _, re := f.ReadAt(b, at) + b[0] ^= 0xff + _, we := f.WriteAt(b, at) + ce := f.Close() + if re != nil || we != nil || ce != nil { + t.Fatal(re, we, ce) + } + cfg := durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root, BlockSize: 4096, NumBlocks: 16} + outcome, h := startAfterCorruption(t, cfg) + if outcome != durableStartupFaulted || len(h.reported) != 1 || h.reported[0] != volume.UnhealthyWALCorrupt || len(h.blocked) == 0 { + t.Fatalf("committed hole: outcome=%v reported=%v blocked=%v; want wal_corrupt and blocked", outcome, h.reported, h.blocked) + } +} diff --git a/seaweed-block/cmd/blockvolume/durable_startup_test.go b/seaweed-block/cmd/blockvolume/durable_startup_test.go new file mode 100644 index 0000000000..28630ad3c6 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/durable_startup_test.go @@ -0,0 +1,125 @@ +package main + +import ( + "context" + "errors" + "io/fs" + "os" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// #133 (review of #139): blockvolume's startup open-and-replay step +// reports a classifiable failure of EITHER step through the host and +// faults fail-closed. These drive openAndRecoverDurable, the function +// main runs, so removing its reporting fails them. + +type spyHost struct { + blocked []string + cleared int + reported []string // the classified reasons ReportLocalRecoveryFailure returned +} + +func (s *spyHost) BlockLocalReadiness(reason string) { s.blocked = append(s.blocked, reason) } +func (s *spyHost) ClearLocalReadinessBlock() { s.cleared++ } +func (s *spyHost) ReportLocalRecoveryFailure(err error) string { + r := volume.LocalRecoveryHealthReason(err) + s.reported = append(s.reported, r) + return r +} + +type fakeStartup struct { + ensureErr error + recoverErr error + report durable.RecoveryReport + recovered bool +} + +func (f *fakeStartup) EnsureStorage(string) (storage.LogicalStorage, error) { return nil, f.ensureErr } +func (f *fakeStartup) RecoverVolume(context.Context, string) (durable.RecoveryReport, error) { + f.recovered = true + return f.report, f.recoverErr +} + +func TestDurableStartup_ClassifiableOpenFailureFaultsAndReports(t *testing.T) { + h := &spyHost{} + dp := &fakeStartup{ensureErr: &fs.PathError{Op: "open", Path: "/vol/v1.bin", Err: syscall.EIO}} + outcome, evidence, err := openAndRecoverDurable(dp, h, "v1", time.Second) + if outcome != durableStartupFaulted || err == nil { + t.Fatalf("classifiable open failure: outcome=%v err=%v; want faulted", outcome, err) + } + if len(h.blocked) != 1 || len(h.reported) != 1 || h.reported[0] != volume.UnhealthyIOError { + t.Fatalf("host calls: blocked=%v reported=%v; want one block and io_error reported", h.blocked, h.reported) + } + if dp.recovered { + t.Fatal("replay ran after a failed open") + } + if evidence == "" { + t.Fatal("no evidence for the faulted open") + } +} + +func TestDurableStartup_UnclassifiedOpenFailureStaysFatal(t *testing.T) { + h := &spyHost{} + dp := &fakeStartup{ensureErr: errors.New("durable: bad config")} + outcome, _, err := openAndRecoverDurable(dp, h, "v1", time.Second) + if outcome != durableStartupFatal || err == nil { + t.Fatalf("unclassified open failure: outcome=%v err=%v; want fatal (the earlier exit)", outcome, err) + } + if len(h.blocked) != 0 || len(h.reported) != 0 { + t.Fatalf("host calls for a fatal open: blocked=%v reported=%v; want none", h.blocked, h.reported) + } +} + +func TestDurableStartup_ReplayFailureFaultsAndReports(t *testing.T) { + h := &spyHost{} + dp := &fakeStartup{recoverErr: storage.NewWALIntegrityFailure(nil, "crc"), report: durable.RecoveryReport{Evidence: "recover failed: crc"}} + outcome, evidence, _ := openAndRecoverDurable(dp, h, "v1", time.Second) + if outcome != durableStartupFaulted || evidence != "recover failed: crc" { + t.Fatalf("replay failure: outcome=%v evidence=%q", outcome, evidence) + } + if len(h.reported) != 1 || h.reported[0] != volume.UnhealthyWALCorrupt || len(h.blocked) != 1 { + t.Fatalf("host calls: blocked=%v reported=%v; want one block and wal_corrupt", h.blocked, h.reported) + } +} + +func TestDurableStartup_CleanRecoveryClearsBlock(t *testing.T) { + h := &spyHost{} + outcome, _, err := openAndRecoverDurable(&fakeStartup{report: durable.RecoveryReport{Evidence: "recovered LSN=3"}}, h, "v1", time.Second) + if outcome != durableStartupReady || err != nil || h.cleared != 1 || len(h.reported) != 0 { + t.Fatalf("clean recovery: outcome=%v err=%v cleared=%d reported=%v", outcome, err, h.cleared, h.reported) + } +} + +type healthyView struct{} + +func (healthyView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v1", Healthy: true} +} + +// Real provider, open path: the volume file is truncated (2 bytes), so +// the provider's 4-byte magic read fails with io.ErrUnexpectedEOF +// (io_error). +func TestDurableStartup_RealProviderOpenFailureIsIOError(t *testing.T) { + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "v1.bin"), []byte{0x53, 0x57}, 0o644); err != nil { + t.Fatal(err) + } + dp, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root}, healthyView{}) + if err != nil { + t.Fatal(err) + } + defer dp.Close() + h := &spyHost{} + outcome, _, oErr := openAndRecoverDurable(dp, h, "v1", 5*time.Second) + if outcome != durableStartupFaulted || len(h.reported) != 1 || h.reported[0] != volume.UnhealthyIOError { + t.Fatalf("truncated volume file: outcome=%v err=%v reported=%v; want faulted with io_error", outcome, oErr, h.reported) + } +} diff --git a/seaweed-block/cmd/blockvolume/durable_wal_multiblock_flag_test.go b/seaweed-block/cmd/blockvolume/durable_wal_multiblock_flag_test.go new file mode 100644 index 0000000000..06cf2e1fb7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/durable_wal_multiblock_flag_test.go @@ -0,0 +1,84 @@ +package main + +import ( + "strings" + "testing" +) + +func phase150RequiredBlockvolumeArgs() []string { + return []string{ + "--master=127.0.0.1:9333", + "--server-id=m02", + "--volume-id=v1", + "--replica-id=r1", + "--data-addr=127.0.0.1:19101", + "--ctrl-addr=127.0.0.1:19102", + } +} + +func TestPhase150_BlockvolumeDurableWALMultiBlockFlagDefaultFalse(t *testing.T) { + f, err := parseFlags(phase150RequiredBlockvolumeArgs()) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if f.durableWALMultiBlockRecords { + t.Fatal("durableWALMultiBlockRecords default=true, want false") + } +} + +func TestPhase150_BlockvolumeDurableWALMultiBlockFlagRequiresWalstore(t *testing.T) { + args := append(phase150RequiredBlockvolumeArgs(), + "--durable-root=/tmp/sw-block", + "--durable-wal-multiblock-records", + ) + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "requires --durable-impl=walstore") { + t.Fatalf("parseFlags: err=%v; want the walstore requirement error", err) + } +} + +func TestPhase150_BlockvolumeDurableWALMultiBlockFlagParsesOptIn(t *testing.T) { + args := append(phase150RequiredBlockvolumeArgs(), + "--durable-root=/tmp/sw-block", + "--durable-impl=walstore", + "--durable-wal-multiblock-records", + ) + f, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !f.durableWALMultiBlockRecords { + t.Fatal("durableWALMultiBlockRecords=false, want true") + } +} + +func TestPhase152_BlockvolumeDurableWALRecoveryTestDisableFlusherFlag(t *testing.T) { + args := append(phase150RequiredBlockvolumeArgs(), + "--durable-root=/tmp/sw-block", + "--durable-impl=walstore", + "--durable-wal-recovery-test-disable-flusher", + ) + f, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !f.durableWALRecoveryTestDisableFlusher { + t.Fatal("durableWALRecoveryTestDisableFlusher=false, want true") + } +} + +func TestPhase152_BlockvolumeDurableWALRecoveryTestDisableFlusherRequiresWalstore(t *testing.T) { + args := append(phase150RequiredBlockvolumeArgs(), + "--durable-root=/tmp/sw-block", + "--durable-wal-recovery-test-disable-flusher", + ) + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "requires --durable-impl=walstore") { + t.Fatalf("parseFlags: err=%v; want the walstore requirement error", err) + } +} + +func TestPhase167_BlockvolumeRejectsUnknownDurableImpl(t *testing.T) { + args := append(phase150RequiredBlockvolumeArgs(), "--durable-impl=parallel-looking") + if _, err := parseFlags(args); err == nil { + t.Fatal("parseFlags succeeded; want unknown durable impl rejected") + } +} diff --git a/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go b/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go new file mode 100644 index 0000000000..eb82e9925f --- /dev/null +++ b/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go @@ -0,0 +1,135 @@ +package main + +import ( + "bytes" + "context" + "errors" + "os" + "path/filepath" + "strconv" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestExistingDurableVolumeIgnoresCreateGeometry(t *testing.T) { + root := t.TempDir() + s, err := storage.CreateWALStore(filepath.Join(root, "v1.bin"), 16, 4096) + if err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{0x73}, 4096) + if _, err = s.Write(0, want); err != nil { + s.Close() + t.Fatal(err) + } + if _, err = s.Sync(); err != nil { + s.Close() + t.Fatal(err) + } + if err = s.Close(); err != nil { + t.Fatal(err) + } + args := append(phase150RequiredBlockvolumeArgs(), "--volume-id=v1", "--durable-root="+root, "--durable-impl=walstore", "--durable-blocks=4294967295", "--durable-blocksize=8192") + f, err := parseFlags(args) + if err != nil { + t.Fatalf("existing storage must ignore create-only geometry: %v", err) + } + blocks, blockSize, err := durableCreateGeometry(f) + if err != nil { + t.Fatal(err) + } + if blocks != 0 { + t.Fatal("existing file must select open-only mode") + } + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplName(f.durableImpl), StorageRoot: f.durableRoot, NumBlocks: blocks, BlockSize: blockSize}, healthyView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + result, _, err := openAndRecoverDurable(p, &spyHost{}, "v1", 5*time.Second) + if err != nil || result != durableStartupReady { + t.Fatalf("existing recovery: %v %v", result, err) + } + st, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if st.NumBlocks() != 16 || st.BlockSize() != 4096 { + t.Fatalf("existing geometry changed: %d x %d", st.NumBlocks(), st.BlockSize()) + } + got := make([]byte, 4096) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err = b.Read(context.Background(), 0, got); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatal("existing bytes changed") + } +} + +func TestExistingDurableVolumeDisappearsDoesNotCreateFromIgnoredFlags(t *testing.T) { + if strconv.IntSize < 64 { + t.Skip("64-bit CLI uint overflow case") + } + for _, impl := range []durable.ImplName{durable.ImplWALStore, durable.ImplWALStoreChunk} { + t.Run(string(impl), func(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "v1.bin") + s, err := storage.CreateWALStore(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + if err = s.Close(); err != nil { + t.Fatal(err) + } + args := append(phase150RequiredBlockvolumeArgs(), "--volume-id=v1", "--durable-root="+root, "--durable-impl="+string(impl), "--durable-blocks=4294967297") + if impl == durable.ImplWALStoreChunk { + args = append(args, "--chunk-filer=127.0.0.1:18888", "--workspace-lease") + } + f, err := parseFlags(args) + if err != nil { + t.Fatal(err) + } + blocks, bs, err := durableCreateGeometry(f) + if err != nil { + t.Fatal(err) + } + if blocks != 0 { + t.Fatal("not open-only") + } + if err = os.Remove(path); err != nil { + t.Fatal(err) + } + if _, _, err = durableCreateGeometry(f); err == nil { + t.Fatal("fresh recheck accepted original overflowing count") + } + cfg := durable.ProviderConfig{Impl: impl, StorageRoot: root, NumBlocks: blocks, BlockSize: bs} + if impl == durable.ImplWALStoreChunk { + unexpected := errors.New("unexpected layout access for missing open-only volume") + cfg.ChunkLayoutHeadFor = func(string) (layout.StartStore, error) { return nil, unexpected } + cfg.ChunkLayoutRemoteFor = func(string, layout.HolderID) (storage.ChunkRemote, error) { return nil, unexpected } + } + p, err := durable.NewDurableProvider(cfg, healthyView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + if _, err = p.EnsureStorage("v1"); err == nil { + t.Fatal("created replacement from ignored flags") + } + if _, err = os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("replacement file exists: %v", err) + } + if _, err = os.Stat(path + ".chunkfresh"); !os.IsNotExist(err) { + t.Fatalf("open-only refusal left a fresh marker: %v", err) + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/fence_heal_integration_test.go b/seaweed-block/cmd/blockvolume/fence_heal_integration_test.go new file mode 100644 index 0000000000..cbbe480621 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/fence_heal_integration_test.go @@ -0,0 +1,320 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" +) + +// TestFencingRoundHealContinuesThePrimary runs the heal of a failed fencing +// round through the production binaries: an RF3 sync-quorum volume whose +// primary r1 stops long enough to be judged lost. The fencing round reaches +// r2, but r3 cannot make its floor durable (a regular file stands where its +// durable root was, so the floor record write fails with ENOTDIR, root too), +// so it does not answer: one fenced survivor, two needed, nothing is +// published, and r1 does not answer the heal. When r1 resumes, the master +// continues it at epoch 2 on its own evidence; a write after that reads back +// with the one before it. +func TestFencingRoundHealContinuesThePrimary(t *testing.T) { fencingRoundHeal(t, false) } + +// TestFencingRoundSurvivorRejoins is the same scenario carried one step +// further: once r3 can persist again, both replicas serve r1 as healthy +// peers of the primary, even across a short host scheduling pause (at +// epoch 2, or later when the pause made the gate fence r1 once more). +func TestFencingRoundSurvivorRejoins(t *testing.T) { fencingRoundHeal(t, true) } + +func fencingRoundHeal(t *testing.T, rejoin bool) { + if isWindows() { + t.Skip("SIGSTOP: Linux only") + } + bins := buildG54Binaries(t) + h := &plannedHandoffHarness{dir: t.TempDir(), t: t} + h.masterAddr = handoffAddress(t) + type host struct { + id, data, ctrl, status, nvme, root string + d *daemon + args []string + } + hosts := make([]*host, 3) + var nodes, placements strings.Builder + for i := range hosts { + id := fmt.Sprintf("s%d", i+1) + hosts[i] = &host{id: id, data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t), root: filepath.Join(h.dir, "vol-"+id)} + fmt.Fprintf(&nodes, " - server_id: %s\n data_addr: %s\n ctrl_addr: %s\n", id, hosts[i].data, hosts[i].ctrl) + fmt.Fprintf(&placements, " - server_id: %s\n replica_id: r%d\n", id, i+1) + } + spec := filepath.Join(h.dir, "cluster-spec.yaml") + if err := os.WriteFile(spec, []byte("nodes:\n"+nodes.String()+"volumes:\n - id: v1\n size_bytes: 268435456\n replication_factor: 3\n placements:\n"+placements.String()), 0o644); err != nil { + t.Fatal(err) + } + master := h.start(t, "blockmaster", bins.master, + "--authority-store", filepath.Join(h.dir, "master", "authority"), "--lifecycle-store", filepath.Join(h.dir, "master", "lifecycle"), + "--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", "200ms", + // Keep the production default (30s). A 2s override turns a short + // scheduling pause during rejoin into another real fencing round, + // after which waiting for the old epoch can never succeed. + "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr) + master.waitLog(t, 30*time.Second, "blockmaster: lock acquired") + for i, b := range hosts { + lockDir := b.root + ".locks" + if err := os.MkdirAll(lockDir, 0o700); err != nil { + t.Fatal(err) + } + b.args = []string{"--volume-lock-dir-test-only", lockDir, "--master", h.masterAddr, "--server-id", b.id, "--volume-id", "v1", + "--replica-id", fmt.Sprintf("r%d", i+1), "--data-addr", b.data, "--ctrl-addr", b.ctrl, "--status-addr", b.status, + "--durable-root", b.root, "--durable-impl", "walstore", "--durable-blocks", "65536", "--durable-blocksize", "4096", + "--heartbeat-interval", "200ms", "--t1-readiness", "--replication-ack", "sync-quorum", + "--nvme-listen", b.nvme, "--nvme-subsysnqn", plannedHandoffNQN} + b.d = h.start(t, "blockvolume-"+b.id, bins.volume, b.args...) + // Registered after the daemon's own cleanup, so it runs first: a + // stopped child is resumed before it is cancelled. + d := b.d + t.Cleanup(func() { _ = d.proc.Signal(syscall.SIGCONT) }) + } + r1, r2, r3 := hosts[0], hosts[1], hosts[2] + // r3's floor fault: its durable root moved aside and a regular file put + // at its path, so a new file under it fails with ENOTDIR (for root as + // well); the files r3 already holds open keep working. + aside := r3.root + ".aside" + breakFloor := func() { + if err := os.Rename(r3.root, aside); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(r3.root, nil, 0o644); err != nil { + t.Fatal(err) + } + } + healFloor := func() { + if err := os.Remove(r3.root); err != nil { + t.Fatal(err) + } + if err := os.Rename(aside, r3.root); err != nil { + t.Fatal(err) + } + } + t.Cleanup(func() { + if st, err := os.Stat(aside); err == nil && st.IsDir() { + _ = os.Remove(r3.root) + _ = os.Rename(aside, r3.root) + } + }) + + // 1. r1 serves at epoch 1 with both replicas healthy behind it. + h.waitPrimaryAt(t, r1.status, 1) + waitPeersHealthy(t, r1.status, 1) + a := bytes.Repeat([]byte{0xa1}, 4096) + c := dialNVMe(t, r1.nvme, plannedHandoffNQN) + c.write(t, 0, a) + c.flush(t) + if got := c.read(t, 0, 4096); !bytes.Equal(got, a) { + t.Fatal("block A did not read back at epoch 1") + } + c.close() + // The gate has seen both replicas ready on the stores r1 attested (its + // probe of a ready primary logs each candidate's readiness). + poll(t, 30*time.Second, "the gate never saw r2 and r3 ready on attested stores", func() bool { + data, _ := os.ReadFile(master.log) + for _, l := range strings.Split(string(data), string(rune(10))) { + if strings.Contains(l, "promotion gate volume=v1 current=r1") && strings.Contains(l, "{r2 true") && strings.Contains(l, "{r3 true") { + return true + } + } + return false + }) + + // 2. r3 can no longer persist a floor; r1 stops: a fencing round at 2 + // gets only r2, publishes nothing, and r1 cannot answer the heal. + breakFloor() + if err := r1.d.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatal(err) + } + master.waitLog(t, 60*time.Second, "fencing round at 2: 1 fenced survivors, need 2") + master.waitLog(t, 30*time.Second, "heal: primary r1 did not answer ready") + r3.d.waitLog(t, 30*time.Second, "fencing round=") + if master.has("heal: continuing") || master.has("direct_reassign") { + t.Fatal("a line was published while the fencing round had too few survivors") + } + for _, b := range []*host{r2, r3} { + if e := statusEpoch(t, b.status); e != 1 { + t.Fatalf("%s is at epoch %d while nothing may be published; want 1", b.id, e) + } + } + + // 3. r1 resumes: the remembered round heals it at epoch 2. + if err := r1.d.proc.Signal(syscall.SIGCONT); err != nil { + t.Fatal(err) + } + master.waitLog(t, 60*time.Second, "heal: continuing r1 at epoch 2") + h.waitPrimaryAt(t, r1.status, 2) + if master.has("direct_reassign=r2") || master.has("direct_reassign=r3") { + t.Fatal("a survivor was promoted instead of the heal") + } + + // 4. A write at epoch 2 reads back with the one before it. + b := bytes.Repeat([]byte{0xb2}, 4096) + c = dialNVMe(t, r1.nvme, plannedHandoffNQN) + c.write(t, 1, b) + c.flush(t) + if got := c.read(t, 0, 8192); !bytes.Equal(got, append(append([]byte(nil), a...), b...)) { + t.Fatal("blocks A and B did not read back at epoch 2") + } + c.close() + + if !rejoin { + return + } + // 5. r3 can persist again: both replicas rejoin r1 at epoch 2. + healFloor() + // A deterministic slow-host control: longer than the former 2s test + // window, but below the production freshness window. Do not mistake it + // for a second primary failure. Cleanup already resumes a stopped child. + if err := r1.d.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatal(err) + } + time.Sleep(6 * time.Second) + if err := r1.d.proc.Signal(syscall.SIGCONT); err != nil { + t.Fatal(err) + } + // The property is the rejoin: both replicas serve r1 as healthy peers, + // r1 stays the primary, and nothing written is lost. The epoch is not + // part of it: on a loaded host the resumed r1 may answer the gate's probe + // not ready, and the gate then fences once more and continues r1 at the + // next epoch, which is the designed answer to a primary that is not + // ready, not a failure of the rejoin. + epoch := waitRejoinConverged(t, r1.status, 2, func() string { + return "r2 log tail:\n" + r2.d.tail(40) + "\nr3 log tail:\n" + r3.d.tail(40) + }, "r2", "r3") + if epoch > 2 { + t.Logf("a further fencing round continued r1 at epoch %d after the pause", epoch) + } + if master.has("direct_reassign=r2") || master.has("direct_reassign=r3") { + t.Fatal("a replica was promoted instead of r1 being continued") + } + c = dialNVMe(t, r1.nvme, plannedHandoffNQN) + defer c.close() + if got := c.read(t, 0, 8192); !bytes.Equal(got, append(append([]byte(nil), a...), b...)) { + t.Fatal("blocks A and B did not read back after the rejoin") + } +} + +// waitRejoinConverged polls until the primary at statusAddr is a healthy +// primary at some epoch e >= minEpoch and every replica in rids is a healthy +// peer at that same e, all read in one pass; it returns e. Reading the epoch +// once and then waiting for that exact epoch would fail if a further round +// moved it in between. +// On failure it reports the last answer and dump(), the replicas' own logs: +// the primary's answer alone cannot tell a replica that never caught up from +// one that never answered. +func waitRejoinConverged(t *testing.T, statusAddr string, minEpoch uint64, dump func() string, rids ...string) uint64 { + t.Helper() + c := &http.Client{Timeout: 5 * time.Second} + get := func(path string) []byte { + resp, err := c.Get("http://" + statusAddr + path) + if err != nil { + return nil + } + defer resp.Body.Close() + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + return b + } + var last string + for end := time.Now().Add(120 * time.Second); time.Now().Before(end); time.Sleep(200 * time.Millisecond) { + var st struct{ Epoch uint64 } + sb := get("/status?volume=v1") + if json.Unmarshal(sb, &st) != nil || st.Epoch < minEpoch || !statusPrimary(sb, st.Epoch) { + last = string(sb) + continue + } + pb := get("/status/peers?volume=v1") + last = string(pb) + var ps struct { + Peers []struct { + ReplicaID string + State string + Epoch uint64 + } + } + if json.Unmarshal(pb, &ps) != nil { + continue + } + healthy := map[string]bool{} + for _, p := range ps.Peers { + if p.State == "healthy" && p.Epoch == st.Epoch { + healthy[p.ReplicaID] = true + } + } + all := true + for _, r := range rids { + all = all && healthy[r] + } + if all { + return st.Epoch + } + } + t.Fatalf("the primary and %v never converged on one epoch >= %d; last answer: %s\n%s", rids, minEpoch, last, dump()) + return 0 +} + +// statusEpoch is the epoch a host's /status reports. +func statusEpoch(t *testing.T, statusAddr string) uint64 { + t.Helper() + resp, err := (&http.Client{Timeout: 5 * time.Second}).Get("http://" + statusAddr + "/status?volume=v1") + if err != nil { + t.Fatalf("status %s: %v", statusAddr, err) + } + defer resp.Body.Close() + var st struct{ Epoch uint64 } + if err := json.NewDecoder(resp.Body).Decode(&st); err != nil { + t.Fatalf("status %s: %v", statusAddr, err) + } + return st.Epoch +} + +// waitPeersHealthy waits until the primary's /status/peers lists r2 and r3 +// healthy at epoch: the primary ships to both and counts them again. +func waitPeersHealthy(t *testing.T, statusAddr string, epoch uint64) { + t.Helper() + c := &http.Client{Timeout: 5 * time.Second} + var last string + end := time.Now().Add(90 * time.Second) + for time.Now().Before(end) { + if resp, err := c.Get("http://" + statusAddr + "/status/peers?volume=v1"); err == nil { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + resp.Body.Close() + last = string(body) + var st struct { + Peers []struct { + ReplicaID string + State string + Epoch uint64 + } + } + if json.Unmarshal(body, &st) == nil { + healthy := map[string]bool{} + var states []string + for _, p := range st.Peers { + states = append(states, fmt.Sprintf("%s=%s@%d", p.ReplicaID, p.State, p.Epoch)) + if p.State == "healthy" && p.Epoch == epoch { + healthy[p.ReplicaID] = true + } + } + last = strings.Join(states, ", ") + if healthy["r2"] && healthy["r3"] { + return + } + } + } + time.Sleep(200 * time.Millisecond) + } + t.Fatalf("the primary's peers never were r2 and r3 healthy at epoch %d; last: %s", epoch, last) +} diff --git a/seaweed-block/cmd/blockvolume/fill_witness_test.go b/seaweed-block/cmd/blockvolume/fill_witness_test.go new file mode 100644 index 0000000000..d9fe9611c2 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/fill_witness_test.go @@ -0,0 +1,54 @@ +package main_test + +import ( + "errors" + "fmt" + "testing" +) + +// fillProgress is what a test knows about a running fill: the absent chunk +// count when its reader started, the count now, and the reader's state. +type fillProgress struct { + baseline, absent int + reads int64 + readerErr error + finished bool +} + +// fillWitness is nil only while a fill is observably running: the reader +// has completed a read without error and has not finished, the absent +// count fell below its value when the reader started, and work remains. +// Remaining work alone does not show a fill is running. +func fillWitness(p fillProgress) error { + switch { + case p.readerErr != nil: + return fmt.Errorf("the reader failed: %w", p.readerErr) + case p.reads == 0: + return errors.New("the reader has completed no read") + case p.finished: + return errors.New("the reader finished: no fill left to interrupt") + case p.absent >= p.baseline: + return fmt.Errorf("no chunk was made local since the reader started (%d absent, %d at its start)", p.absent, p.baseline) + case p.absent == 0: + return errors.New("every chunk is local: no fill left to interrupt") + } + return nil +} + +func TestFillWitnessNeedsAnObservedRunningFill(t *testing.T) { + running := fillProgress{baseline: 16, absent: 12, reads: 3} + if err := fillWitness(running); err != nil { + t.Fatalf("a running fill: %v", err) + } + for name, p := range map[string]fillProgress{ + "reader never started": {baseline: 16, absent: 16}, + "reader failed": {baseline: 16, absent: 12, reads: 3, readerErr: errors.New("read: i/o timeout")}, + "reader finished": {baseline: 16, absent: 12, reads: 8, finished: true}, + "no progress": {baseline: 16, absent: 16, reads: 3}, + "nothing left": {baseline: 16, absent: 0, reads: 16}, + } { + if err := fillWitness(p); err == nil { + t.Errorf("%s: %+v accepted as a running fill", name, p) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/frontend_capacity_test.go b/seaweed-block/cmd/blockvolume/frontend_capacity_test.go new file mode 100644 index 0000000000..73cf67206b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/frontend_capacity_test.go @@ -0,0 +1,164 @@ +package main + +import ( + "context" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/iscsi" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" +) + +// stubBackend is a no-op frontend.Backend sufficient to satisfy +// HandlerConfig.Backend != nil — these tests only exercise the +// capacity plumb, not data path. +type stubBackend struct{} + +func (stubBackend) Read(_ context.Context, _ int64, _ []byte) (int, error) { return 0, nil } +func (stubBackend) Write(_ context.Context, _ int64, _ []byte) (int, error) { return 0, nil } +func (stubBackend) Sync(_ context.Context) error { return nil } +func (stubBackend) SetOperational(_ bool, _ string) {} +func (stubBackend) Identity() frontend.Identity { return frontend.Identity{} } +func (stubBackend) Close() error { return nil } + +// G5-5C addendum (P0 product fix): +// frontend volume capacity MUST derive from --durable-blocks × +// --durable-blocksize, not silently fall back to frontend defaults. +// +// These tests pin INV-G5-FRONTEND-CAPACITY-FROM-DURABLE-CONFIG by +// exercising the production construction path: feed (blocks, +// blockSize) through computeFrontendVolumeSize, build an iSCSI/NVMe +// HandlerConfig, construct a Target, and read back the advertised +// capacity from SCSIHandler.VolumeSize / NVMe IOHandler.VolumeSize. + +func TestComputeFrontendVolumeSize_ProductOfBlocksAndBlockSize(t *testing.T) { + cases := []struct { + blocks uint + blockSize uint + want uint64 + }{ + {1, 4096, 4096}, + {256, 4096, 1 << 20}, // 1 MiB at 4 KiB blocks + {65536, 4096, 256 << 20}, // 256 MiB at 4 KiB blocks (the case that exposed the bug) + {2048, 512, 1 << 20}, // 1 MiB at 512 B blocks (legacy default) + {1 << 20, 4096, 4 << 30}, // 4 GiB + } + for _, c := range cases { + got, err := computeFrontendVolumeSize(c.blocks, c.blockSize) + if err != nil { + t.Errorf("blocks=%d blockSize=%d: unexpected err %v", c.blocks, c.blockSize, err) + continue + } + if got != c.want { + t.Errorf("blocks=%d blockSize=%d: got %d, want %d", c.blocks, c.blockSize, got, c.want) + } + } +} + +func TestComputeFrontendVolumeSize_RejectsZero(t *testing.T) { + if _, err := computeFrontendVolumeSize(0, 4096); err == nil { + t.Error("blocks=0 should be rejected") + } + if _, err := computeFrontendVolumeSize(256, 0); err == nil { + t.Error("blockSize=0 should be rejected") + } +} + +// TestComputeFrontendVolumeSize_OverflowGuard verifies the uint64 +// overflow check fires before silently wrapping to a small value. +func TestComputeFrontendVolumeSize_OverflowGuard(t *testing.T) { + // 2^32 × 2^32 = 2^64 = wraps to 0 on uint64 multiply. + if _, err := computeFrontendVolumeSize(1<<33, 1<<33); err == nil { + t.Error("blocks × blockSize that overflows uint64 should be rejected") + } +} + +// TestIscsiHandlerCapacity_FromDurableConfig is the load-bearing +// pin for INV-G5-FRONTEND-CAPACITY-FROM-DURABLE-CONFIG on the iSCSI +// path: construct an iscsi.HandlerConfig with capacity computed by +// computeFrontendVolumeSize, build the SCSIHandler exactly as +// iscsi.NewTarget does internally, and assert the advertised +// capacity round-trips. This is the layer that broke in production: +// HandlerConfig was zero-valued and silently fell back to the +// 1 MiB defaults. +func TestIscsiHandlerCapacity_FromDurableConfig(t *testing.T) { + const ( + blocks = uint(65536) + blockSize = uint(4096) + ) + wantSize, err := computeFrontendVolumeSize(blocks, blockSize) + if err != nil { + t.Fatalf("computeFrontendVolumeSize: %v", err) + } + + h := iscsi.NewSCSIHandler(iscsi.HandlerConfig{ + Backend: stubBackend{}, + BlockSize: uint32(blockSize), + VolumeSize: wantSize, + }) + if got := h.VolumeSize(); got != wantSize { + t.Errorf("SCSIHandler.VolumeSize = %d, want %d (durable bytes)", got, wantSize) + } + if got := h.BlockSize(); got != uint32(blockSize) { + t.Errorf("SCSIHandler.BlockSize = %d, want %d", got, uint32(blockSize)) + } + // Sanity: the bug-trigger value (1 MiB default) must NOT match + // when 256 MiB was requested. Without this assertion, the test + // would still pass under a regression that re-introduced the + // default fallback if wantSize happened to equal 1 MiB. + if got := h.VolumeSize(); got == 1<<20 { + t.Errorf("SCSIHandler.VolumeSize fell back to 1 MiB default — capacity plumb broken") + } +} + +// TestNvmeHandlerCapacity_FromDurableConfig is the symmetric pin on +// the NVMe path. +func TestNvmeHandlerCapacity_FromDurableConfig(t *testing.T) { + const ( + blocks = uint(65536) + blockSize = uint(4096) + ) + wantSize, err := computeFrontendVolumeSize(blocks, blockSize) + if err != nil { + t.Fatalf("computeFrontendVolumeSize: %v", err) + } + + h := nvme.NewIOHandler(nvme.HandlerConfig{ + Backend: stubBackend{}, + NSID: 1, + BlockSize: uint32(blockSize), + VolumeSize: wantSize, + }) + if got := h.VolumeSize(); got != wantSize { + t.Errorf("NVMe IOHandler.VolumeSize = %d, want %d", got, wantSize) + } + if got := h.BlockSize(); got != uint32(blockSize) { + t.Errorf("NVMe IOHandler.BlockSize = %d, want %d", got, uint32(blockSize)) + } + if got := h.VolumeSize(); got == 1<<20 { + t.Errorf("NVMe IOHandler.VolumeSize fell back to 1 MiB default — capacity plumb broken") + } +} + +// TestFrontendDefaults_StillReturn1MiB is the negative-control pin: +// when HandlerConfig is zero-valued (the production-shipping bug +// shape), capacity falls to 1 MiB. This documents what was broken +// so a future reader can grep for the bug pattern by INV ID. +func TestFrontendDefaults_StillReturn1MiB(t *testing.T) { + // iSCSI default fallback (the bug) — 2048 × 512 = 1 MiB. + hi := iscsi.NewSCSIHandler(iscsi.HandlerConfig{Backend: stubBackend{}}) + if got := hi.VolumeSize(); got != 1<<20 { + t.Errorf("iSCSI default VolumeSize = %d, want %d (1 MiB)", got, 1<<20) + } + // NVMe default fallback — same shape. + hn := nvme.NewIOHandler(nvme.HandlerConfig{Backend: stubBackend{}, NSID: 1}) + if got := hn.VolumeSize(); got != 1<<20 { + t.Errorf("NVMe default VolumeSize = %d, want %d (1 MiB)", got, 1<<20) + } + // This test will keep passing as long as the defaults stay 1 + // MiB. If a future change updates the frontend defaults (e.g., + // to match a more useful production shape), this test fails + // and the reader should re-evaluate whether + // INV-G5-FRONTEND-CAPACITY-FROM-DURABLE-CONFIG still pins the + // right behavior. +} diff --git a/seaweed-block/cmd/blockvolume/frontend_gate.go b/seaweed-block/cmd/blockvolume/frontend_gate.go new file mode 100644 index 0000000000..8d7ae9628f --- /dev/null +++ b/seaweed-block/cmd/blockvolume/frontend_gate.go @@ -0,0 +1,94 @@ +package main + +import ( + "fmt" + "os" + "time" +) + +// workspaceStopWait is what the process's one stop waiter (waitWorkspaceStop) +// returned: the lease drain request to honour, and the lease guard's done +// channel (nil once consumed). +type workspaceStopWait struct { + leaseStop *workspaceStopRequest + leaseDone <-chan error +} + +// awaitFrontendStart races the backend's first admitted I/O against the stop +// waiter (INV-FE-PRIMARY-READY-OPERATIONAL-001). serving is closed the first +// time the backend admits I/O (for a chunk volume: after its storage claim); +// nil means there is no durable backend to wait for. It returns start = true +// when the frontends may start; otherwise the stop that won, which the caller +// shuts down with exactly as after the frontends. A stop decided meanwhile by +// INV-WS-STARTUP-RETRY-001 (exit 75 or 78) ends the stop waiter too, so a +// refused claim never starts a frontend. +// servingBackend is the part of the durable backend the start gate reads. +type servingBackend interface { + FirstServing() <-chan struct{} + AdmitsIO() error +} + +// frontendStartSignal is what the frontends wait for. A workspace chunk +// primary starts its targets only once the one "may +// serve" function (AdmitsIO) passes after the backend first admitted I/O; +// any other volume (non-chunk, or a supporting replica) starts right after +// open, as before: it never makes the claim a workspace primary waits for. +func frontendStartSignal(f flags, b servingBackend, stop <-chan struct{}) <-chan struct{} { + if f.workspaceLease && f.durableImpl == "walstore-chunk" { + out, _ := firstAdmitted(stop, b.FirstServing(), b.AdmitsIO) + return out + } + return b.FirstServing() +} + +// admitRecheck bounds firstAdmitted's re-check of AdmitsIO after the backend +// first admits I/O (workspace primaries only, until first served): the +// backend has no projection-change signal. +const admitRecheck = 50 * time.Millisecond + +// firstAdmitted's out is closed once first has closed (the backend first +// admitted I/O) and admits() then passes; it re-checks every admitRecheck +// until then, and ends without closing out when stop closes. done is closed +// when its goroutine has returned, on either path. +func firstAdmitted(stop <-chan struct{}, first <-chan struct{}, admits func() error) (out, done <-chan struct{}) { + o, d := make(chan struct{}), make(chan struct{}) + go func() { + defer close(d) + select { + case <-first: + case <-stop: + return + } + t := time.NewTicker(admitRecheck) + defer t.Stop() + for admits() != nil { + select { + case <-t.C: + case <-stop: + return + } + } + close(o) + }() + return o, d +} + +func awaitFrontendStart(serving <-chan struct{}, stopWait <-chan workspaceStopWait) (stopped *workspaceStopWait, start bool) { + if serving == nil { + return nil, true + } + select { + case <-serving: + return nil, true + default: + } + fmt.Fprintln(os.Stderr, "blockvolume: frontends wait for the storage claim: the backend admits no I/O yet") + select { + case <-serving: + fmt.Fprintln(os.Stderr, "blockvolume: backend admits I/O: starting the frontends") + return nil, true + case w := <-stopWait: + fmt.Fprintln(os.Stderr, "blockvolume: stopping before any frontend started") + return &w, false + } +} diff --git a/seaweed-block/cmd/blockvolume/frontend_gate_test.go b/seaweed-block/cmd/blockvolume/frontend_gate_test.go new file mode 100644 index 0000000000..7f6abc571b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/frontend_gate_test.go @@ -0,0 +1,103 @@ +package main + +import ( + "context" + "testing" + "time" +) + +type gateResult struct { + stopped *workspaceStopWait + start bool +} + +// gateWait bounds every receive of a gate result in these tests. +const gateWait = 5 * time.Second + +// runGate runs awaitFrontendStart on serving and a stop channel it owns +// (buffered, returned for the test to send on). Its cleanup, registered +// before the worker starts, releases a gate that is still waiting with a +// stop and joins the worker within gateWait, so a failing check never +// strands it. +func runGate(t *testing.T, serving <-chan struct{}) (<-chan gateResult, chan<- workspaceStopWait) { + t.Helper() + out := make(chan gateResult, 1) + stopWait := make(chan workspaceStopWait, 1) + exited := make(chan struct{}) + t.Cleanup(func() { + select { + case stopWait <- workspaceStopWait{}: + default: + } + select { + case <-exited: + case <-time.After(gateWait): + t.Errorf("the gate worker did not exit within %s of a stop", gateWait) + } + }) + go func() { + defer close(exited) + s, ok := awaitFrontendStart(serving, stopWait) + out <- gateResult{s, ok} + }() + return out, stopWait +} + +func receiveGate(t *testing.T, res <-chan gateResult, what string) gateResult { + t.Helper() + select { + case r := <-res: + return r + case <-time.After(gateWait): + t.Fatalf("%s: the gate did not return within %s", what, gateWait) + return gateResult{} + } +} + +// INV-FE-PRIMARY-READY-OPERATIONAL-001: the frontends start only once the +// backend first admits I/O. With no durable backend, and with a backend that +// already serves, they start at once. Sampled every 10 ms while the backend +// admits no I/O (a chunk volume before its storage claim), the gate never +// releases; it releases as soon as the backend's first-serving channel closes. +func TestFrontendGateWaitsForTheStorageClaim(t *testing.T) { + served := make(chan struct{}) + close(served) + for name, ch := range map[string]<-chan struct{}{"no durable backend": nil, "already serving": served} { + res, _ := runGate(t, ch) + if r := receiveGate(t, res, name); !r.start || r.stopped != nil { + t.Fatalf("%s: %+v, want the frontends started at once", name, r) + } + } + + serving := make(chan struct{}) + res, _ := runGate(t, serving) + for i := 0; i < 30; i++ { // 300 ms of samples while the claim is pending + select { + case r := <-res: + t.Fatalf("sample %d: the gate released (%+v) before the backend admitted I/O", i, r) + case <-time.After(10 * time.Millisecond): + } + } + close(serving) // the storage claim succeeded + if r := receiveGate(t, res, "after the claim"); !r.start { + t.Fatalf("after the claim: %+v, want the frontends started", r) + } +} + +// A refused claim never closes the first-serving channel; the process's stop +// waiter then wins (a signal, the lease guard, or INV-WS-STARTUP-RETRY-001's +// latched exit 75/78) and no frontend starts: the stop is handed back for +// the ordinary shutdown, its lease drain request included. +func TestFrontendGateStopsWithoutStartingTheFrontends(t *testing.T) { + res, stopWait := runGate(t, make(chan struct{})) // fenced: never serves + select { + case r := <-res: + t.Fatalf("a backend that never serves released the gate: %+v", r) + case <-time.After(100 * time.Millisecond): + } + req := &workspaceStopRequest{ctx: context.Background()} + stopWait <- workspaceStopWait{leaseStop: req} + if r := receiveGate(t, res, "stop before serving"); r.start || r.stopped == nil || r.stopped.leaseStop != req { + t.Fatalf("stop before serving: %+v, want no frontends and the lease drain request handed back", r) + } +} diff --git a/seaweed-block/cmd/blockvolume/frontend_start_signal_test.go b/seaweed-block/cmd/blockvolume/frontend_start_signal_test.go new file mode 100644 index 0000000000..7a97a128cb --- /dev/null +++ b/seaweed-block/cmd/blockvolume/frontend_start_signal_test.go @@ -0,0 +1,107 @@ +package main + +import ( + "errors" + "sync/atomic" + "testing" + "time" +) + +type servingStub struct { + first chan struct{} + admits atomic.Bool +} + +func (s *servingStub) FirstServing() <-chan struct{} { return s.first } +func (s *servingStub) AdmitsIO() error { + if s.admits.Load() { + return nil + } + return errors.New("stale primary lineage") +} + +func closedWithin(ch <-chan struct{}, d time.Duration) bool { + select { + case <-ch: + return true + case <-time.After(d): + return false + } +} + +// The frontend start-signal rule: a workspace chunk primary's targets start only once +// AdmitsIO passes after the backend first admitted I/O; the stop ends the +// wait without starting them. +func TestFrontendStartSignal_WorkspacePrimaryWaitsForAdmitsIO(t *testing.T) { + f := flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v1"} + stop := make(chan struct{}) + t.Cleanup(func() { close(stop) }) // ends the re-check goroutine on any path + b := &servingStub{first: make(chan struct{})} + sig := frontendStartSignal(f, b, stop) + if closedWithin(sig, 100*time.Millisecond) { + t.Fatal("started before the backend first admitted I/O") + } + close(b.first) // operational, but the guarded projection does not admit yet + if closedWithin(sig, 4*admitRecheck) { + t.Fatal("started while AdmitsIO refuses") + } + b.admits.Store(true) + if !closedWithin(sig, 5*time.Second) { + t.Fatal("did not start after AdmitsIO passed") + } + +} + +// A stop ends firstAdmitted's worker without starting the targets, both +// while it waits for the first admitted I/O and while it re-checks AdmitsIO: +// its completion is observed on its own channel, and every join is bounded. +func TestFirstAdmittedStopEndsTheWorker(t *testing.T) { + for _, served := range []bool{false, true} { + stop := make(chan struct{}) + b := &servingStub{first: make(chan struct{})} + if served { + close(b.first) // re-checking AdmitsIO, which keeps refusing + } + out, done := firstAdmitted(stop, b.FirstServing(), b.AdmitsIO) + stopped := false + t.Cleanup(func() { + if !stopped { + close(stop) + } + if !closedWithin(done, 5*time.Second) { + t.Errorf("served=%v: the worker did not return within 5s of its stop (cleanup)", served) + } + }) + if closedWithin(done, 2*admitRecheck) { + t.Fatalf("served=%v: the worker returned before any stop", served) + } + close(stop) + stopped = true + if !closedWithin(done, 5*time.Second) { + t.Fatalf("served=%v: the worker did not return within 5s of its stop", served) + } + select { + case <-out: + t.Fatalf("served=%v: a stopped wait started the targets", served) + default: + } + } +} + +// INV-WS-SERVE-LEASE-HELD-001 scope: a non-chunk volume or a supporting +// replica starts its frontends right after open, as before: its start +// signal is the backend's first-serving channel itself, not AdmitsIO. +func TestFrontendStartSignal_OtherVolumesStartAfterOpenAsBefore(t *testing.T) { + stop := make(chan struct{}) + defer close(stop) + for _, f := range []flags{ + {durableImpl: "walstore", volumeID: "v1"}, + {durableImpl: "walstore-chunk", volumeID: "v1"}, // chunk without the workspace lease + } { + b := &servingStub{first: make(chan struct{})} + close(b.first) // open and recovered; AdmitsIO refuses (not the primary) + if !closedWithin(frontendStartSignal(f, b, stop), time.Second) { + t.Fatalf("impl=%s workspace-lease=%v: did not start right after open while AdmitsIO refuses", f.durableImpl, f.workspaceLease) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/g5_4_l2_replication_test.go b/seaweed-block/cmd/blockvolume/g5_4_l2_replication_test.go new file mode 100644 index 0000000000..bb03d55c8a --- /dev/null +++ b/seaweed-block/cmd/blockvolume/g5_4_l2_replication_test.go @@ -0,0 +1,458 @@ +// G5-4.5 binary integration test — pin INV-BIN-WIRING-* through the +// production binary code path (NOT component framework fixture). +// +// Per mini-plan v0.4 §4 #2 architect binding (round 50): "Healthy" +// must split by role. Primary asserts Healthy=true via the existing +// frontend/write-ready projection. Replica asserts replication-ready +// (listener bound, accepting connections) via the bound --data-addr. +// Replica MUST NOT report Healthy=true (would imply +// frontend-primary-write-ready, which it isn't). +// +// Scope (per mini-plan v0.4 §4): +// - #1 binary constructs ReplicationVolume + ReplicaListener +// - #2 in-process 2-volume cluster reaches role-appropriate ready state +// - #5 no regressions +// Deferred to G5-5 (m01 hardware): +// - #3 byte-equal primary→replica via real frontend write client +// - #4 stop-restart catch-up convergence (needs frontend write driver) +// - #6 10× -race stress +// G5-4.5 documented carry: byte-equal write verification needs a real +// frontend client (iSCSI/NVMe). Subprocess test verifies the wiring + +// steady-state role split; G5-5 m01 hardware exercises the data path. + +//go:build subprocess + +package main_test + +import ( + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "syscall" + "testing" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +// l2bins holds the paths of compiled blockmaster + blockvolume. +type l2bins struct { + master string + volume string +} + +// buildG54Binaries compiles cmd/blockmaster + cmd/blockvolume into a +// per-test temp dir. Identical pattern to core/host/l2harness_test +// but local so this test is self-contained. +func buildG54Binaries(t *testing.T) l2bins { + t.Helper() + dir := t.TempDir() + suf := "" + if isWindows() { + suf = ".exe" + } + master := filepath.Join(dir, "blockmaster"+suf) + volume := filepath.Join(dir, "blockvolume"+suf) + for _, b := range []struct{ pkg, out string }{ + {"github.com/seaweedfs/seaweed-block/cmd/blockmaster", master}, + {"github.com/seaweedfs/seaweed-block/cmd/blockvolume", volume}, + } { + cmd := exec.Command("go", "build", "-o", b.out, b.pkg) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("build %s: %v\n%s", b.pkg, err, out) + } + } + return l2bins{master: master, volume: volume} +} + +func isWindows() bool { return os.PathSeparator == '\\' } + +// write2SlotTopology writes an RF=2 topology — pins that the binary +// works at the smoke-test 2-node configuration G5-5 will use on m01. +func write2SlotTopology(t *testing.T, dir string) string { + t.Helper() + path := filepath.Join(dir, "topology.yaml") + body := `volumes: + - volume_id: v1 + slots: + - replica_id: r1 + server_id: s1 + - replica_id: r2 + server_id: s2 +` + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatalf("topology: %v", err) + } + return path +} + +type proc struct { + cmd *exec.Cmd + logPath string +} + +func (p *proc) stop(t *testing.T) { + if p.cmd != nil && p.cmd.Process != nil { + _ = p.cmd.Process.Signal(syscall.SIGTERM) + done := make(chan struct{}) + go func() { _ = p.cmd.Wait(); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + _ = p.cmd.Process.Kill() + <-done + } + } + if t.Failed() { + if b, err := os.ReadFile(p.logPath); err == nil { + t.Logf("=== %s ===\n%s", filepath.Base(p.logPath), b) + } + } +} + +func startG54Master(t *testing.T, bins l2bins, art string) (*proc, string) { + t.Helper() + storeDir := filepath.Join(art, "master-store") + _ = os.MkdirAll(storeDir, 0o755) + topo := write2SlotTopology(t, art) + logPath := filepath.Join(art, "master.log") + lf, err := os.Create(logPath) + if err != nil { + t.Fatalf("master log: %v", err) + } + cmd := exec.Command(bins.master, + "--authority-store", storeDir, + "--listen", "127.0.0.1:0", + "--topology", topo, + "--expected-slots-per-volume", "2", + "--t0-print-ready", + ) + stdout, err := cmd.StdoutPipe() + if err != nil { + lf.Close() + t.Fatalf("master stdout pipe: %v", err) + } + cmd.Stderr = lf + if err := cmd.Start(); err != nil { + lf.Close() + t.Fatalf("master start: %v", err) + } + p := &proc{cmd: cmd, logPath: logPath} + t.Cleanup(func() { p.stop(t); lf.Close() }) + + // Read ready line: {"component":"blockmaster","phase":"listening","addr":"..."} + buf := make([]byte, 512) + n, _ := stdout.Read(buf) + go func() { + // Drain so the pipe doesn't block. + for { + b := make([]byte, 1024) + if _, err := stdout.Read(b); err != nil { + return + } + } + }() + var rl struct { + Component, Phase, Addr string + } + if err := json.Unmarshal(buf[:n], &rl); err != nil { + t.Fatalf("parse master ready %q: %v", buf[:n], err) + } + if rl.Addr == "" { + t.Fatalf("master ready: empty addr (line=%q)", buf[:n]) + } + return p, rl.Addr +} + +type volOpts struct { + masterAddr string + serverID string + replicaID string + dataAddr string + ctrlAddr string + statusAddr string + iscsiAddr string + iscsiIQN string + durableRoot string + logTag string + replicationAck string +} + +func startG54Volume(t *testing.T, bins l2bins, art string, o volOpts) *proc { + t.Helper() + logPath := filepath.Join(art, fmt.Sprintf("volume-%s.log", o.logTag)) + lf, err := os.Create(logPath) + if err != nil { + t.Fatalf("volume log: %v", err) + } + _ = os.MkdirAll(o.durableRoot, 0o755) + lockDir := o.durableRoot + ".locks" // one simulated host + _ = os.MkdirAll(lockDir, 0o700) + cmd := exec.Command(bins.volume, + "--volume-lock-dir-test-only", lockDir, + "--master", o.masterAddr, + "--server-id", o.serverID, + "--volume-id", "v1", + "--replica-id", o.replicaID, + "--data-addr", o.dataAddr, + "--ctrl-addr", o.ctrlAddr, + "--status-addr", o.statusAddr, + "--durable-root", o.durableRoot, + "--durable-impl", "walstore", + "--durable-blocks", "256", + "--durable-blocksize", "4096", + "--heartbeat-interval", "200ms", + "--t1-readiness", + ) + if o.iscsiAddr != "" { + cmd.Args = append(cmd.Args, + "--iscsi-listen", o.iscsiAddr, + "--iscsi-iqn", o.iscsiIQN, + ) + } + if o.replicationAck != "" { + cmd.Args = append(cmd.Args, "--replication-ack", o.replicationAck) + } + stripSystemdForTestLockDir(cmd) + cmd.Stdout = lf + cmd.Stderr = lf + if err := cmd.Start(); err != nil { + lf.Close() + t.Fatalf("volume %s start: %v", o.logTag, err) + } + p := &proc{cmd: cmd, logPath: logPath} + t.Cleanup(func() { p.stop(t); lf.Close() }) + return p +} + +// pollStatus polls the status endpoint until check() returns true or +// the deadline expires. Returns the last successful response body for +// debugging on failure. +func pollStatus(t *testing.T, addr string, deadline time.Duration, check func(map[string]any) bool) map[string]any { + t.Helper() + end := time.Now().Add(deadline) + var last map[string]any + for time.Now().Before(end) { + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + req, _ := http.NewRequestWithContext(ctx, "GET", "http://"+addr+"/status?volume=v1", nil) + resp, err := http.DefaultClient.Do(req) + cancel() + if err != nil { + time.Sleep(100 * time.Millisecond) + continue + } + var body map[string]any + if err := json.NewDecoder(resp.Body).Decode(&body); err == nil { + last = body + if check(body) { + resp.Body.Close() + return body + } + } + resp.Body.Close() + time.Sleep(100 * time.Millisecond) + } + return last +} + +// TestG54_BinaryWiring_RoleSplit_2NodeSmoke is the headline G5-4 +// integration pin. Verifies through the real binary code path: +// - Primary (r1) receives assignment naming itself, reaches Healthy=true +// - Replica (r2) receives same assignment naming r1, does NOT flip +// Healthy=true (correct: replica isn't frontend-primary-write-ready) +// - Replica's --data-addr accepts TCP connections (ReplicaListener +// bound; the production wire path is open for primary writes to +// ship through, even though this test doesn't drive a frontend +// write — see deferral note in file header) +// +// INV-BIN-WIRING-ROLE-FROM-ASSIGNMENT, INV-BIN-WIRING-LISTENER-LIFECYCLE-LIFO +// pin via this test. +func TestG54_BinaryWiring_RoleSplit_2NodeSmoke(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess test; -short skip") + } + bins := buildG54Binaries(t) + art := t.TempDir() + + master, masterAddr := startG54Master(t, bins, art) + _ = master + + // Use OS-assigned ports for data + ctrl + status to avoid clashes. + primaryDataLn, primaryStatusLn := pickAddr(t), pickAddr(t) + replicaDataLn, replicaStatusLn := pickAddr(t), pickAddr(t) + primaryCtrl, replicaCtrl := pickAddr(t), pickAddr(t) + + _ = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s1", replicaID: "r1", + dataAddr: primaryDataLn, ctrlAddr: primaryCtrl, + statusAddr: primaryStatusLn, + durableRoot: filepath.Join(art, "primary-store"), + logTag: "primary", + }) + _ = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s2", replicaID: "r2", + dataAddr: replicaDataLn, ctrlAddr: replicaCtrl, + statusAddr: replicaStatusLn, + durableRoot: filepath.Join(art, "replica-store"), + logTag: "replica", + }) + + // Wait for primary to reach Healthy=true. + got := pollStatus(t, primaryStatusLn, 10*time.Second, func(b map[string]any) bool { + h, _ := b["Healthy"].(bool) + return h + }) + if got == nil { + t.Fatal("primary: no /status response within 10s") + } + if h, _ := got["Healthy"].(bool); !h { + t.Fatalf("primary: Healthy=true expected; got status=%v", got) + } + + // Wait for replica's status endpoint to be reachable. Replica MUST + // NOT report Healthy=true (it's a supporting replica, not the + // frontend-primary-write-ready role). We tolerate either: + // - body present with healthy=false (clean replica role), or + // - body present with healthy=false AND assignment fields populated + // We do NOT tolerate healthy=true — that would mean the projection + // is reporting the replica as primary-write-ready, violating the + // architect-binding role split. + rGot := pollStatus(t, replicaStatusLn, 10*time.Second, func(b map[string]any) bool { + // Wait until status responds with a body that has the healthy field. + _, ok := b["Healthy"] + return ok + }) + if rGot == nil { + t.Fatal("replica: no /status response within 10s") + } + if h, _ := rGot["Healthy"].(bool); h { + t.Fatalf("replica: Healthy=true UNEXPECTED — replica role must not report frontend-write-ready; got status=%v", rGot) + } + + // Replica's --data-addr MUST accept TCP connections — pins + // INV-BIN-WIRING-LISTENER-LIFECYCLE-LIFO from the open-side + // (listener bound during host lifetime). Primary's executor would + // dial this addr to ship WAL entries; if it isn't listening, the + // production wire path is dead. + conn, err := net.DialTimeout("tcp", replicaDataLn, 2*time.Second) + if err != nil { + t.Fatalf("replica data-addr %s: TCP dial failed (ReplicaListener not bound): %v", replicaDataLn, err) + } + _ = conn.Close() +} + +func TestG15a_BlockvolumeReportsFrontendTargetsToMasterStatus(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess test; -short skip") + } + bins := buildG54Binaries(t) + art := t.TempDir() + + _, masterAddr := startG54Master(t, bins, art) + + primaryDataLn, primaryStatusLn := pickAddr(t), pickAddr(t) + replicaDataLn, replicaStatusLn := pickAddr(t), pickAddr(t) + primaryCtrl, replicaCtrl := pickAddr(t), pickAddr(t) + iscsiListen := pickAddr(t) + iqn := "iqn.2026-05.io.seaweedfs:g15a-v1" + + _ = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s1", + replicaID: "r1", + dataAddr: primaryDataLn, + ctrlAddr: primaryCtrl, + statusAddr: primaryStatusLn, + iscsiAddr: iscsiListen, + iscsiIQN: iqn, + durableRoot: filepath.Join(art, "primary-store"), + logTag: "primary-iscsi", + }) + _ = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s2", + replicaID: "r2", + dataAddr: replicaDataLn, + ctrlAddr: replicaCtrl, + statusAddr: replicaStatusLn, + durableRoot: filepath.Join(art, "replica-store"), + logTag: "replica", + }) + + resp := pollMasterStatus(t, masterAddr, "v1", 15*time.Second, func(resp *control.StatusResponse) bool { + if !resp.GetAssigned() || resp.GetReplicaId() != "r1" { + return false + } + for _, ft := range resp.GetFrontends() { + if ft.GetProtocol() == "iscsi" && ft.GetAddr() == iscsiListen && ft.GetIqn() == iqn { + return true + } + } + return false + }) + if resp == nil { + t.Fatal("master status did not expose assigned replica's iSCSI frontend target") + } +} + +// pickAddr binds a temporary listener to find a free port, then closes +// it. Caller passes the addr to a subprocess; brief race window is +// acceptable for a smoke test. +var addrMu sync.Mutex + +func pickAddr(t *testing.T) string { + t.Helper() + addrMu.Lock() + defer addrMu.Unlock() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("pick addr: %v", err) + } + addr := ln.Addr().String() + _ = ln.Close() + return addr +} + +func pollMasterStatus(t *testing.T, masterAddr, volumeID string, deadline time.Duration, check func(*control.StatusResponse) bool) *control.StatusResponse { + t.Helper() + conn, err := grpc.NewClient(masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("dial master: %v", err) + } + defer conn.Close() + client := control.NewEvidenceServiceClient(conn) + end := time.Now().Add(deadline) + var last *control.StatusResponse + for time.Now().Before(end) { + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + resp, err := client.QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: volumeID}) + cancel() + if err == nil { + last = resp + if check(resp) { + return resp + } + } + time.Sleep(100 * time.Millisecond) + } + if last != nil { + t.Logf("last master status: %+v", last) + } + return nil +} + +// silence unused-import warnings on platforms where strings/sync +// aren't picked up (placeholder; both are used above). +var _ = strings.TrimSpace diff --git a/seaweed-block/cmd/blockvolume/g8_iscsi_client_test.go b/seaweed-block/cmd/blockvolume/g8_iscsi_client_test.go new file mode 100644 index 0000000000..a35a9996aa --- /dev/null +++ b/seaweed-block/cmd/blockvolume/g8_iscsi_client_test.go @@ -0,0 +1,179 @@ +package main_test + +import ( + "bytes" + "encoding/binary" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/iscsi" +) + +type g8IscsiClient struct { + conn net.Conn + cmdSN uint32 + itt uint32 + statSN uint32 +} + +func dialG8Iscsi(t *testing.T, addr, targetName string) *g8IscsiClient { + t.Helper() + conn, err := net.DialTimeout("tcp", addr, 5*time.Second) + if err != nil { + t.Fatalf("dial iSCSI %s: %v", addr, err) + } + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + c := &g8IscsiClient{conn: conn, itt: 1} + + req := &iscsi.PDU{} + req.SetOpcode(iscsi.OpLoginReq) + req.SetImmediate(true) + req.SetLoginStages(iscsi.StageLoginOp, iscsi.StageFullFeature) + req.SetLoginTransit(true) + req.SetISID([6]byte{0x02, 0x47, 0x08, 0x00, 0x00, 0x01}) + req.SetInitiatorTaskTag(c.itt) + c.itt++ + req.SetCmdSN(c.cmdSN) + + params := iscsi.NewParams() + params.Set("InitiatorName", "iqn.2026-05.example.host:g8") + params.Set("SessionType", iscsi.SessionTypeNormal) + params.Set("TargetName", targetName) + params.Set("HeaderDigest", "None") + params.Set("DataDigest", "None") + params.Set("MaxRecvDataSegmentLength", "262144") + params.Set("InitialR2T", "Yes") + params.Set("ImmediateData", "Yes") + req.DataSegment = params.Encode() + + if err := iscsi.WritePDU(conn, req); err != nil { + t.Fatalf("write iSCSI login: %v", err) + } + resp, err := iscsi.ReadPDU(conn) + if err != nil { + t.Fatalf("read iSCSI login: %v", err) + } + if resp.Opcode() != iscsi.OpLoginResp || resp.LoginStatusClass() != iscsi.LoginStatusSuccess { + t.Fatalf("iSCSI login failed: opcode=%s class=0x%02x detail=0x%02x", + iscsi.OpcodeName(resp.Opcode()), resp.LoginStatusClass(), resp.LoginStatusDetail()) + } + c.cmdSN++ + c.statSN = resp.StatSN() + return c +} + +func (c *g8IscsiClient) close(t *testing.T) { + t.Helper() + if c == nil || c.conn == nil { + return + } + req := &iscsi.PDU{} + req.SetOpcode(iscsi.OpLogoutReq) + req.SetOpSpecific1(iscsi.FlagF) + req.SetInitiatorTaskTag(c.itt) + c.itt++ + req.SetCmdSN(c.cmdSN) + c.cmdSN++ + _ = iscsi.WritePDU(c.conn, req) + _, _ = iscsi.ReadPDU(c.conn) + _ = c.conn.Close() +} + +func (c *g8IscsiClient) write10(t *testing.T, lba uint32, payload []byte) { + t.Helper() + status := c.write10Status(t, lba, payload) + if status != iscsi.StatusGood { + t.Fatalf("iSCSI WRITE(10) status=0x%02x", status) + } +} + +func (c *g8IscsiClient) write10Status(t *testing.T, lba uint32, payload []byte) uint8 { + t.Helper() + status, _ := c.scsi(t, g8WriteCDB10(lba, 1), payload, 0) + return status +} + +func (c *g8IscsiClient) read10(t *testing.T, lba uint32, blocks uint16, bytesPerBlock int) []byte { + t.Helper() + status, data := c.scsi(t, g8ReadCDB10(lba, blocks), nil, int(blocks)*bytesPerBlock) + if status != iscsi.StatusGood { + t.Fatalf("iSCSI READ(10) status=0x%02x", status) + } + return data +} + +func (c *g8IscsiClient) syncCache10(t *testing.T) { + t.Helper() + status, _ := c.scsi(t, g8SyncCacheCDB10(), nil, 0) + if status != iscsi.StatusGood { + t.Fatalf("iSCSI SYNCHRONIZE CACHE(10) status=0x%02x", status) + } +} + +func (c *g8IscsiClient) scsi(t *testing.T, cdb [16]byte, writePayload []byte, expectedDataIn int) (uint8, []byte) { + t.Helper() + req := &iscsi.PDU{} + req.SetOpcode(iscsi.OpSCSICmd) + req.SetOpSpecific1(iscsi.FlagF) + if len(writePayload) > 0 { + req.BHS[1] |= iscsi.FlagW + } + if expectedDataIn > 0 { + req.BHS[1] |= iscsi.FlagR + } + req.SetLUN(0) + itt := c.itt + req.SetInitiatorTaskTag(itt) + c.itt++ + req.SetExpectedDataTransferLength(uint32(len(writePayload) + expectedDataIn)) + req.SetCmdSN(c.cmdSN) + c.cmdSN++ + req.SetExpStatSN(c.statSN + 1) + req.SetCDB(cdb) + req.DataSegment = writePayload + if err := iscsi.WritePDU(c.conn, req); err != nil { + t.Fatalf("write iSCSI SCSI-Cmd: %v", err) + } + + var collected bytes.Buffer + for { + resp, err := iscsi.ReadPDU(c.conn) + if err != nil { + t.Fatalf("read iSCSI response: %v", err) + } + switch resp.Opcode() { + case iscsi.OpSCSIDataIn: + collected.Write(resp.DataSegment) + if resp.OpSpecific1()&iscsi.FlagS != 0 { + return resp.SCSIStatusByte(), collected.Bytes() + } + case iscsi.OpSCSIResp: + return resp.SCSIStatusByte(), collected.Bytes() + default: + t.Fatalf("unexpected iSCSI opcode: %s", iscsi.OpcodeName(resp.Opcode())) + } + } +} + +func g8WriteCDB10(lba uint32, blocks uint16) [16]byte { + var cdb [16]byte + cdb[0] = iscsi.ScsiWrite10 + binary.BigEndian.PutUint32(cdb[2:6], lba) + binary.BigEndian.PutUint16(cdb[7:9], blocks) + return cdb +} + +func g8ReadCDB10(lba uint32, blocks uint16) [16]byte { + var cdb [16]byte + cdb[0] = iscsi.ScsiRead10 + binary.BigEndian.PutUint32(cdb[2:6], lba) + binary.BigEndian.PutUint16(cdb[7:9], blocks) + return cdb +} + +func g8SyncCacheCDB10() [16]byte { + var cdb [16]byte + cdb[0] = iscsi.ScsiSyncCache10 + return cdb +} diff --git a/seaweed-block/cmd/blockvolume/g8_l2_failover_test.go b/seaweed-block/cmd/blockvolume/g8_l2_failover_test.go new file mode 100644 index 0000000000..6b1251523b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/g8_l2_failover_test.go @@ -0,0 +1,293 @@ +//go:build subprocess + +package main_test + +import ( + "bytes" + "encoding/json" + "os" + "os/exec" + "path/filepath" + "testing" + "time" +) + +func startG8Master(t *testing.T, bins l2bins, art string) (*proc, string) { + t.Helper() + storeDir := filepath.Join(art, "master-store") + _ = os.MkdirAll(storeDir, 0o755) + topo := write2SlotTopology(t, art) + logPath := filepath.Join(art, "master-g8.log") + lf, err := os.Create(logPath) + if err != nil { + t.Fatalf("master log: %v", err) + } + cmd := exec.Command(bins.master, + "--authority-store", storeDir, + "--listen", "127.0.0.1:0", + "--topology", topo, + "--expected-slots-per-volume", "2", + "--freshness-window", "800ms", + "--pending-grace", "100ms", + "--t0-print-ready", + ) + stdout, err := cmd.StdoutPipe() + if err != nil { + lf.Close() + t.Fatalf("master stdout pipe: %v", err) + } + cmd.Stderr = lf + if err := cmd.Start(); err != nil { + lf.Close() + t.Fatalf("master start: %v", err) + } + p := &proc{cmd: cmd, logPath: logPath} + t.Cleanup(func() { p.stop(t); lf.Close() }) + + ready := readMasterReadyLine(t, stdout) + return p, ready +} + +func readMasterReadyLine(t *testing.T, stdout interface{ Read([]byte) (int, error) }) string { + t.Helper() + buf := make([]byte, 512) + n, _ := stdout.Read(buf) + go func() { + for { + b := make([]byte, 1024) + if _, err := stdout.Read(b); err != nil { + return + } + } + }() + var rl struct { + Component, Phase, Addr string + } + if err := json.Unmarshal(buf[:n], &rl); err != nil { + t.Fatalf("parse master ready %q: %v", buf[:n], err) + } + if rl.Addr == "" { + t.Fatalf("master ready: empty addr (line=%q)", buf[:n]) + } + return rl.Addr +} + +func TestG8B_L2PrimaryKill_ReassignsAuthorityToReplica(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess failover test; -short skip") + } + bins := buildG54Binaries(t) + art := t.TempDir() + + _, masterAddr := startG8Master(t, bins, art) + + r1Data, r1Status := pickAddr(t), pickAddr(t) + r2Data, r2Status := pickAddr(t), pickAddr(t) + r1Ctrl, r2Ctrl := pickAddr(t), pickAddr(t) + + r1 := startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s1", replicaID: "r1", + dataAddr: r1Data, ctrlAddr: r1Ctrl, + statusAddr: r1Status, + durableRoot: filepath.Join(art, "r1-store"), + logTag: "g8-r1", + }) + _ = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s2", replicaID: "r2", + dataAddr: r2Data, ctrlAddr: r2Ctrl, + statusAddr: r2Status, + durableRoot: filepath.Join(art, "r2-store"), + logTag: "g8-r2", + }) + + pollStatus(t, r1Status, 10*time.Second, func(b map[string]any) bool { + h, _ := b["Healthy"].(bool) + rid, _ := b["ReplicaID"].(string) + return h && rid == "r1" + }) + r2Initial := pollStatus(t, r2Status, 10*time.Second, func(b map[string]any) bool { + _, ok := b["Healthy"] + return ok + }) + if r2Initial == nil { + t.Fatal("r2: no initial status response") + } + if h, _ := r2Initial["Healthy"].(bool); h { + t.Fatalf("r2 must not be primary before r1 kill; status=%v", r2Initial) + } + + r1.stop(t) + + r2Failover := pollStatus(t, r2Status, 8*time.Second, func(b map[string]any) bool { + h, _ := b["Healthy"].(bool) + rid, _ := b["ReplicaID"].(string) + epoch, _ := b["Epoch"].(float64) + return h && rid == "r2" && epoch >= 2 + }) + if r2Failover == nil { + t.Fatal("r2: no status response after r1 kill") + } + if h, _ := r2Failover["Healthy"].(bool); !h { + t.Fatalf("r2 did not become Healthy after r1 kill; status=%v", r2Failover) + } +} + +func TestG8B_L2PrimaryKill_NewPrimaryReadsAcknowledgedISCSIWrite(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess failover data-continuity test; -short skip") + } + bins := buildG54Binaries(t) + art := t.TempDir() + + _, masterAddr := startG8Master(t, bins, art) + + iqn := "iqn.2026-05.example.g8:v1" + r1Data, r1Status, r1Iscsi := pickAddr(t), pickAddr(t), pickAddr(t) + r2Data, r2Status, r2Iscsi := pickAddr(t), pickAddr(t), pickAddr(t) + r1Ctrl, r2Ctrl := pickAddr(t), pickAddr(t) + + r1 := startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s1", replicaID: "r1", + dataAddr: r1Data, ctrlAddr: r1Ctrl, + statusAddr: r1Status, + iscsiAddr: r1Iscsi, + iscsiIQN: iqn, + durableRoot: filepath.Join(art, "g8b-data-r1-store"), + logTag: "g8b-data-r1", + }) + _ = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s2", replicaID: "r2", + dataAddr: r2Data, ctrlAddr: r2Ctrl, + statusAddr: r2Status, + iscsiAddr: r2Iscsi, + iscsiIQN: iqn, + durableRoot: filepath.Join(art, "g8b-data-r2-store"), + logTag: "g8b-data-r2", + }) + + pollStatus(t, r1Status, 10*time.Second, func(b map[string]any) bool { + h, _ := b["Healthy"].(bool) + rid, _ := b["ReplicaID"].(string) + return h && rid == "r1" + }) + + const durableBlockSize = 4096 + payload := bytes.Repeat([]byte{0x5a}, durableBlockSize) + copy(payload, []byte("g8-acknowledged-write-before-primary-kill")) + c1 := dialG8Iscsi(t, r1Iscsi, iqn) + c1.write10(t, 7, payload) + c1.close(t) + + r1.stop(t) + + r2Failover := pollStatus(t, r2Status, 8*time.Second, func(b map[string]any) bool { + h, _ := b["Healthy"].(bool) + rid, _ := b["ReplicaID"].(string) + epoch, _ := b["Epoch"].(float64) + return h && rid == "r2" && epoch >= 2 + }) + if r2Failover == nil { + t.Fatal("r2: no status response after r1 kill") + } + if h, _ := r2Failover["Healthy"].(bool); !h { + t.Fatalf("r2 did not become Healthy after r1 kill; status=%v", r2Failover) + } + + c2 := dialG8Iscsi(t, r2Iscsi, iqn) + got := c2.read10(t, 7, 1, durableBlockSize) + c2.close(t) + if !bytes.Equal(got, payload) { + t.Fatalf("new primary read mismatch after failover: got prefix=%x want prefix=%x", got[:32], payload[:32]) + } +} + +func TestG8C_L2OldPrimaryReturn_RemainsStaleAfterFailover(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess failover test; -short skip") + } + bins := buildG54Binaries(t) + art := t.TempDir() + + _, masterAddr := startG8Master(t, bins, art) + + r1Data, r1Status := pickAddr(t), pickAddr(t) + r2Data, r2Status := pickAddr(t), pickAddr(t) + r1Ctrl, r2Ctrl := pickAddr(t), pickAddr(t) + r1Store := filepath.Join(art, "r1-store") + r2Store := filepath.Join(art, "r2-store") + + r1 := startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s1", replicaID: "r1", + dataAddr: r1Data, ctrlAddr: r1Ctrl, + statusAddr: r1Status, + durableRoot: r1Store, + logTag: "g8c-r1-initial", + }) + _ = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s2", replicaID: "r2", + dataAddr: r2Data, ctrlAddr: r2Ctrl, + statusAddr: r2Status, + durableRoot: r2Store, + logTag: "g8c-r2", + }) + + pollStatus(t, r1Status, 10*time.Second, func(b map[string]any) bool { + h, _ := b["Healthy"].(bool) + rid, _ := b["ReplicaID"].(string) + return h && rid == "r1" + }) + r1.stop(t) + + r2Failover := pollStatus(t, r2Status, 8*time.Second, func(b map[string]any) bool { + h, _ := b["Healthy"].(bool) + rid, _ := b["ReplicaID"].(string) + epoch, _ := b["Epoch"].(float64) + return h && rid == "r2" && epoch >= 2 + }) + if r2Failover == nil { + t.Fatal("r2: no status response after r1 kill") + } + if h, _ := r2Failover["Healthy"].(bool); !h { + t.Fatalf("r2 did not become Healthy after r1 kill; status=%v", r2Failover) + } + + r1ReturnStatus := pickAddr(t) + _ = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s1", replicaID: "r1", + dataAddr: r1Data, ctrlAddr: r1Ctrl, + statusAddr: r1ReturnStatus, + durableRoot: r1Store, + logTag: "g8c-r1-return", + }) + + r1Returned := pollStatus(t, r1ReturnStatus, 10*time.Second, func(b map[string]any) bool { + _, ok := b["Healthy"] + return ok + }) + if r1Returned == nil { + t.Fatal("returned r1: no status response") + } + if h, _ := r1Returned["Healthy"].(bool); h { + t.Fatalf("returned old primary must remain stale/non-Healthy after r2 failover; status=%v", r1Returned) + } + + r2StillPrimary := pollStatus(t, r2Status, 5*time.Second, func(b map[string]any) bool { + h, _ := b["Healthy"].(bool) + rid, _ := b["ReplicaID"].(string) + epoch, _ := b["Epoch"].(float64) + return h && rid == "r2" && epoch >= 2 + }) + if r2StillPrimary == nil { + t.Fatal("r2: no status response after r1 return") + } + if h, _ := r2StillPrimary["Healthy"].(bool); !h { + t.Fatalf("r2 must remain primary after old r1 returns; status=%v", r2StillPrimary) + } +} diff --git a/seaweed-block/cmd/blockvolume/g9a_ack_profile_test.go b/seaweed-block/cmd/blockvolume/g9a_ack_profile_test.go new file mode 100644 index 0000000000..1e3ed3b147 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/g9a_ack_profile_test.go @@ -0,0 +1,63 @@ +package main + +import ( + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/replication" +) + +func TestG9A_ParseReplicationAckProfile(t *testing.T) { + tests := []struct { + name string + profile string + wantMode replication.DurabilityMode + wantWrite durable.WriteAckPolicy + wantErr bool + }{ + { + name: "best effort default", + profile: "best-effort", + wantMode: replication.DurabilityBestEffort, + wantWrite: durable.WriteAckBestEffort, + }, + { + name: "sync quorum gates foreground writes", + profile: "sync-quorum", + wantMode: replication.DurabilitySyncQuorum, + wantWrite: durable.WriteAckRequireObserverAck, + }, + { + name: "sync all gates foreground writes", + profile: "sync-all", + wantMode: replication.DurabilitySyncAll, + wantWrite: durable.WriteAckRequireObserverAck, + }, + { + name: "unknown profile rejected", + profile: "full-sync-ish", + wantErr: true, + }, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + gotMode, gotWrite, err := parseReplicationAckProfile(tt.profile) + if tt.wantErr { + if err == nil { + t.Fatalf("parseReplicationAckProfile(%q): expected error", tt.profile) + } + return + } + if err != nil { + t.Fatalf("parseReplicationAckProfile(%q): %v", tt.profile, err) + } + if gotMode != tt.wantMode { + t.Fatalf("mode=%v want %v", gotMode, tt.wantMode) + } + if gotWrite != tt.wantWrite { + t.Fatalf("writeAck=%v want %v", gotWrite, tt.wantWrite) + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/g9a_l2_ack_test.go b/seaweed-block/cmd/blockvolume/g9a_l2_ack_test.go new file mode 100644 index 0000000000..b01e70062b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/g9a_l2_ack_test.go @@ -0,0 +1,131 @@ +//go:build subprocess + +package main_test + +import ( + "bytes" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/iscsi" +) + +func TestG9A_L2SyncQuorumWriteFailsWhenReplicaDown(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess strict ACK test; -short skip") + } + bins := buildG54Binaries(t) + art := t.TempDir() + + _, masterAddr := startG8Master(t, bins, art) + + iqn := "iqn.2026-05.example.g9a:v1" + r1Data, r1Status, r1Iscsi := pickAddr(t), pickAddr(t), pickAddr(t) + r2Data, r2Status := pickAddr(t), pickAddr(t) + r1Ctrl, r2Ctrl := pickAddr(t), pickAddr(t) + + _ = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s1", replicaID: "r1", + dataAddr: r1Data, ctrlAddr: r1Ctrl, + statusAddr: r1Status, + iscsiAddr: r1Iscsi, + iscsiIQN: iqn, + durableRoot: filepath.Join(art, "g9a-sync-r1-store"), + logTag: "g9a-sync-r1", + replicationAck: "sync-quorum", + }) + r2 := startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s2", replicaID: "r2", + dataAddr: r2Data, ctrlAddr: r2Ctrl, + statusAddr: r2Status, + durableRoot: filepath.Join(art, "g9a-sync-r2-store"), + logTag: "g9a-sync-r2", + }) + + pollStatus(t, r1Status, 10*time.Second, func(b map[string]any) bool { + h, _ := b["Healthy"].(bool) + rid, _ := b["ReplicaID"].(string) + return h && rid == "r1" + }) + pollStatus(t, r2Status, 10*time.Second, func(b map[string]any) bool { + _, ok := b["Healthy"] + return ok + }) + + const durableBlockSize = 4096 + payload := bytes.Repeat([]byte{0x9a}, durableBlockSize) + copy(payload, []byte("g9a-sync-quorum-first-write")) + c := dialG8Iscsi(t, r1Iscsi, iqn) + c.write10(t, 9, payload) + + r2.stop(t) + + copy(payload, []byte("g9a-sync-quorum-write-while-r2-down")) + status := c.write10Status(t, 10, payload) + c.close(t) + if status == iscsi.StatusGood { + t.Fatalf("sync-quorum RF=2 write while secondary down returned GOOD; want foreground ACK failure") + } +} + +func TestG9A_L2BestEffortWriteSucceedsWhenReplicaDown(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess best-effort ACK test; -short skip") + } + bins := buildG54Binaries(t) + art := t.TempDir() + + _, masterAddr := startG8Master(t, bins, art) + + iqn := "iqn.2026-05.example.g9a-best-effort:v1" + r1Data, r1Status, r1Iscsi := pickAddr(t), pickAddr(t), pickAddr(t) + r2Data, r2Status := pickAddr(t), pickAddr(t) + r1Ctrl, r2Ctrl := pickAddr(t), pickAddr(t) + + _ = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s1", replicaID: "r1", + dataAddr: r1Data, ctrlAddr: r1Ctrl, + statusAddr: r1Status, + iscsiAddr: r1Iscsi, + iscsiIQN: iqn, + durableRoot: filepath.Join(art, "g9a-best-effort-r1-store"), + logTag: "g9a-best-effort-r1", + }) + r2 := startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s2", replicaID: "r2", + dataAddr: r2Data, ctrlAddr: r2Ctrl, + statusAddr: r2Status, + durableRoot: filepath.Join(art, "g9a-best-effort-r2-store"), + logTag: "g9a-best-effort-r2", + }) + + pollStatus(t, r1Status, 10*time.Second, func(b map[string]any) bool { + h, _ := b["Healthy"].(bool) + rid, _ := b["ReplicaID"].(string) + return h && rid == "r1" + }) + pollStatus(t, r2Status, 10*time.Second, func(b map[string]any) bool { + _, ok := b["Healthy"] + return ok + }) + + const durableBlockSize = 4096 + payload := bytes.Repeat([]byte{0xbe}, durableBlockSize) + copy(payload, []byte("g9a-best-effort-first-write")) + c := dialG8Iscsi(t, r1Iscsi, iqn) + c.write10(t, 11, payload) + + r2.stop(t) + + copy(payload, []byte("g9a-best-effort-write-while-r2-down")) + status := c.write10Status(t, 12, payload) + c.close(t) + if status != iscsi.StatusGood { + t.Fatalf("best-effort write while secondary down status=0x%02x want GOOD", status) + } +} diff --git a/seaweed-block/cmd/blockvolume/g9b_l2_join_lifecycle_test.go b/seaweed-block/cmd/blockvolume/g9b_l2_join_lifecycle_test.go new file mode 100644 index 0000000000..e4ef88ccb1 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/g9b_l2_join_lifecycle_test.go @@ -0,0 +1,94 @@ +//go:build subprocess + +package main_test + +import ( + "bytes" + "path/filepath" + "testing" + "time" +) + +func TestG9B_L2GenesisObservationRequiresAssignmentBeforeISCSIReady(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess join lifecycle test; -short skip") + } + bins := buildG54Binaries(t) + art := t.TempDir() + + _, masterAddr := startG8Master(t, bins, art) + + iqn := "iqn.2026-05.example.g9b:v1" + r1Data, r1Status, r1Iscsi := pickAddr(t), pickAddr(t), pickAddr(t) + r2Data, r2Status := pickAddr(t), pickAddr(t) + r1Ctrl, r2Ctrl := pickAddr(t), pickAddr(t) + + _ = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s1", replicaID: "r1", + dataAddr: r1Data, ctrlAddr: r1Ctrl, + statusAddr: r1Status, + iscsiAddr: r1Iscsi, + iscsiIQN: iqn, + durableRoot: filepath.Join(art, "g9b-r1-store"), + logTag: "g9b-r1", + }) + + // With RF=2 topology and only r1 observed, r1 is a candidate, + // not a frontend primary. This pins the G9B rule that heartbeat / + // observation alone does not mint authority. + r1Candidate := pollStatus(t, r1Status, 5*time.Second, func(b map[string]any) bool { + _, ok := b["Healthy"] + return ok + }) + if r1Candidate == nil { + t.Fatal("r1 candidate: no /status response") + } + if h, _ := r1Candidate["Healthy"].(bool); h { + t.Fatalf("r1 became Healthy before full topology/assignment; status=%v", r1Candidate) + } + time.Sleep(800 * time.Millisecond) + r1StillCandidate := pollStatus(t, r1Status, 2*time.Second, func(b map[string]any) bool { + _, ok := b["Healthy"] + return ok + }) + if r1StillCandidate == nil { + t.Fatal("r1 candidate recheck: no /status response") + } + if h, _ := r1StillCandidate["Healthy"].(bool); h { + t.Fatalf("r1 became Healthy from observation alone; status=%v", r1StillCandidate) + } + + _ = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s2", replicaID: "r2", + dataAddr: r2Data, ctrlAddr: r2Ctrl, + statusAddr: r2Status, + durableRoot: filepath.Join(art, "g9b-r2-store"), + logTag: "g9b-r2", + }) + + r1Ready := pollStatus(t, r1Status, 10*time.Second, func(b map[string]any) bool { + h, _ := b["Healthy"].(bool) + rid, _ := b["ReplicaID"].(string) + epoch, _ := b["Epoch"].(float64) + return h && rid == "r1" && epoch >= 1 + }) + if r1Ready == nil { + t.Fatal("r1: no frontend-ready status after r2 joined") + } + if h, _ := r1Ready["Healthy"].(bool); !h { + t.Fatalf("r1 did not become Healthy after assignment stream; status=%v", r1Ready) + } + + const durableBlockSize = 4096 + payload := bytes.Repeat([]byte{0xb9}, durableBlockSize) + copy(payload, []byte("g9b-genesis-assignment-before-iscsi-ready")) + c := dialG8Iscsi(t, r1Iscsi, iqn) + c.write10(t, 13, payload) + got := c.read10(t, 13, 1, durableBlockSize) + c.close(t) + if !bytes.Equal(got, payload) { + t.Fatalf("iSCSI read mismatch after assignment: got prefix=%x want prefix=%x", got[:32], payload[:32]) + } +} diff --git a/seaweed-block/cmd/blockvolume/g9g_l2_product_loop_test.go b/seaweed-block/cmd/blockvolume/g9g_l2_product_loop_test.go new file mode 100644 index 0000000000..24351a0b33 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/g9g_l2_product_loop_test.go @@ -0,0 +1,122 @@ +//go:build subprocess + +package main_test + +import ( + "encoding/json" + "os" + "os/exec" + "path/filepath" + "testing" + "time" +) + +func TestG9G_L2ProductLoopPublishesAssignmentToBlockvolume(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess product-loop test; -short skip") + } + bins := buildG54Binaries(t) + art := t.TempDir() + lifecycleDir := filepath.Join(art, "lifecycle") + specPath := writeG9GClusterSpec(t, art) + + _, masterAddr := startG9GMaster(t, bins, art, lifecycleDir, specPath) + + r2Data, r2Status := pickAddr(t), pickAddr(t) + r2Ctrl := pickAddr(t) + _ = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s2", replicaID: "r2", + dataAddr: r2Data, ctrlAddr: r2Ctrl, + statusAddr: r2Status, + durableRoot: filepath.Join(art, "g9g-r2-store"), + logTag: "g9g-r2", + }) + + r2Ready := pollStatus(t, r2Status, 10*time.Second, func(b map[string]any) bool { + h, _ := b["Healthy"].(bool) + rid, _ := b["ReplicaID"].(string) + epoch, _ := b["Epoch"].(float64) + return h && rid == "r2" && epoch >= 1 + }) + if r2Ready == nil { + t.Fatal("r2: no status response after product-loop assignment") + } + if h, _ := r2Ready["Healthy"].(bool); !h { + t.Fatalf("r2 did not become Healthy from product-loop assignment; status=%v", r2Ready) + } +} + +func writeG9GClusterSpec(t *testing.T, art string) string { + t.Helper() + specPath := filepath.Join(art, "m01.yaml") + raw := []byte(` +volumes: + - id: v1 + size_bytes: 1048576 + replication_factor: 1 + placements: + - server_id: s2 + replica_id: r2 + source: existing_replica +`) + if err := os.WriteFile(specPath, raw, 0o644); err != nil { + t.Fatalf("write cluster spec: %v", err) + } + return specPath +} + +func startG9GMaster(t *testing.T, bins l2bins, art, lifecycleDir, specPath string) (*proc, string) { + t.Helper() + storeDir := filepath.Join(art, "master-store") + _ = os.MkdirAll(storeDir, 0o755) + logPath := filepath.Join(art, "master-g9g.log") + lf, err := os.Create(logPath) + if err != nil { + t.Fatalf("master log: %v", err) + } + cmd := exec.Command(bins.master, + "--authority-store", storeDir, + "--lifecycle-store", lifecycleDir, + "--cluster-spec", specPath, + "--lifecycle-product-loop-interval", "100ms", + "--listen", "127.0.0.1:0", + "--expected-slots-per-volume", "2", + "--freshness-window", "800ms", + "--pending-grace", "100ms", + "--t0-print-ready", + ) + stdout, err := cmd.StdoutPipe() + if err != nil { + lf.Close() + t.Fatalf("master stdout pipe: %v", err) + } + cmd.Stderr = lf + if err := cmd.Start(); err != nil { + lf.Close() + t.Fatalf("master start: %v", err) + } + p := &proc{cmd: cmd, logPath: logPath} + t.Cleanup(func() { p.stop(t); lf.Close() }) + + buf := make([]byte, 512) + n, _ := stdout.Read(buf) + go func() { + for { + b := make([]byte, 1024) + if _, err := stdout.Read(b); err != nil { + return + } + } + }() + var rl struct { + Component, Phase, Addr string + } + if err := json.Unmarshal(buf[:n], &rl); err != nil { + t.Fatalf("parse master ready %q: %v", buf[:n], err) + } + if rl.Addr == "" { + t.Fatalf("master ready: empty addr (line=%q)", buf[:n]) + } + return p, rl.Addr +} diff --git a/seaweed-block/cmd/blockvolume/geometry_flag_record_integration_test.go b/seaweed-block/cmd/blockvolume/geometry_flag_record_integration_test.go new file mode 100644 index 0000000000..28ac228ffe --- /dev/null +++ b/seaweed-block/cmd/blockvolume/geometry_flag_record_integration_test.go @@ -0,0 +1,137 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "os" + "path" + "strings" + "testing" + "time" +) + +// 1.0.1 red: blockvolume compares its geometry flags with the volume record +// BEFORE it creates a local store, and refuses a mismatch as a permanent +// error. A restore target started with half the record's --durable-blocks +// must exit 78 (no restart under the shipped unit) well inside the 30 s +// recovery watchdog, name both block counts, leave no file under +// --durable-root, and never claim HEAD. On 1.0 it creates the store at the +// wrong size, retries geometry_mismatch for 30 s and exits 75 (restart), and +// a right-flag start on the same root then fails on the leftover store. +func TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated(t *testing.T) { + env := startSourceWithSnapshot(t, "v2") + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + b := env.hosts["n-v2"] + args := append([]string{}, env.volArgsFor(b)...) + for i := range args { + if args[i] == "--durable-blocks" { + args[i+1] = "32768" // the record says 65536 + } + } + start := time.Now() + d := env.h.start(t, "blockvolume-v2-wrong-flag", env.h.volume, args...) + err := d.wait(90 * time.Second) + took := time.Since(start) + refusal := d.line("65536") + left := listTree(b.root) + head := env.headOf(t, "v2") + t.Logf("wrong-flag start: exit %v after %v; refusal line %q; HEAD %s; files under --durable-root:\n%s", err, took.Round(time.Millisecond), refusal, head, left) + + var problems []string + if code := exitCode(err); code != 78 { + problems = append(problems, "exit is not 78 (a permanent refusal)") + } + if took >= 20*time.Second { + problems = append(problems, "the refusal waited for the recovery watchdog") + } + if refusal == "" || !strings.Contains(refusal, "32768") || !strings.Contains(refusal, "--durable-blocks") { + problems = append(problems, "no log line names --durable-blocks 32768 against the record's 65536") + } + if entries, _ := os.ReadDir(b.root); len(entries) != 0 { + problems = append(problems, "a local store was created under --durable-root") + } + if !strings.Contains(head, `"epoch":0,"holder":""`) { + problems = append(problems, "HEAD was claimed") + } + if len(problems) > 0 { + t.Fatalf("1.0.1: %s", strings.Join(problems, "; ")) + } +} + +// INV-VOL-GEOMETRY-FLAGS-RECORD-001, the corrupt record: in create mode, a +// volume record that is there but does not decode is refused for good (exit +// 78) before any local store exists, never taken as "absent" and never +// retried. The filer stays up and answers the startup checks; v2's VOLUME +// entry is made undecodable. A wrong and a right --durable-blocks alike exit +// 78 and leave nothing under --durable-root. With the entry restored the wrong +// flag is refused (78, mismatch) and the right flag serves. (A filer that +// cannot deliver the record is the retryable case, 75: the unit test.) +func TestCorruptRecordIsRefusedBeforeTheStoreIsCreated(t *testing.T) { + env := startSourceWithSnapshot(t, "v2") + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + b := env.hosts["n-v2"] + right := append([]string{}, env.volArgsFor(b)...) + wrong := append([]string{}, right...) + for i := range wrong { + if wrong[i] == "--durable-blocks" { + wrong[i+1] = "32768" + } + } + ctx := context.Background() + cl := env.cluster.client(t, "") + dir := path.Join(env.chunkPath, "v2") + entry, err := cl.LookupEntry(ctx, dir, "VOLUME") + if err != nil { + t.Fatal(err) + } + record := append([]byte(nil), entry.Content...) + entry.Content = []byte("{") + if err := cl.UpdateEntry(ctx, dir, entry, nil); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + name string + args []string + }{{"wrong", wrong}, {"right", right}} { + d := env.h.start(t, "blockvolume-v2-"+c.name+"-corrupt", env.h.volume, c.args...) + err := d.wait(60 * time.Second) + line := d.line("is unreadable (corrupt:") + entries, _ := os.ReadDir(b.root) + t.Logf("%s flag over a corrupt record: exit %v; %q; files under --durable-root %d", c.name, err, line, len(entries)) + if exitCode(err) != 78 || !strings.Contains(line, "no local store was created") || len(entries) != 0 { + t.Fatalf("1.0.1: a %s-flag first start over a corrupt record must exit 78 before creating anything; exit %v, line %q, %d files", c.name, err, line, len(entries)) + } + } + entry.Content = record + if err := cl.UpdateEntry(ctx, dir, entry, nil); err != nil { + t.Fatal(err) + } + d := env.h.start(t, "blockvolume-v2-wrong-readable", env.h.volume, wrong...) + if err := d.wait(60 * time.Second); exitCode(err) != 78 { + t.Fatalf("with the record readable again, the wrong flag must be refused (78); exit %v", err) + } + served := env.startTarget(t, "v2", "blockvolume-v2-right-readable") + served.kill(t) +} + +// Guard: a first start with the filer stopped ends at the startup filer +// check (exit 1) before the record check and before any store exists. +func TestFirstStartWithTheFilerDownCreatesNoStore(t *testing.T) { + env := startSourceWithSnapshot(t, "v2") + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + b := env.hosts["n-v2"] + env.cluster.stopProc(t, "filer") + d := env.h.start(t, "blockvolume-v2-filer-down", env.h.volume, env.volArgsFor(b)...) + err := d.wait(120 * time.Second) + env.cluster.restartProc(t, "filer") + w4WaitTCP(t, env.cluster.filerGRPC, 30*time.Second) + entries, _ := os.ReadDir(b.root) + t.Logf("filer down: exit %v; %q; files under --durable-root %d", err, d.line("needs exactly one filer"), len(entries)) + if exitCode(err) != 1 || d.line("needs exactly one filer") == "" || len(entries) != 0 { + t.Fatalf("a first start with the filer down must end at the startup filer check without a store; exit %v, %d files", err, len(entries)) + } +} diff --git a/seaweed-block/cmd/blockvolume/handoff_cli_output_test.go b/seaweed-block/cmd/blockvolume/handoff_cli_output_test.go new file mode 100644 index 0000000000..895d5705b2 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/handoff_cli_output_test.go @@ -0,0 +1,76 @@ +package main_test + +import ( + "encoding/json" + "fmt" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// handoffHeadJSON adapts the CLI's typed show envelope to the canonical HEAD +// bytes the process tests inspect. A public volume name is not its directory. +func handoffHeadJSON(out string) (string, error) { + var result struct { + Head *layout.Head `json:"head"` + } + if err := json.Unmarshal([]byte(out), &result); err != nil { + return "", err + } + if result.Head == nil { + return "", fmt.Errorf("show returned no HEAD") + } + raw, err := result.Head.Encode() + return string(raw), err +} + +func handoffDeleteCompleted(out string) bool { + var result struct { + Volume string `json:"volume"` + State string `json:"state"` + } + return json.Unmarshal([]byte(out), &result) == nil && result.Volume != "" && result.State == layout.StateDeleted +} + +func TestHandoffShowUsesTheNestedLayoutHead(t *testing.T) { + for _, state := range []string{layout.StateLive, layout.StateDeleted} { + t.Run(state, func(t *testing.T) { + head := layout.Head{VolumeID: layout.VolumeID{1}, State: state, Activity: layout.Activity{Kind: layout.ActIdle}} + // This is chunkShow's public JSON shape, not HEAD's on-filer codec. + raw, err := json.Marshal(struct { + Volume any `json:"volume"` + Head *layout.Head `json:"head"` + }{Head: &head}) + if err != nil { + t.Fatal(err) + } + got, err := handoffHeadJSON(string(raw)) + if err != nil || !strings.Contains(got, `"epoch":0,"holder":""`) || (state == layout.StateDeleted && !strings.Contains(got, `"state":"deleted"`)) { + t.Fatalf("show adapter: %s, %v", got, err) + } + }) + } + for _, raw := range []string{`{}`, `{"head":null}`, `{"head":{"State":"deleted"}}`, `not JSON`} { + if got, err := handoffHeadJSON(raw); err == nil { + t.Errorf("invalid/absent HEAD accepted: %s -> %s", raw, got) + } + } +} + +func TestHandoffDeleteUsesTheCLIState(t *testing.T) { + for _, row := range []struct { + raw string + want bool + }{ + {`{"volume":"v2-34071d5f","state":"deleted"}`, true}, + {`{"volume":"v2-34071d5f","state":"deleting"}`, false}, + {`{"completed":true}`, false}, + {`{"state":"deleted"}`, false}, + {`not JSON`, false}, + } { + if got := handoffDeleteCompleted(row.raw); got != row.want { + t.Errorf("delete completion for %s: %v, want %v", row.raw, got, row.want) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/handoff_layout_identity_cache_test.go b/seaweed-block/cmd/blockvolume/handoff_layout_identity_cache_test.go new file mode 100644 index 0000000000..1984dc64ff --- /dev/null +++ b/seaweed-block/cmd/blockvolume/handoff_layout_identity_cache_test.go @@ -0,0 +1,52 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "net" + "sync/atomic" + "testing" + + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" +) + +type handoffIdentityServer struct { + control.UnimplementedLifecycleServiceServer + calls atomic.Int32 +} + +func (s *handoffIdentityServer) GetVolume(_ context.Context, req *control.GetLifecycleVolumeRequest) (*control.CreateVolumeResponse, error) { + s.calls.Add(1) + return &control.CreateVolumeResponse{VolumeId: req.VolumeId, LayoutId: "00112233445566778899aabbccddeeff"}, nil +} + +// Known-zero's source and target env constructors begin without a cache. +// Resolve through the real helper/RPC, then require cached reads to keep +// working when the master is unavailable (the crash fixtures depend on it). +func TestHandoffLayoutIdentityCacheStartsEmpty(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + rpc := &handoffIdentityServer{} + control.RegisterLifecycleServiceServer(server, rpc) + go server.Serve(listener) + t.Cleanup(server.Stop) + env := &handoffEnv{h: &plannedHandoffHarness{t: t, masterAddr: listener.Addr().String()}} + const want = "00112233445566778899aabbccddeeff" + for _, volume := range []string{"kzext4", "kzxfs", "kzext4", "kzxfs"} { + if got := env.layoutID(volume); got != want { + t.Fatalf("%s id=%s want %s", volume, got, want) + } + } + if got := rpc.calls.Load(); got != 2 { + t.Fatalf("resolve calls=%d want two distinct volumes", got) + } + server.Stop() + if got := env.layoutID("kzext4"); got != want { + t.Fatalf("cached id after master stop=%s", got) + } +} diff --git a/seaweed-block/cmd/blockvolume/harness_helpers_test.go b/seaweed-block/cmd/blockvolume/harness_helpers_test.go new file mode 100644 index 0000000000..56dec68c19 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/harness_helpers_test.go @@ -0,0 +1,63 @@ +package main_test + +import ( + "bytes" + "fmt" + "testing" +) + +// pattern repeats s to exactly one 4096-byte block. It panics unless len(s) +// divides 4096: a shorter block would be a short NVMe write, which hangs the +// in-test initiator until its deadline instead of failing at once. +func pattern(s string) []byte { + if len(s) == 0 || 4096%len(s) != 0 { + panic(fmt.Sprintf("pattern %q: %d bytes do not divide a 4096-byte block", s, len(s))) + } + return bytes.Repeat([]byte(s), 4096/len(s)) +} + +// TestPatternIsExactlyOneBlock: a 16-byte string fills one block; a 15-byte +// one (it would make 4095 bytes) panics with its name. +func TestPatternIsExactlyOneBlock(t *testing.T) { + if b := pattern("sixteen-bytes!!!"); len(b) != 4096 { + t.Fatalf("pattern of 16 bytes: %d bytes; want 4096", len(b)) + } + defer func() { + if r := recover(); r == nil { + t.Fatal("pattern of 15 bytes returned a block; want a panic (4096 is not a multiple of 15)") + } + }() + pattern("fifteen-bytes!!") +} + +// TestHarnessParsersReadTheNamedVolume: the adoption, plain-detach and +// forced-move parsers read the volume they are given, and refuse a line or +// answer for another volume; the v1 forms are those parsers for v1. +func TestHarnessParsersReadTheNamedVolume(t *testing.T) { + v4 := `2026/11/23 07:30:06 blockvolume: volume v4 adopted as PRIMARY at r1@3 (EV=1) process="n-v4" server="n-v4"` + if e, err := adoptedEpochOf("v4", v4); err != nil || e != 3 { + t.Fatalf("adoptedEpochOf v4: %d %v; want 3", e, err) + } + if _, err := adoptedEpochOf("v1", v4); err == nil { + t.Fatal("adoptedEpochOf v1 read a v4 adoption line") + } + if _, err := adoptedEpoch(v4); err == nil { + t.Fatal("adoptedEpoch (v1) read a v4 adoption line") + } + + seal := `{"volumeID":"v6","headGen":4,"headEpoch":2,"cutLSN":9,"lastWrittenLSN":9}` + if g, err := sealedGenOf(seal, "sealed HEAD generation: 4\n", "v6", 2); err != nil || g != 4 { + t.Fatalf("sealedGenOf v6: %d %v; want 4", g, err) + } + if _, err := sealedGen(seal, "sealed HEAD generation: 4\n", 2); err == nil { + t.Fatal("sealedGen (v1) accepted a v6 detach answer") + } + + move := "forced move issued: volume v6 request force-v6: r1@1 on n-v6 -> r1@2 on n-v7 (kept HEAD gen 3, remote LSN 8)\n" + if e2, err := forcedEpochOf(move, "v6", 1, "n-v6", "n-v7"); err != nil || e2 != 2 { + t.Fatalf("forcedEpochOf v6: %d %v; want 2", e2, err) + } + if _, err := forcedEpoch(move, 1, "n-v6", "n-v7"); err == nil { + t.Fatal("forcedEpoch (v1) read a v6 forced move") + } +} diff --git a/seaweed-block/cmd/blockvolume/head_size_integration_test.go b/seaweed-block/cmd/blockvolume/head_size_integration_test.go new file mode 100644 index 0000000000..8ebd6ecd7a --- /dev/null +++ b/seaweed-block/cmd/blockvolume/head_size_integration_test.go @@ -0,0 +1,640 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "math/rand" + "net" + "net/http" + "net/url" + "os" + "os/exec" + "path" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// HEAD size against volume size, informative: it measures, +// it does not judge. Runs only with HEADSZ_RUN=1, on a host booked for it. +// +// For each size in HEADSZ_SIZES (default 10G,100G,1T): one volume of that +// size; one 4 KiB block written in every 1 GiB segment; a snapshot (cut 1); +// then HEADSZ_CHANGE_CUTS snapshots (default 3), each after changing one +// block. Per cut it records the HEAD entry's byte size as the filer returns +// it, the number of segments HEAD lists, the cut's total and barrier time, +// and the chunks and bytes the cut uploaded. A size the durable root has no +// room for is recorded as refused by the blockvolume's headroom check, never +// shrunk or bypassed. The JSON report goes to HEADSZ_REPORT. +// +// HEADSZ_SNAPSHOT_TIMEOUT is the snapshot command's --timeout (default 60s; +// the server caps it at its own operation deadline). HEADSZ_ATTEMPTS (default +// 1) retries a failed cut with the same request id; every attempt is +// recorded with the volume's chunk-key count in the filer after it, so a +// retry shows whether an earlier attempt's uploads were kept. A cut that never +// completes is recorded as cut_not_completed, not failed. +// +// The filer runs on its default store (leveldb2) under the test's directory; +// a filer.toml anywhere weed would read one fails the test before any start, +// so the store measured is the one named in the report. + +const headSegmentBytes = 1 << 30 + +// headSzAttempt is one snapshot command for one cut: a failed attempt is +// resent with the same request id, as the command's refusal says. +type headSzAttempt struct { + Attempt int `json:"attempt"` + ExitCode int `json:"exit_code"` + Code string `json:"code,omitempty"` + Message string `json:"message,omitempty"` + WallMs float64 `json:"wall_ms"` + KeysAfter int `json:"chunk_keys_after"` + LastCutTotalMs float64 `json:"last_cut_total_ms"` + LastCutChunks int `json:"last_cut_uploaded_chunks"` + // DirtyAfter is the volume's DirtyChunks (capture candidates) after the + // attempt: on a failed attempt it shows whether the work done was kept. + DirtyAfter int `json:"dirty_chunks_after"` + // ChunkStatusAfter is the volume's whole chunk section of its durable + // status after the attempt, as served (every counter and the full + // LastCut), so a term no named field covers can still be read. + ChunkStatusAfter json.RawMessage `json:"chunk_status_after,omitempty"` + // the volume's last SUCCESSFUL cut's candidates, unchanged chunks and + // payload (streaming, copy, upload) wall time, as its durable status + // reports them (a failed attempt does not change them) + LastCutCandidates int `json:"last_cut_candidate_chunks"` + LastCutUnchanged int `json:"last_cut_unchanged_chunks"` + LastCutPayloadMs float64 `json:"last_cut_payload_ms"` +} + +type headSzCut struct { + Cut int `json:"cut"` + Completed bool `json:"completed"` + Attempts []headSzAttempt `json:"attempts"` + ChangedBlocks int `json:"changed_blocks"` + HeadBytes int `json:"head_bytes"` + HeadSegments int `json:"head_segments"` + CutTotalMs float64 `json:"cut_total_ms"` + BarrierPauseMs float64 `json:"cut_barrier_pause_ms"` + UploadedChunks int `json:"uploaded_chunks"` + UploadedBytes int64 `json:"uploaded_bytes"` + SnapshotMs float64 `json:"snapshot_command_ms"` +} + +type headSzSize struct { + Size string `json:"size"` + Bytes uint64 `json:"bytes"` + Segments int `json:"segments"` + Result string `json:"result"` // measured | refused_headroom | cut_not_completed + Refusal string `json:"refusal,omitempty"` + WriteMs float64 `json:"write_ms,omitempty"` + // DirtyBeforeCut1 is the volume's DirtyChunks (its capture candidates) + // from the durable status right before the first cut. + DirtyBeforeCut1 int `json:"dirty_chunks_before_cut1"` + Cuts []headSzCut `json:"cuts,omitempty"` + HeadPerGiB float64 `json:"head_bytes_per_gib,omitempty"` +} + +type headSzReport struct { + StartedAt time.Time `json:"started_at"` + FilerStore string `json:"filer_store"` + ChunkPath string `json:"chunk_path"` + Sizes []headSzSize `json:"sizes"` +} + +func headSzParse(t *testing.T, s string) uint64 { + t.Helper() + s = strings.ToUpper(strings.TrimSpace(s)) + mul := map[byte]uint64{'G': 1 << 30, 'T': 1 << 40}[s[len(s)-1]] + n, err := strconv.ParseUint(s[:len(s)-1], 10, 64) + if mul == 0 || err != nil || n == 0 { + t.Fatalf("HEADSZ_SIZES: %q is not G or T", s) + } + return n * mul +} + +// headSzAmbientFilerToml fails the test when weed could read a filer.toml +// other than none: its working directory (the cluster dir) and the standard +// configuration directories. +func headSzAmbientFilerToml(t *testing.T, clusterDir string) { + t.Helper() + home, _ := os.UserHomeDir() + for _, d := range []string{clusterDir, filepath.Join(home, ".seaweedfs"), "/usr/local/etc/seaweedfs", "/etc/seaweedfs"} { + if _, err := os.Stat(filepath.Join(d, "filer.toml")); err == nil { + t.Fatalf("a filer.toml in %s would replace the default filer store: remove it or run elsewhere", d) + } + } +} + +func TestHeadSizeAgainstVolumeSize(t *testing.T) { + if os.Getenv("HEADSZ_RUN") != "1" { + t.Skip("HEADSZ_RUN=1 not set") + } + sizes := strings.Split(os.Getenv("HEADSZ_SIZES"), ",") + if os.Getenv("HEADSZ_SIZES") == "" { + sizes = []string{"10G", "100G", "1T"} + } + changeCuts := 3 + if v := os.Getenv("HEADSZ_CHANGE_CUTS"); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 0 { + t.Fatalf("HEADSZ_CHANGE_CUTS=%q", v) + } + changeCuts = n + } + cfg := headSzConfig{snapshotTimeout: "60s", attempts: 1} + if v := os.Getenv("HEADSZ_SNAPSHOT_TIMEOUT"); v != "" { + if _, err := time.ParseDuration(v); err != nil { + t.Fatalf("HEADSZ_SNAPSHOT_TIMEOUT=%q: %v", v, err) + } + cfg.snapshotTimeout = v + } + if v := os.Getenv("HEADSZ_ATTEMPTS"); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 1 { + t.Fatalf("HEADSZ_ATTEMPTS=%q", v) + } + cfg.attempts = n + } + var vols []headSzVol + for _, s := range sizes { + vols = append(vols, headSzVol{id: "h" + strings.ToLower(strings.TrimSpace(s)), bytes: headSzParse(t, s)}) + } + env, clusterDir := headSzStartCluster(t, "headsz", vols) + rep := &headSzReport{StartedAt: time.Now().UTC(), ChunkPath: env.chunkPath, + FilerStore: "leveldb2 (weed filer default store), -defaultStoreDir=" + filepath.Join(clusterDir, "f") + ", no filer.toml"} + defer func() { + if p := os.Getenv("HEADSZ_REPORT"); p != "" { + b, _ := json.MarshalIndent(rep, "", " ") + if err := os.WriteFile(p, append(b, '\n'), 0o644); err != nil { + t.Errorf("HEADSZ_REPORT: %v", err) + } + } + }() + + for _, s := range sizes { + rep.Sizes = append(rep.Sizes, headSzOne(t, env, cfg, s, changeCuts)) + } +} + +// headSzVol is one volume of the test cluster spec. server "" places it on +// s1 (replica rN); any other server gets its own node in the spec and the +// volume's one replica r1 on it (a restore or fork target, as +// startHandoffEnvWith places its targets). +type headSzVol struct { + id string + bytes uint64 + server string + // host, when set, is another machine that runs this volume's blockvolume: + // its spec data and ctrl addresses are host: (ports picked here, not + // probed there), and the test running on that host uses the same ones. + host string + // restoreTarget lists the volume with its placement only, no size_bytes: + // it has no volume record until a restore creates it. + restoreTarget bool +} + +// headSzStartCluster starts one weed cluster (the filer's default store, no +// filer.toml) and a blockmaster whose spec holds vols. It returns the env, +// with one bvHost per volume, and the cluster dir. The chunk path is +// /-. +func headSzStartCluster(t *testing.T, prefix string, vols []headSzVol) (*handoffEnv, string) { + t.Helper() + h := newPlannedHandoffHarness(t) + clusterDir := filepath.Join(h.dir, "weed") + if err := os.MkdirAll(clusterDir, 0o700); err != nil { + t.Fatal(err) + } + headSzAmbientFilerToml(t, clusterDir) + env := &handoffEnv{h: h, cluster: startWorkspaceWeedWith(t, clusterDir, w4WeedOpts{VolumeSizeLimitMB: 1024, VolumeMax: 64}), + chunkPath: fmt.Sprintf("/%s-%d", prefix, time.Now().UnixNano()), hosts: map[string]bvHost{}} + var spec strings.Builder + nodes := fmt.Sprintf(" - server_id: s1\n data_addr: %s\n ctrl_addr: %s\n", h.dataAddr, h.ctrlAddr) + for i, v := range vols { + server, replica := "s1", fmt.Sprintf("r%d", i+1) + if v.server != "" { + server, replica = v.server, "r1" + } + b := bvHost{id: v.id, server: server, replica: replica, volume: v.id, root: filepath.Join(h.dir, "vol-"+v.id), + data: handoffAddress(t), ctrl: handoffAddress(t), status: headSzLoopbackAddr(t), nvme: headSzLoopbackAddr(t)} + if v.host != "" { + b.data, b.ctrl = headSzRemoteAddr(t, v.host), headSzRemoteAddr(t, v.host) + } + env.hosts[v.id] = b + if v.server != "" { + nodes += fmt.Sprintf(" - server_id: %s\n data_addr: %s\n ctrl_addr: %s\n", server, b.data, b.ctrl) + } + size := fmt.Sprintf(" size_bytes: %d\n", v.bytes) + if v.restoreTarget { + size = "" + } + fmt.Fprintf(&spec, " - id: %s\n%s replication_factor: 1\n placements:\n - server_id: %s\n replica_id: %s\n", v.id, size, server, replica) + } + specPath := filepath.Join(h.dir, "cluster-spec.yaml") + if err := os.WriteFile(specPath, []byte("nodes:\n"+nodes+"volumes:\n"+spec.String()), 0o644); err != nil { + t.Fatal(err) + } + mstate := filepath.Join(h.dir, "master") + margs := []string{"--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"), + "--cluster-spec", specPath, "--expected-slots-per-volume", "1", "--listen", h.masterAddr, + "--workspace-rpc", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath} + if testListenHost() != "127.0.0.1" { + // a lab run spanning two hosts: blockmaster refuses a non-loopback listen without this + margs = append(margs, "--insecure-external-bind") + } + master := h.start(t, "blockmaster", h.master, margs...) + master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + return env, clusterDir +} + +// headSzLoopbackAddr picks a free 127.0.0.1 port from the harness's range: +// blockvolume's NVMe/TCP target and status endpoint refuse any non-loopback +// bind, and the test (user-space client, kernel nvme connect, sw-block ops +// --status-addr) always reaches them from the same host as that blockvolume, +// also when SWBLOCK_TEST_LISTEN_HOST names a host address. +func headSzLoopbackAddr(t *testing.T) string { + t.Helper() + handoffPorts.Lock() + defer handoffPorts.Unlock() + if handoffPorts.used == nil { + handoffPorts.used = map[int]bool{} + } + for i := 0; i < 500; i++ { + lo, hi := testPortSpan(10000, 20000) + p := lo + rand.Intn(hi-lo) + if handoffPorts.used[p] || !claimHostPort(p) { + continue + } + addr := fmt.Sprintf("127.0.0.1:%d", p) + if ln, err := net.Listen("tcp", addr); err == nil { + ln.Close() + handoffPorts.used[p] = true + return addr + } + } + t.Fatal("no free loopback port") + return "" +} + +// headSzRemoteAddr picks host: for a process on another machine from +// the same port range handoffAddress uses, never handing out a port twice. +func headSzRemoteAddr(t *testing.T, host string) string { + t.Helper() + handoffPorts.Lock() + defer handoffPorts.Unlock() + if handoffPorts.used == nil { + handoffPorts.used = map[int]bool{} + } + for i := 0; i < 500; i++ { + lo, hi := testPortSpan(10000, 20000) + p := lo + rand.Intn(hi-lo) + if !handoffPorts.used[p] { + handoffPorts.used[p] = true + return fmt.Sprintf("%s:%d", host, p) + } + } + t.Fatal("no port left for " + host) + return "" +} + +// headSzConfig: HEADSZ_SNAPSHOT_TIMEOUT is the snapshot command's --timeout +// (the server caps it at its own operation deadline); HEADSZ_ATTEMPTS is how +// many times one cut is tried before it is recorded as not completed. name +// is the snapshot name prefix ("headsz" when empty): cut N is "-N". +type headSzConfig struct { + snapshotTimeout string + attempts int + name string +} + +// headSzStartVolume starts b's blockvolume for a volume of bytes (no capture +// interval, no snapshot schedule: cuts happen only when the test asks), waits +// until it adopted the volume as PRIMARY and its frontend is ready, and +// returns it. When the volume refuses for headroom it returns nil and the +// refusal line; any other early exit or timeout fails the test. The caller +// stops the daemon. +func headSzStartVolume(t *testing.T, env *handoffEnv, b bvHost, bytes uint64, extra ...string) (*daemon, string) { + t.Helper() + env.volExtra = append([]string{"--durable-blocks", strconv.FormatUint(bytes/4096, 10), "--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}, extra...) + d := env.h.start(t, "blockvolume-"+b.id, env.h.volume, env.volArgsFor(b)...) + primary := fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at %s@", b.volume, b.replica) + end := time.Now().Add(120 * time.Second) + for !d.has(primary) { + select { + case <-d.done: + if l := d.line("bytes free"); l != "" { + return nil, strings.TrimSpace(l) + } + t.Fatalf("blockvolume %s exited before it adopted its volume: %v", b.id, d.err) + case <-time.After(200 * time.Millisecond): + } + if time.Now().After(end) { + t.Fatalf("blockvolume %s did not adopt its volume in 120 s", b.id) + } + } + poll(t, 60*time.Second, b.id+" never reported its frontend ready", func() bool { return volumeFrontendReady(b.status, b.volume) }) + return d, "" +} + +// headSzOne measures one size; its blockvolume is stopped at the end. +func headSzOne(t *testing.T, env *handoffEnv, cfg headSzConfig, size string, changeCuts int) headSzSize { + t.Helper() + bytes := headSzParse(t, size) + id := "h" + strings.ToLower(strings.TrimSpace(size)) + b := env.hosts[id] + row := headSzSize{Size: strings.TrimSpace(size), Bytes: bytes, Segments: int((bytes + headSegmentBytes - 1) / headSegmentBytes)} + d, refusal := headSzStartVolume(t, env, b, bytes) + if d == nil { + row.Result, row.Refusal = "refused_headroom", refusal + return row + } + defer d.term(t, 60*time.Second) + + c := dialNVMe(t, b.nvme, plannedHandoffNQN) + write := func(lba uint64, tag string) { + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + c.write(t, lba, f1Block(id, 0, tag, lba)) + } + start := time.Now() + for seg := 0; seg < row.Segments; seg++ { + write(uint64(seg)*headSegmentBytes/4096, "seg") + } + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + c.flush(t) + row.WriteMs = ms(time.Since(start)) + row.DirtyBeforeCut1 = headSzDirty(t, b) + for cut := 1; cut <= 1+changeCuts; cut++ { + changed := 0 + if cut > 1 { + write(uint64(cut), fmt.Sprintf("change%d", cut)) + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + c.flush(t) + changed = 1 + } + r := headSzCutOnce(t, env, cfg, b, cut, changed) + row.Cuts = append(row.Cuts, r) + if !r.Completed { + row.Result = "cut_not_completed" + return row + } + } + row.Result = "measured" + if row.Segments > 0 && len(row.Cuts) > 0 { + row.HeadPerGiB = float64(row.Cuts[0].HeadBytes) / float64(row.Segments) + } + return row +} + +// headSzCutOnce takes one snapshot, retried with the same request id up to +// cfg.attempts times, and reads what it wrote: HEAD from the filer, the cut +// from the volume's durable status. After every attempt it counts the +// volume's chunk keys in the filer, so a retry shows whether the chunks an +// earlier attempt uploaded are still there. +func headSzCutOnce(t *testing.T, env *handoffEnv, cfg headSzConfig, b bvHost, cut, changed int) headSzCut { + t.Helper() + r := headSzCut{Cut: cut, ChangedBlocks: changed} + name := cfg.name + if name == "" { + name = "headsz" + } + start := time.Now() + for a := 1; a <= cfg.attempts; a++ { + as := time.Now() + out, code := headSzRun(t, env, cfg.snapshotTimeout, "ops", "chunk", "snapshot", "--volume", b.volume, "--status-addr", b.status, "--timeout", cfg.snapshotTimeout, + "--name", fmt.Sprintf("%s-%d", name, cut), "--request-id", fmt.Sprintf("%s-%s-%d", name, b.volume, cut)) + at := headSzAttempt{Attempt: a, ExitCode: code, WallMs: ms(time.Since(as)), KeysAfter: env.poolObjects(t, b.volume)} + if code != 0 { + var e struct{ Code, Message string } + if json.Unmarshal([]byte(strings.TrimSpace(out)), &e) == nil { + at.Code, at.Message = e.Code, e.Message + } else { + at.Message = strings.TrimSpace(out) + } + } + at.DirtyAfter = headSzDirty(t, b) + at.ChunkStatusAfter = headSzChunkStatus(t, b) + lc := headSzLastCut(t, b) + at.LastCutTotalMs, at.LastCutChunks = float64(lc.TotalNs)/1e6, lc.UploadedChunks + at.LastCutCandidates, at.LastCutUnchanged, at.LastCutPayloadMs = lc.CandidateChunks, lc.UnchangedChunks, float64(lc.PayloadNs)/1e6 + r.Attempts = append(r.Attempts, at) + if code == 0 { + r.Completed = true + break + } + } + r.SnapshotMs = ms(time.Since(start)) + if !r.Completed { + return r + } + var st struct { + Volumes []struct { + VolumeID string + Chunk *struct { + Stats struct { + LastCut *struct { + TotalNs, BarrierPauseNs int64 + UploadedChunks int + UploadedBytes int64 + } + } + } + } + } + if err := json.Unmarshal(headSzGet(t, "http://"+b.status+"/status/durable?volume="+b.volume, 4<<20), &st); err != nil { + t.Fatalf("durable status of %s: %v", b.volume, err) + } + for _, s := range st.Volumes { + if s.VolumeID == b.volume && s.Chunk != nil && s.Chunk.Stats.LastCut != nil { + l := s.Chunk.Stats.LastCut + r.CutTotalMs, r.BarrierPauseMs = float64(l.TotalNs)/1e6, float64(l.BarrierPauseNs)/1e6 + r.UploadedChunks, r.UploadedBytes = l.UploadedChunks, l.UploadedBytes + } + } + // The volume's store directory is -, its id from blockmaster's + // record. HEAD names the current root; the root names the segments. + id, err := layout.ParseVolumeID(env.layoutID(b.volume)) + if err != nil { + t.Fatal(err) + } + dir := "http://" + env.cluster.filerHTTP + path.Join(env.chunkPath, layout.VolumeDir(b.volume, id)) + raw := headSzGet(t, dir+"/"+layout.HeadName, 256<<20) + r.HeadBytes = len(raw) + head, err := layout.DecodeHead(raw, 0, id) + if err != nil { + t.Fatalf("HEAD of %s (%d bytes): %v", b.volume, len(raw), err) + } + if head.Current != nil { + root, err := layout.DecodeRoot(headSzGet(t, dir+"/"+head.Current.Path(), 256<<20)) + if err != nil { + t.Fatalf("current root of %s: %v", b.volume, err) + } + r.HeadSegments = len(root.Segments) + } + return r +} + +// headSzLastCutStats is the part of the volume's last cut an attempt records. +type headSzLastCutStats struct { + TotalNs, PayloadNs int64 + UploadedChunks, CandidateChunks, UnchangedChunks int +} + +// headSzLastCut reads the volume's last cut from its durable status; zeros +// when there is no last cut yet. +func headSzLastCut(t *testing.T, b bvHost) headSzLastCutStats { + t.Helper() + var st struct { + Volumes []struct { + VolumeID string + Chunk *struct { + Stats struct { + LastCut *headSzLastCutStats + } + } + } + } + if err := json.Unmarshal(headSzGet(t, "http://"+b.status+"/status/durable?volume="+b.volume, 4<<20), &st); err != nil { + t.Fatalf("durable status of %s: %v", b.volume, err) + } + for _, s := range st.Volumes { + if s.VolumeID == b.volume && s.Chunk != nil && s.Chunk.Stats.LastCut != nil { + return *s.Chunk.Stats.LastCut + } + } + return headSzLastCutStats{} +} + +// headSzCountDir counts the entries of one filer directory by its JSON +// listing; a directory that does not exist yet counts 0. +func headSzCountDir(t *testing.T, env *handoffEnv, dir string) int { + t.Helper() + c := &http.Client{Timeout: 30 * time.Second} + n, last := 0, "" + for { + req, _ := http.NewRequest(http.MethodGet, "http://"+env.cluster.filerHTTP+dir+"/?limit=1000&lastFileName="+url.QueryEscape(last), nil) + req.Header.Set("Accept", "application/json") + resp, err := c.Do(req) + if err != nil { + t.Fatalf("filer list %s: %v", dir, err) + } + if resp.StatusCode == http.StatusNotFound { + resp.Body.Close() + return n + } + var page struct { + Entries []struct{ FullPath string } + ShouldDisplayLoadMore bool + LastFileName string + } + err = json.NewDecoder(resp.Body).Decode(&page) + resp.Body.Close() + if err != nil { + t.Fatalf("filer list %s: %v", dir, err) + } + n += len(page.Entries) + if !page.ShouldDisplayLoadMore || page.LastFileName == "" { + return n + } + last = page.LastFileName + } +} + +// headSzRun runs sw-block with its own bound, the snapshot command's +// --timeout plus a minute, so the server's operation deadline answers first +// (the shared runner's fixed 150 s would kill a longer cut). A command that +// still has to be killed returns exit code -1 and its output, a recorded +// attempt, never a test failure. +func headSzRun(t *testing.T, env *handoffEnv, timeout string, args ...string) (string, int) { + t.Helper() + d, err := time.ParseDuration(timeout) + if err != nil { + t.Fatalf("timeout %q: %v", timeout, err) + } + ctx, cancel := context.WithTimeout(context.Background(), d+time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, env.h.cli, args...) + cmd.Dir = env.h.dir + cmd.WaitDelay = 5 * time.Second + var stdout, stderr strings.Builder + cmd.Stdout, cmd.Stderr = &stdout, &stderr + err = cmd.Run() + env.h.logCommand(args, stdout.String(), stderr.String(), err) + var exit *exec.ExitError + switch { + case err == nil: + return stdout.String(), 0 + case errors.As(err, &exit) && ctx.Err() == nil: + return stdout.String(), exit.ExitCode() + case ctx.Err() != nil: + return "killed after " + (d + time.Minute).String() + ": " + strings.TrimSpace(stdout.String()+" "+stderr.String()), -1 + } + t.Fatalf("sw-block %q: %v\nstdout: %s\nstderr: %s", args, err, stdout.String(), stderr.String()) + return "", -1 +} + +// headSzChunkStatus returns the volume's chunk section of its durable status +// as served, unparsed; nil when there is none. +func headSzChunkStatus(t *testing.T, b bvHost) json.RawMessage { + t.Helper() + var st struct { + Volumes []struct { + VolumeID string + Chunk json.RawMessage + } + } + if err := json.Unmarshal(headSzGet(t, "http://"+b.status+"/status/durable?volume="+b.volume, 4<<20), &st); err != nil { + t.Fatalf("durable status of %s: %v", b.volume, err) + } + for _, s := range st.Volumes { + if s.VolumeID == b.volume && len(s.Chunk) > 0 && string(s.Chunk) != "null" { + return s.Chunk + } + } + return nil +} + +// headSzDirty reads the volume's DirtyChunks (its capture candidates) from +// its durable status; -1 when the status has no chunk section. +func headSzDirty(t *testing.T, b bvHost) int { + t.Helper() + var st struct { + Volumes []struct { + VolumeID string + Chunk *struct { + Stats struct{ DirtyChunks int } + } + } + } + if err := json.Unmarshal(headSzGet(t, "http://"+b.status+"/status/durable?volume="+b.volume, 4<<20), &st); err != nil { + t.Fatalf("durable status of %s: %v", b.volume, err) + } + for _, s := range st.Volumes { + if s.VolumeID == b.volume && s.Chunk != nil { + return s.Chunk.Stats.DirtyChunks + } + } + return -1 +} + +func headSzGet(t *testing.T, u string, limit int64) []byte { + t.Helper() + c := &http.Client{Timeout: 30 * time.Second} + resp, err := c.Get(u) + if err != nil { + t.Fatalf("GET %s: %v", u, err) + } + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, limit)) + if err != nil || resp.StatusCode != http.StatusOK { + t.Fatalf("GET %s: status %d err %v", u, resp.StatusCode, err) + } + return body +} diff --git a/seaweed-block/cmd/blockvolume/headroom_blast_radius_integration_test.go b/seaweed-block/cmd/blockvolume/headroom_blast_radius_integration_test.go new file mode 100644 index 0000000000..af44aec3ec --- /dev/null +++ b/seaweed-block/cmd/blockvolume/headroom_blast_radius_integration_test.go @@ -0,0 +1,199 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "net/http" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + "time" +) + +// TestHeadroomRefusedTargetBlastRadiusAndAnotherRoot: two restore targets of +// a snapshot of v1 (v2, v3) are refused for local headroom on the small file +// system (as in TestHeadroomRefusesRestoreTargetsThenServesThem; run +// it with testdata/headroom-small-fs.sh). Then: +// +// - another root on the same host is a way out: v3's blockvolume, started +// again on the same host (same server and endpoints) with --durable-root +// on a file system with room and nothing freed, starts and serves the +// snapshot; +// - the source's snapshot stays while targets depend on it: its delete is +// refused with snapshot_has_dependents while v2 is refused and v3 +// serves. Once both targets are deleted (v2 started on a root with room; +// each through the volume-lifecycle page's seal, revoke, ACK and +// volume-delete), the snapshot delete succeeds, and the source volume is +// then deleted through the same steps. Each step answers within its +// bound. +func TestHeadroomRefusedTargetBlastRadiusAndAnotherRoot(t *testing.T) { + small, filler := os.Getenv("CHUNKSTORE_SMALL_ROOT"), os.Getenv("CHUNKSTORE_SMALL_FILLER") + if small == "" || filler == "" { + t.Skip("CHUNKSTORE_SMALL_ROOT and CHUNKSTORE_SMALL_FILLER name a small file system and its filler file") + } + if free, need := freeBytes(t, small), int64(headroomVolumeBytes+headroomWALBytes); free >= need { + t.Fatalf("the small file system has %d bytes free, not less than the %d a volume needs: fix the runner", free, need) + } + t.Cleanup(func() { _ = os.RemoveAll(filepath.Join(small, t.Name())) }) + + env := startHandoffEnvWith(t, 1, []string{"v2", "v3"}) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + src := env.start(t, "blockvolume-v1", "s1") + e := env.adopt(t, src, "s1") + for _, v := range []string{"v2", "v3"} { + b := env.hosts["n-"+v] + b.root = filepath.Join(small, t.Name(), "vol-n-"+v) + env.hosts["n-"+v] = b + if err := os.MkdirAll(b.root, 0o700); err != nil { + t.Fatal(err) + } + } + img := ladderImage("blastrad", []uint64{0, 3}, 4) + env.writeImage(t, "s1", img) + env.snapshot(t, "s1", "v1", "base") + for _, v := range []string{"v2", "v3"} { + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "base", "--target", v, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + env.refusedForHeadroom(t, v, "blockvolume-"+v+"-no-room") + } + + // Another root with room on the same host, nothing freed. + b3 := env.hosts["n-v3"] + b3.root = filepath.Join(env.h.dir, "vol-n-v3-with-room") + env.hosts["n-v3"] = b3 + d3 := env.h.start(t, "blockvolume-v3-other-root", env.h.volume, env.volArgsFor(b3)...) + d3.waitLog(t, 60*time.Second, "blockvolume: volume v3 adopted as PRIMARY at r1@") + poll(t, 60*time.Second, "v3 on another root never reported its frontend ready", func() bool { + return volumeFrontendReady(b3.status, "v3") + }) + env.requireImage(t, "n-v3", img) + + // While v2 is refused and v3 serves, the source's snapshot cannot be deleted. + deleteBase := func() (string, string, int) { + return env.h.run(t, "ops", "chunk", "snapshot-delete", "--master", env.h.masterAddr, "--volume", "v1", "--name", "base", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + } + out, errOut, code := deleteBase() + if code == 0 || !strings.Contains(out+errOut, "snapshot_has_dependents") { + t.Fatalf("snapshot-delete of the source snapshot while restore targets depend on it: exit %d %s %s; want snapshot_has_dependents", code, out, errOut) + } + + // Delete both targets: v2 on a root with room, then each through the + // page's steps. + b2 := env.hosts["n-v2"] + b2.root = filepath.Join(env.h.dir, "vol-n-v2-with-room") + env.hosts["n-v2"] = b2 + adopted := func(vol string) *regexp.Regexp { + return regexp.MustCompile(`blockvolume: volume ` + vol + ` adopted as PRIMARY at r1@(\d+) `) + } + d2 := env.startTarget(t, "v2", "blockvolume-v2-with-room") + env.deleteServingTarget(t, "v2", env.hosts["n-v2"], d2, logUint(t, d2, adopted("v2"))) + env.deleteServingTarget(t, "v3", b3, d3, logUint(t, d3, adopted("v3"))) + + // Now the snapshot delete succeeds, and then the source volume's delete. + out, errOut, code = deleteBase() + if code != 0 || !strings.Contains(out, `"state":"absent"`) { + t.Fatalf("snapshot-delete of the source snapshot after its targets were deleted: exit %d %s %s; want absent", code, out, errOut) + } + g := env.seal(t, "s1", e) + env.revoke(t, e, g) + if err := src.wait(30 * time.Second); err != nil { + t.Fatalf("s1 after the revocation: %v; want a clean exit by itself", err) + } + env.waitAck(t, e, g) + out, errOut, code = env.volumeDelete(t, "del-v1") + requireDeleteCompleted(t, out, errOut, code) +} + +// TestHeadroomRefusedRestoreTargetKeepsItsSourceSnapshot: a restore target +// (v2) refused for local headroom has never read a chunk, so its HEAD names +// its source's chunks. While it waits, its source snapshot cannot go: the +// delete through the source's holder (whose cleaning pass would collect the +// snapshot's chunks) is refused because v2 depends on it, and the source's +// pool keeps every chunk. Then space is freed and v2 starts: it must read +// back the snapshot exactly, at once and again after every chunk is made +// local. A read that differs or reads zero is a data-loss path and fails the +// test as such; a target that refuses to start fails with its reason. +func TestHeadroomRefusedRestoreTargetKeepsItsSourceSnapshot(t *testing.T) { + small, filler := os.Getenv("CHUNKSTORE_SMALL_ROOT"), os.Getenv("CHUNKSTORE_SMALL_FILLER") + if small == "" || filler == "" { + t.Skip("CHUNKSTORE_SMALL_ROOT and CHUNKSTORE_SMALL_FILLER name a small file system and its filler file") + } + need := int64(headroomVolumeBytes + headroomWALBytes) + if free := freeBytes(t, small); free >= need { + t.Fatalf("the small file system has %d bytes free, not less than the %d a volume needs: fix the runner", free, need) + } + t.Cleanup(func() { _ = os.RemoveAll(filepath.Join(small, t.Name())) }) + + env := startHandoffEnvWith(t, 1, []string{"v2"}) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + src := env.start(t, "blockvolume-v1", "s1") + env.adopt(t, src, "s1") + b2 := env.hosts["n-v2"] + b2.root = filepath.Join(small, t.Name(), "vol-n-v2") + env.hosts["n-v2"] = b2 + if err := os.MkdirAll(b2.root, 0o700); err != nil { + t.Fatal(err) + } + img := ladderImage("srcgone", []uint64{0, 3, 9}, 4) + env.writeImage(t, "s1", img) + env.snapshot(t, "s1", "v1", "base") + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "base", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + env.refusedForHeadroom(t, "v2", "blockvolume-v2-no-room") + + // The source snapshot stays while v2 depends on it. + stored := env.poolObjects(t, "v1") + code, out := env.holderDeleteSnapshot(t, "s1", "v1", "base") + if code == http.StatusOK || !strings.Contains(out, "dependents") { + t.Fatalf("holder delete of the snapshot v2 depends on: status %d %s; want it refused (dependents)", code, out) + } + env.requireSnapshotNames(t, "v1", "base") + time.Sleep(5 * time.Second) // a cleaning pass, had one run, ends well inside this + if got := env.poolObjects(t, "v1"); got != stored { + t.Fatalf("the source pool held %d chunk objects before the refused delete and %d after; want them all kept", stored, got) + } + + // The refused target, now with room, must read the snapshot exactly. + if err := os.Remove(filler); err != nil { + t.Fatal(err) + } + d2 := env.h.start(t, "blockvolume-v2-with-room", env.h.volume, env.volArgsFor(b2)...) + adopted := false + for end := time.Now().Add(60 * time.Second); time.Now().Before(end) && !adopted; time.Sleep(200 * time.Millisecond) { + select { + case <-d2.done: + t.Fatalf("v2 refused to start: %v; %q", d2.err, strings.TrimSpace(d2.line("blockvolume:"))) + default: + } + adopted = d2.has("blockvolume: volume v2 adopted as PRIMARY at r1@") + } + if !adopted { + t.Fatal("v2 never adopted once it had room") + } + poll(t, 60*time.Second, "v2 never reported its frontend ready", func() bool { return volumeFrontendReady(b2.status, "v2") }) + requireImageExact(t, env, "n-v2", img, "after the refused delete of its source snapshot") + env.hydrate(t, "v2") + requireImageExact(t, env, "n-v2", img, "after it was read in full (hydrated)") +} + +// requireImageExact reads every block of img on the host and fails, marked +// as a data-loss path, on any block that differs (or reads zero). +func requireImageExact(t *testing.T, env *handoffEnv, hostID string, img map[uint64][]byte, when string) { + t.Helper() + c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN) + defer c.close() + bad := 0 + for lba, want := range img { + if got := c.read(t, lba, 4096); string(got) != string(want) { + bad++ + } + } + if bad != 0 { + t.Fatalf("DATA LOSS PATH: %s, %d of %d snapshot blocks on %s differ from what was written", when, bad, len(img), hostID) + } + env.requireEdges(t, hostID) + t.Logf("%s: all %d snapshot blocks on %s read back exactly", when, len(img), hostID) +} diff --git a/seaweed-block/cmd/blockvolume/headroom_restore_fork_integration_test.go b/seaweed-block/cmd/blockvolume/headroom_restore_fork_integration_test.go new file mode 100644 index 0000000000..39cac9a21e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/headroom_restore_fork_integration_test.go @@ -0,0 +1,274 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +// Local headroom for restore targets. The durable root of each +// target is on a small file system (CHUNKSTORE_SMALL_ROOT, a directory on it) +// that a filler file (CHUNKSTORE_SMALL_FILLER, on the same file system) keeps +// below the volume size + WAL. testdata/headroom-small-fs.sh prepares both on +// a fresh loop-mounted ext4 for each run and removes it afterwards (root +// only); without them the test is skipped, as in CI. +// +// The check's limit: it compares one volume's size + WAL with the free space +// at that moment, not the sum over every volume on the file system. Once the +// filler is gone, four 256 MiB + 64 MiB targets (1280 MiB together) all start +// on the 768 MiB file system; the test asserts that sum exceeds the file +// system's size. + +const ( + headroomVolumeBytes = 65536 * 4096 // the harness's volume size + headroomWALBytes = 64 << 20 // the default WAL +) + +func freeBytes(t *testing.T, dir string) int64 { + t.Helper() + var st syscall.Statfs_t + if err := syscall.Statfs(dir, &st); err != nil { + t.Fatal(err) + } + return int64(st.Bavail) * int64(st.Bsize) +} + +func fsBytes(t *testing.T, dir string) int64 { + t.Helper() + var st syscall.Statfs_t + if err := syscall.Statfs(dir, &st); err != nil { + t.Fatal(err) + } + return int64(st.Blocks) * int64(st.Bsize) +} + +// requireOnlyReplicaFloor requires the regular files under dir to be exactly +// the volume's replica floor: a refused create writes no store, WAL or +// marker. The floor is written when the assignment arrives, before the store +// is opened and refused (a known limit: the check precedes the store, not +// every sidecar). +func requireOnlyReplicaFloor(t *testing.T, dir, vol string) { + t.Helper() + var files []string + if err := filepath.Walk(dir, func(p string, info os.FileInfo, err error) error { + if err != nil { + return err + } + if !info.IsDir() { + files = append(files, filepath.Base(p)) + } + return nil + }); err != nil { + t.Fatalf("listing %s: %v", dir, err) + } + if len(files) != 1 || files[0] != vol+".replica-floor" { + t.Fatalf("a refused create left %v under %s; want exactly %s.replica-floor", files, dir, vol) + } +} + +// refusedForHeadroom starts the target's blockvolume and requires it to +// refuse the create the way the durable store's open fails at startup: it +// exits on its own with status 1, its log says "blockvolume: durable storage +// open:" and names the free bytes and the need (size + WAL), and its durable +// root holds no store (only its replica floor). Status 1 is not +// RestartPreventExitStatus=78 in the shipped unit, so systemd starts it +// again every 5 s, refusing each time, until space is freed or its start +// limit stops it. It returns the refused process. +func (env *handoffEnv) refusedForHeadroom(t *testing.T, target, name string) *daemon { + t.Helper() + b := env.hosts["n-"+target] + d := env.h.start(t, name, env.h.volume, env.volArgsFor(b)...) + err := d.wait(60 * time.Second) + select { + case <-d.done: + default: + t.Fatalf("%s: blockvolume did not exit within 60 s of a create without room (%v)", name, err) + } + if err == nil { + t.Fatalf("%s: blockvolume created %s without room for it and exited cleanly", name, target) + } + want := fmt.Sprintf("volume %s needs %d (size %d + WAL %d)", target, headroomVolumeBytes+headroomWALBytes, headroomVolumeBytes, headroomWALBytes) + line := d.line(want) + if line == "" || !strings.Contains(line, "bytes free") { + t.Fatalf("%s: no refusal naming the free bytes and %q", name, want) + } + if code := exitCode(err); code != 1 || !strings.Contains(line, "blockvolume: durable storage open:") { + t.Fatalf("%s: exit status %d, refusal %q; want status 1 from the durable storage open at startup", name, code, line) + } + t.Logf("%s refused (exit status 1): %s", name, strings.TrimSpace(line)) + requireOnlyReplicaFloor(t, b.root, target) + return d +} + +// logUint reads the number re captures from the first line of d's log that +// it matches. +func logUint(t *testing.T, d *daemon, re *regexp.Regexp) uint64 { + t.Helper() + data, _ := os.ReadFile(d.log) + m := re.FindSubmatch(data) + if m == nil { + t.Fatalf("%s: no line matching %s", d.name, re) + } + n, err := strconv.ParseUint(string(m[1]), 10, 64) + if err != nil || n == 0 { + t.Fatalf("%s: %q: %v", d.name, m[0], err) + } + return n +} + +// deleteServingTarget runs the volume-lifecycle page's delete for a target +// that serves (d on host b at epoch e): seal, revoke and wait for its ACK +// and clean exit, then volume-delete, which must complete. +func (env *handoffEnv) deleteServingTarget(t *testing.T, vol string, b bvHost, d *daemon, e uint64) { + t.Helper() + out, errOut := env.h.command(t, "ops", "chunk", "detach", "--plain", "--volume", vol, "--status-addr", b.status, "--timeout", "120s") + var a struct { + VolumeID string `json:"volumeID"` + HeadGen uint64 `json:"headGen"` + HeadEpoch uint64 `json:"headEpoch"` + } + if err := json.Unmarshal([]byte(out), &a); err != nil || a.VolumeID != vol || a.HeadGen == 0 || a.HeadEpoch != e || + strings.TrimSpace(errOut) != fmt.Sprintf("sealed HEAD generation: %d", a.HeadGen) { + t.Fatalf("plain detach of %s: %v %q %q; want %s sealed at epoch %d with its generation line", vol, err, out, errOut, vol, e) + } + g := a.HeadGen + env.h.command(t, "ops", "workspace", "revoke", "--master", env.h.masterAddr, "--volume", vol, "--replica", "r1", + "--epoch", fmt.Sprint(e), "--sealed-gen", fmt.Sprint(g)) + if err := d.wait(30 * time.Second); err != nil { + t.Fatalf("%s after the revocation: %v; want a clean exit by itself", vol, err) + } + poll(t, 30*time.Second, fmt.Sprintf("workspace show never reported %s's ACK", vol), func() bool { + out, _ := env.h.command(t, "ops", "workspace", "show", "--master", env.h.masterAddr, "--volume", vol) + return showsAck(out, e, g) + }) + out, errOut, code := env.h.run(t, "ops", "chunk", "volume-delete", "--volume", vol, "--chunk-filer", env.cluster.filerGRPC, + "--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-"+vol) + if code != 0 || !handoffDeleteCompleted(out) { + t.Fatalf("volume-delete of %s after the way out: exit %d %s %s; want completed", vol, code, out, errOut) + } +} + +// TestHeadroomRefusesRestoreTargetsThenServesThem: a snapshot of v1 is +// restored into v2, v4 and v6 (fork is not in v1), each target's durable +// root on a small file system with less free space than the volume size + +// WAL. +// Each target's blockvolume refuses the create, naming both numbers, exits +// with status 1, and writes no store; the source still serves its data and +// its snapshot is still listed, and restores into another target (v5) that +// serves it. +// +// A refused target exists in the catalog and holds the master's line, but +// cannot start, and until it has started once it is stranded (a known limit +// of 1.0): a volume-delete wants a clean revocation ACK its holder cannot +// send, and a forced move to a host with room (n-v7) is refused because the +// master knows no holder of it. The one way out is run: once space is freed, +// v2 starts and serves the snapshot, and v4 and v6 start, serve, and are +// sealed, revoked, acknowledged and deleted. +func TestHeadroomRefusesRestoreTargetsThenServesThem(t *testing.T) { + small, filler := os.Getenv("CHUNKSTORE_SMALL_ROOT"), os.Getenv("CHUNKSTORE_SMALL_FILLER") + if small == "" || filler == "" { + t.Skip("CHUNKSTORE_SMALL_ROOT and CHUNKSTORE_SMALL_FILLER name a small file system and its filler file") + } + need := int64(headroomVolumeBytes + headroomWALBytes) + if free := freeBytes(t, small); free >= need { + t.Fatalf("the small file system has %d bytes free, not less than the %d a volume needs: fix the runner", free, need) + } + + t.Cleanup(func() { _ = os.RemoveAll(filepath.Join(small, t.Name())) }) + env := startLadderEnv(t, "v2", "v4", "v5", "v6", "v7") + for _, v := range []string{"v2", "v4", "v6"} { + b := env.hosts["n-"+v] + b.root = filepath.Join(small, t.Name(), "vol-n-"+v) + env.hosts["n-"+v] = b + if err := os.MkdirAll(b.root, 0o700); err != nil { + t.Fatal(err) + } + } + img := ladderImage("headroom", []uint64{0, 3}, 4) + env.writeImage(t, "s1", img) + env.snapshot(t, "s1", "v1", "base") + + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "base", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + for _, v := range []string{"v4", "v6"} { + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "base", "--target", v, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + } + refused := map[string]*daemon{} + for _, v := range []string{"v2", "v4", "v6"} { + refused[v] = env.refusedForHeadroom(t, v, "blockvolume-"+v+"-no-room") + } + + // The stranded target: not deletable while its holder cannot start. + deleteV4 := func() (string, string, int) { + return env.h.run(t, "ops", "chunk", "volume-delete", "--volume", "v4", "--chunk-filer", env.cluster.filerGRPC, + "--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-v4-while-refused") + } + out, errOut, code := deleteV4() + if code != 1 || !strings.Contains(out+errOut, "live authority requires clean revocation ACK") { + t.Fatalf("volume-delete of the refused target v4: exit %d %s %s; want refused for the missing ACK (a known limit)", code, out, errOut) + } + // The snapshot is still restorable into another target that has room. + env.restoreInto(t, "v1", "base", "v5") + env.requireImage(t, "n-v5", img) + + env.requireImage(t, "s1", img) // the source is intact + if l := env.snapshots(t, "v1", "base"); len(l) != 1 { + t.Fatalf("the source's snapshot after the refusals: %+v", l) + } + + if err := os.Remove(filler); err != nil { + t.Fatal(err) + } + if free := freeBytes(t, small); free < need { + t.Fatalf("after removing the filler the small file system has %d bytes free; the %d a volume needs does not fit: fix the runner", free, need) + } + for _, v := range []string{"v2"} { + env.startTarget(t, v, "blockvolume-"+v+"-with-room") + env.requireImage(t, "n-"+v, img) + } + + // Way out 1 for a stranded target: with room it starts, and the usual + // delete steps (seal, revoke, ACK, delete) complete. + adopted := func(vol string) *regexp.Regexp { + return regexp.MustCompile(`blockvolume: volume ` + vol + ` adopted as PRIMARY at r1@(\d+) `) + } + d4 := env.startTarget(t, "v4", "blockvolume-v4-with-room") + env.deleteServingTarget(t, "v4", env.hosts["n-v4"], d4, logUint(t, d4, adopted("v4"))) + + // A forced move is no way out for a refused target: the master knows no + // holder of it (it never held a lease), so every dry run is refused and + // nothing is sent. Its one way out is the first: with room, it starts on + // its own host and is deleted the usual way. + e6 := logUint(t, refused["v6"], regexp.MustCompile(`assignment stream delivery .*volume="v6" .*epoch=(\d+)`)) + b7 := env.hosts["n-v7"] + move := []string{"ops", "workspace", "force-move", "--master", env.h.masterAddr, "--volume", "v6", + "--target-host", b7.id, "--target-data", b7.data, "--target-ctrl", b7.ctrl, "--request-id", "force-v6", + "--confirm-forced", fmt.Sprintf("v6@%d", e6), "--dry-run"} + for end := time.Now().Add(30 * time.Second); time.Now().Before(end); time.Sleep(3 * time.Second) { + out, errOut, code := env.h.run(t, move...) + if code == 0 || previewAdmitted(out) || !strings.Contains(out+errOut, `the master knows no holder of volume "v6"`) || !strings.Contains(out+errOut, "nothing was sent") { + t.Fatalf("forced move of the refused, never-started v6: exit %d %s %s; want refused, the master knowing no holder, nothing sent", code, out, errOut) + } + } + d6 := env.startTarget(t, "v6", "blockvolume-v6-with-room") + env.requireImage(t, "n-v6", img) + env.deleteServingTarget(t, "v6", env.hosts["n-v6"], d6, logUint(t, d6, adopted("v6"))) + + // The check is per volume, not a sum: all four targets started on this + // file system, though together they need more than its whole size. + if total, size := 4*need, fsBytes(t, small); total <= size { + t.Fatalf("four targets need %d bytes, not more than the %d-byte file system: the run does not show the per-volume limit", total, size) + } else { + t.Logf("four targets needing %d bytes together all started on a %d-byte file system (the check is per volume)", total, size) + } +} diff --git a/seaweed-block/cmd/blockvolume/hold_kzhold.go b/seaweed-block/cmd/blockvolume/hold_kzhold.go new file mode 100644 index 0000000000..3fc55846cc --- /dev/null +++ b/seaweed-block/cmd/blockvolume/hold_kzhold.go @@ -0,0 +1,24 @@ +//go:build kzhold + +package main + +import ( + "log" + "os" + "path/filepath" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" +) + +// applyBuildTagHold: in a kzhold build (test-only, never released) with +// SWBLOCK_KZHOLD_DIR set, the provider holds before the fresh marker is +// retired: it writes /reached and waits for /release. +func applyBuildTagHold(dp *durable.DurableProvider) { + dir := os.Getenv("SWBLOCK_KZHOLD_DIR") + if dir == "" { + return + } + log.Printf("blockvolume: TEST-ONLY build (kzhold): holding before the fresh-marker retire; reached=%s release=%s", + filepath.Join(dir, "reached"), filepath.Join(dir, "release")) + dp.HoldBeforeChunkFreshRetireForTest(filepath.Join(dir, "reached"), filepath.Join(dir, "release")) +} diff --git a/seaweed-block/cmd/blockvolume/hold_release.go b/seaweed-block/cmd/blockvolume/hold_release.go new file mode 100644 index 0000000000..7900f7e4d2 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/hold_release.go @@ -0,0 +1,8 @@ +//go:build !kzhold + +package main + +import "github.com/seaweedfs/seaweed-block/core/frontend/durable" + +// applyBuildTagHold does nothing in a normal build. +func applyBuildTagHold(*durable.DurableProvider) {} diff --git a/seaweed-block/cmd/blockvolume/host_limit.go b/seaweed-block/cmd/blockvolume/host_limit.go new file mode 100644 index 0000000000..2a0538da93 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/host_limit.go @@ -0,0 +1,23 @@ +package main + +import ( + "flag" + "github.com/seaweedfs/seaweed-block/core/hostlimit" +) + +func registerHostLimitFlags(fs *flag.FlagSet, c *hostlimit.Config) { + *c = hostlimit.DefaultConfig("") + fs.StringVar(&c.Directory, "host-limit-dir", "", "shared local directory for background-cut slots; empty disables shared slots") + fs.IntVar(&c.NormalSlots, "host-limit-normal-slots", c.NormalSlots, "host normal-cut slots; identical across processes") + fs.IntVar(&c.UrgentSlots, "host-limit-urgent-slots", c.UrgentSlots, "host reserved urgent-cut slots") + fs.IntVar(&c.FillSlots, "host-limit-fill-slots", c.FillSlots, "host background-fill slots; demand hydration bypasses them") + fs.IntVar(&c.IdleSlots, "host-limit-idle-slots", c.IdleSlots, "host idle-work slots") + fs.Int64Var(&c.PayloadBytes, "host-limit-payload-bytes", c.PayloadBytes, "maximum cut payload per slot") + fs.Int64Var(&c.COWBytes, "host-limit-cow-bytes", c.COWBytes, "maximum saved COW bytes per slot") + fs.Int64Var(&c.BytesPerSecond, "host-limit-upload-bytes-sec", c.BytesPerSecond, "pacing parameter divided per process by cut-slot count; not a host rate cap. --host-limit-no-progress must exceed one chunk's send time at this rate per held slot, or a steadily sending cut is revoked") + fs.IntVar(&c.FallbackVolumes, "host-limit-fallback-volumes", c.FallbackVolumes, "kept for configuration compatibility; the urgent fallback is not paced (no shared host cap to protect)") + fs.IntVar(&c.FetchSlots, "host-limit-fetch-slots", c.FetchSlots, "chunk fetches in flight on the host, across its processes (1-1024); a read of an absent chunk waits for a slot, bounded by its read-miss timeout") + fs.DurationVar(&c.YieldAfter, "host-limit-yield-after", c.YieldAfter, "a normal cut that has held its slot this long gives it to a waiting cut at its next staging batch (keeping what it staged); a lone cut never yields") + fs.DurationVar(&c.NoProgress, "host-limit-no-progress", c.NoProgress, "a held slot is revoked after this long with no progress of its work (chunks compared, staged, uploaded or filled); revocation aborts but waits for admitted I/O before release") + fs.DurationVar(&c.NoProgress, "host-limit-max-hold", c.NoProgress, "deprecated: the same as --host-limit-no-progress (a hold is no longer limited by its age)") +} diff --git a/seaweed-block/cmd/blockvolume/host_limit_test.go b/seaweed-block/cmd/blockvolume/host_limit_test.go new file mode 100644 index 0000000000..5787520c21 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/host_limit_test.go @@ -0,0 +1,25 @@ +package main + +import ( + "path/filepath" + "testing" +) + +func TestHostCutLimitFlags(t *testing.T) { + base := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1") + dir := t.TempDir() + args := append(append([]string{}, base...), "--host-limit-dir="+dir, "--host-limit-normal-slots=2", "--host-limit-urgent-slots=1") + f, e := parseFlags(args) + if e != nil { + t.Fatal(e) + } + if f.chunk.hostLimit.Directory != dir || f.chunk.hostLimit.NormalSlots != 2 || f.chunk.hostLimit.UrgentSlots != 1 { + t.Fatal("lost host limits") + } + for _, extra := range [][]string{{"--host-limit-normal-slots=2"}, {"--host-limit-dir=" + dir, "--host-limit-normal-slots=0"}, {"--host-limit-dir=" + dir, "--host-limit-max-hold=-1s"}, {"--host-limit-dir=" + filepath.Join("relative", "pool")}} { + a := append(append([]string{}, base...), extra...) + if _, e = parseFlags(a); e == nil { + t.Fatalf("accepted invalid limits: %v", extra) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/hydration_flags_test.go b/seaweed-block/cmd/blockvolume/hydration_flags_test.go new file mode 100644 index 0000000000..6fd5dc2377 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/hydration_flags_test.go @@ -0,0 +1,16 @@ +package main + +import "testing" + +func TestChunkHydrationFlagsAreConfigurable(t *testing.T) { + base := append(phase150RequiredBlockvolumeArgs(), "--durable-root=hydration-test", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1") + f, err := parseFlags(append(base, "--chunk-hydration-workers=3", "--chunk-hydration-queue-depth=17")) + if err != nil || f.chunk.hydrationWorkers != 3 || f.chunk.hydrationQueueDepth != 17 { + t.Fatalf("hydration limits: %+v err=%v", f.chunk, err) + } + for _, flag := range []string{"--chunk-hydration-workers=0", "--chunk-hydration-workers=65", "--chunk-hydration-queue-depth=0", "--chunk-hydration-queue-depth=65537"} { + if _, err := parseFlags(append(base, flag)); err == nil { + t.Fatalf("invalid hydration limit accepted: %s", flag) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/iscsi_alua_provider.go b/seaweed-block/cmd/blockvolume/iscsi_alua_provider.go new file mode 100644 index 0000000000..512b9ca7c7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/iscsi_alua_provider.go @@ -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 +} diff --git a/seaweed-block/cmd/blockvolume/iscsi_alua_provider_test.go b/seaweed-block/cmd/blockvolume/iscsi_alua_provider_test.go new file mode 100644 index 0000000000..9f8f0a82ce --- /dev/null +++ b/seaweed-block/cmd/blockvolume/iscsi_alua_provider_test.go @@ -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) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/iscsi_portal_addr_test.go b/seaweed-block/cmd/blockvolume/iscsi_portal_addr_test.go new file mode 100644 index 0000000000..74740c08eb --- /dev/null +++ b/seaweed-block/cmd/blockvolume/iscsi_portal_addr_test.go @@ -0,0 +1,555 @@ +package main + +import ( + "errors" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/nvmerdma" + "github.com/seaweedfs/seaweed-block/core/host/volume" +) + +func TestParseFlags_VersionDoesNotRequireVolumeArgs(t *testing.T) { + got, err := parseFlags([]string{"--version"}) + if err != nil { + t.Fatalf("parseFlags --version: %v", err) + } + if !got.version { + t.Fatal("version flag not set") + } +} + +func TestParseFlags_IscsiPortalAddrRequiresListen(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--iscsi-portal-addr", "203.0.113.10:3260,1", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want --iscsi-portal-addr without --iscsi-listen rejected") + } + if !strings.Contains(err.Error(), "--iscsi-portal-addr requires --iscsi-listen") { + t.Fatalf("error = %q, want portal/listen requirement", err) + } +} + +func TestParseFlags_NVMeTransportDefaultsTCP(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--nvme-listen", "127.0.0.1:4420", + "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:test-v1", + ) + got, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if got.nvmeTransport != "tcp" { + t.Fatalf("nvmeTransport=%q want tcp", got.nvmeTransport) + } +} + +func TestParseFlags_NVMeTransportAcceptsExplicitRDMA(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--nvme-listen", "10.0.0.3:4420", + "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:test-v1", + "--nvme-transport", "rdma", + "--allow-external-nvme-bind", + ) + got, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if got.nvmeTransport != "rdma" { + t.Fatalf("nvmeTransport=%q want rdma", got.nvmeTransport) + } +} + +func TestParseFlags_NVMERDMARejectsTCPMaxH2COption(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--nvme-listen", "10.0.0.3:4420", + "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:test-v1", + "--nvme-transport", "rdma", + "--allow-external-nvme-bind", + "--nvme-max-h2c-data-length", "65536", + ) + _, err := parseFlags(args) + if err == nil || !strings.Contains(err.Error(), "applies only to --nvme-transport=tcp") { + t.Fatalf("error=%v want TCP-only MaxH2C refusal", err) + } +} + +func TestPhase165_NVMeFrontendTargetPublicationRequiresKnownTransport(t *testing.T) { + for _, transport := range []string{"tcp", "rdma"} { + if !shouldPublishNVMeFrontendTarget(transport) { + t.Fatalf("%s target must enter master/CSI publish context", transport) + } + } + if shouldPublishNVMeFrontendTarget("bogus") { + t.Fatal("unknown transport must not enter master/CSI publish context") + } +} + +func TestNVMeFrontendCapabilitiesExposeRDMAUnsupportedNoListener(t *testing.T) { + facts := []volume.FrontendTransportPreflightFact{{ + Name: "nvme_rdma_module", + Available: false, + Reason: "nvme_rdma_module_missing", + }} + caps := nvmeFrontendCapabilitiesWithRDMAPreflight("127.0.0.1:4420", "tcp", true, facts) + if len(caps) != 2 { + t.Fatalf("capabilities=%d want 2", len(caps)) + } + tcp := caps[0] + if tcp.Protocol != "nvme" || tcp.Transport != "tcp" || !tcp.Supported || !tcp.ListenerImplemented || !tcp.ListenerStarted || !tcp.StartAllowed { + t.Fatalf("tcp capability unexpected: %+v", tcp) + } + rdma := caps[1] + if rdma.Protocol != "nvme" || rdma.Transport != "rdma" || rdma.Supported || rdma.ListenerImplemented != nvmerdma.Implemented() || rdma.ListenerStarted || rdma.StartAllowed { + t.Fatalf("rdma capability must stay unsupported with no listener: %+v", rdma) + } + if rdma.Reason != "nvme_rdma_transport_unsupported" { + t.Fatalf("rdma reason=%q want nvme_rdma_transport_unsupported", rdma.Reason) + } + if rdma.StartReason != "nvme_rdma_listener_disabled" { + t.Fatalf("rdma startReason=%q want nvme_rdma_listener_disabled", rdma.StartReason) + } + if len(rdma.Preflight) != 1 || rdma.Preflight[0].Name != "nvme_rdma_module" || rdma.Preflight[0].Available { + t.Fatalf("rdma preflight unexpected: %+v", rdma.Preflight) + } +} + +func TestNVMERDMAListenerStartDecisionDisabledByDefault(t *testing.T) { + got := nvmeRDMAListenerStartDecision(false, nil) + if got.allowed || got.reason != "nvme_rdma_listener_disabled" { + t.Fatalf("start decision=%+v want disabled refusal", got) + } +} + +func TestNVMERDMAListenerStartDecisionMapsPreflightFailure(t *testing.T) { + got := nvmeRDMAListenerStartDecision(true, []volume.FrontendTransportPreflightFact{{ + Name: "rdma_device", + Available: false, + Reason: "rdma_device_missing", + }}) + if got.allowed || got.reason != "rdma_device_missing" { + t.Fatalf("start decision=%+v want rdma_device_missing", got) + } +} + +func TestNVMERDMAListenerStartDecisionMapsEveryTargetPreflightFailure(t *testing.T) { + for _, tc := range []struct { + name string + reason string + }{ + {name: "nvmet_rdma_module", reason: "nvmet_rdma_module_missing"}, + {name: "nbd_module", reason: "nbd_module_missing"}, + {name: "rdma_device", reason: "rdma_device_missing"}, + {name: "rdma_bind_address", reason: "rdma_bind_address_invalid"}, + {name: "configfs", reason: "configfs_missing"}, + } { + t.Run(tc.name, func(t *testing.T) { + got := nvmeRDMAListenerStartDecision(true, []volume.FrontendTransportPreflightFact{{ + Name: tc.name, + Available: false, + Reason: tc.reason, + }}) + if got.allowed || got.reason != tc.reason { + t.Fatalf("start decision=%+v want %s", got, tc.reason) + } + }) + } +} + +func TestNVMERDMATargetStartFailureReason(t *testing.T) { + for _, tc := range []struct { + message string + want string + }{ + {message: "configure kernel target: port ID already exists: 4420", want: "rdma_port_conflict"}, + {message: "configure kernel target: subsystem already exists: nqn.test", want: "rdma_subsystem_conflict"}, + {message: "symlink: cannot assign requested address", want: "rdma_bind_address_unassigned"}, + {message: "open /dev/nbd0: permission denied", want: "rdma_target_permission_denied"}, + {message: "nvmerdma: kernel target requires root", want: "rdma_target_permission_denied"}, + {message: "unexpected target error", want: "rdma_target_start_failed"}, + } { + if got := nvmeRDMATargetStartFailureReason(errors.New(tc.message)); got != tc.want { + t.Errorf("failure reason for %q = %q, want %q", tc.message, got, tc.want) + } + } +} + +func TestNVMERDMAListenerStartDecisionDoesNotRequireInitiatorModule(t *testing.T) { + got := nvmeRDMAListenerStartDecision(true, []volume.FrontendTransportPreflightFact{ + { + Name: "nvme_rdma_module", + Available: false, + Reason: "nvme_rdma_module_missing", + }, + { + Name: "nvmet_rdma_module", + Available: true, + Reason: "nvmet_rdma_module_available", + }, + }) + if nvmerdma.Implemented() { + if !got.allowed || got.reason != "implemented" { + t.Fatalf("start decision=%+v want target allowed without initiator module", got) + } + } else if got.allowed || got.reason != "nvme_rdma_transport_unsupported" { + t.Fatalf("start decision=%+v want unsupported platform", got) + } +} + +func TestNVMERDMAListenerStartDecisionAfterPreflight(t *testing.T) { + got := nvmeRDMAListenerStartDecision(true, []volume.FrontendTransportPreflightFact{{ + Name: "nvme_rdma_module", + Available: true, + Reason: "nvme_rdma_module_loaded", + }, { + Name: "rdma_device", + Available: true, + Reason: "rdma_device_present", + }, { + Name: "rdma_bind_address", + Available: true, + Reason: "rdma_bind_address_candidate", + }}) + if nvmerdma.Implemented() { + if !got.allowed || got.reason != "implemented" { + t.Fatalf("start decision=%+v want implemented", got) + } + } else if got.allowed || got.reason != "nvme_rdma_transport_unsupported" { + t.Fatalf("start decision=%+v want unsupported platform", got) + } +} + +func TestRDMABindAddressFactRejectsLoopback(t *testing.T) { + got := rdmaBindAddressFact("127.0.0.1:4420") + if got.Name != "rdma_bind_address" || got.Available || got.Reason != "rdma_bind_address_invalid" { + t.Fatalf("bind fact=%+v want unavailable rdma_bind_address_invalid", got) + } +} + +func TestRDMABindAddressFactAcceptsNonLoopbackCandidate(t *testing.T) { + got := rdmaBindAddressFact("192.168.100.10:4420") + if got.Name != "rdma_bind_address" || !got.Available || got.Reason != "rdma_bind_address_candidate" || got.Detail != "192.168.100.10" { + t.Fatalf("bind fact=%+v want non-loopback candidate", got) + } +} + +func TestParseFlags_NVMeMaxH2CDataLengthRequiresNVMeListen(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--nvme-max-h2c-data-length", "65536", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want --nvme-max-h2c-data-length without --nvme-listen rejected") + } + if !strings.Contains(err.Error(), "--nvme-max-h2c-data-length requires --nvme-listen") { + t.Fatalf("error = %q, want requires nvme-listen", err) + } +} + +func TestParseFlags_NVMeMaxH2CDataLengthAcceptsCandidate(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--nvme-listen", "127.0.0.1:4420", + "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:test-v1", + "--nvme-max-h2c-data-length", "65536", + ) + got, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if got.nvmeMaxH2C != 65536 { + t.Fatalf("nvmeMaxH2C=%d want 65536", got.nvmeMaxH2C) + } +} + +func TestParseFlags_NVMeMaxH2CDataLengthRejectsInvalid(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--nvme-listen", "127.0.0.1:4420", + "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:test-v1", + "--nvme-max-h2c-data-length", "49152", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want invalid H2C size rejected") + } + if !strings.Contains(err.Error(), "--nvme-max-h2c-data-length=49152 invalid") { + t.Fatalf("error = %q, want invalid H2C size", err) + } +} + +func TestParseFlags_NVMeExternalBindRequiresExplicitOptIn(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--nvme-listen", "203.0.113.10:4420", + "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:test-v1", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want external NVMe/TCP bind rejected") + } + if !strings.Contains(err.Error(), "not loopback") { + t.Fatalf("error = %q, want loopback bind rejection", err) + } +} + +func TestParseFlags_NVMeExternalBindOptIn(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--allow-external-nvme-bind", + "--nvme-listen", "203.0.113.10:4420", + "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:test-v1", + ) + got, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !got.allowExternalNVMeBind { + t.Fatal("allowExternalNVMeBind=false") + } +} + +func TestParseFlags_NVMeExternalBindOptInRejectsLoopback(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--allow-external-nvme-bind", + "--nvme-listen", "127.0.0.1:4420", + "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:test-v1", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want loopback external bind rejected") + } + if !strings.Contains(err.Error(), "non-loopback") { + t.Fatalf("error = %q, want non-loopback requirement", err) + } +} + +func TestParseFlags_IscsiPortalAddrDoesNotChangeLoopbackBind(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--iscsi-listen", "127.0.0.1:3260", + "--iscsi-iqn", "iqn.2026-05.io.seaweedfs:test-v1", + "--iscsi-portal-addr", "203.0.113.10:3260,1", + ) + got, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if got.iscsiPortalAddr != "203.0.113.10:3260,1" { + t.Fatalf("iscsiPortalAddr = %q", got.iscsiPortalAddr) + } + if !got.enableT1Readiness { + t.Fatal("iSCSI should still auto-enable t1 readiness") + } +} + +func TestParseFlags_IscsiPortalAddrStillRejectsExternalBind(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--iscsi-listen", "203.0.113.10:3260", + "--iscsi-iqn", "iqn.2026-05.io.seaweedfs:test-v1", + "--iscsi-portal-addr", "203.0.113.10:3260,1", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want external iSCSI bind rejected") + } + if !strings.Contains(err.Error(), "not loopback") { + t.Fatalf("error = %q, want loopback bind rejection", err) + } +} + +func TestParseFlags_IscsiExternalBindRequiresExplicitOptIn(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--iscsi-listen", "203.0.113.10:3260", + "--iscsi-iqn", "iqn.2026-05.io.seaweedfs:test-v1", + "--iscsi-chap-username", "user1", + "--iscsi-chap-secret", "secret1", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want explicit external bind opt-in") + } + if !strings.Contains(err.Error(), "not loopback") { + t.Fatalf("error = %q, want loopback bind rejection", err) + } +} + +func TestParseFlags_IscsiExternalBindOptInRequiresCHAP(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--allow-external-iscsi-bind", + "--iscsi-listen", "203.0.113.10:3260", + "--iscsi-iqn", "iqn.2026-05.io.seaweedfs:test-v1", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want CHAP requirement") + } + if !strings.Contains(err.Error(), "requires CHAP") { + t.Fatalf("error = %q, want CHAP requirement", err) + } +} + +func TestParseFlags_IscsiExternalBindOptInWithCHAP(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--allow-external-iscsi-bind", + "--iscsi-listen", "203.0.113.10:3260", + "--iscsi-iqn", "iqn.2026-05.io.seaweedfs:test-v1", + "--iscsi-chap-username", "user1", + "--iscsi-chap-secret", "secret1", + ) + got, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !got.allowExternalISCSIBind { + t.Fatal("allowExternalISCSIBind=false") + } +} + +func TestParseFlags_IscsiExternalBindOptInRejectsLoopback(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--allow-external-iscsi-bind", + "--iscsi-listen", "127.0.0.1:3260", + "--iscsi-iqn", "iqn.2026-05.io.seaweedfs:test-v1", + "--iscsi-chap-username", "user1", + "--iscsi-chap-secret", "secret1", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want loopback external bind rejected") + } + if !strings.Contains(err.Error(), "non-loopback") { + t.Fatalf("error = %q, want non-loopback requirement", err) + } +} + +func TestParseFlags_ExternalStatusBindIsExplicitFlag(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--status-addr", "10.0.0.12:23260", + "--allow-external-status-bind", + ) + got, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if !got.allowExternalStatusBind { + t.Fatal("allowExternalStatusBind=false") + } +} + +func TestParseFlags_RuntimeRebuildEndpointIsExplicitFlag(t *testing.T) { + f, err := parseFlags([]string{ + "--master", "127.0.0.1:9333", + "--server-id", "m01", + "--volume-id", "v1", + "--replica-id", "r1", + "--data-addr", "127.0.0.1:19101", + "--ctrl-addr", "127.0.0.1:19102", + "--status-addr", "127.0.0.1:23260", + "--runtime-rebuild-endpoint", + }) + if err != nil { + t.Fatalf("parse: %v", err) + } + if !f.runtimeRebuildEndpoint { + t.Fatalf("runtimeRebuildEndpoint=false, want true") + } +} + +func TestParseFlags_IscsiDataOutTimeoutRequiresListen(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--iscsi-dataout-timeout", "5s", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want --iscsi-dataout-timeout without --iscsi-listen rejected") + } + if !strings.Contains(err.Error(), "--iscsi-dataout-timeout requires --iscsi-listen") { + t.Fatalf("error = %q, want dataout/listen requirement", err) + } +} + +func TestParseFlags_IscsiDataOutTimeoutPlumbed(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--iscsi-listen", "127.0.0.1:3260", + "--iscsi-iqn", "iqn.2026-05.io.seaweedfs:test-v1", + "--iscsi-dataout-timeout", "5s", + ) + got, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if got.iscsiDataOutTTL != 5*time.Second { + t.Fatalf("iscsiDataOutTTL = %s", got.iscsiDataOutTTL) + } +} + +func TestParseFlags_IscsiCHAPRequiresListen(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--iscsi-chap-username", "user1", + "--iscsi-chap-secret", "secret1", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want CHAP without --iscsi-listen rejected") + } + if !strings.Contains(err.Error(), "require --iscsi-listen") { + t.Fatalf("error = %q, want CHAP/listen requirement", err) + } +} + +func TestParseFlags_IscsiCHAPRequiresUserAndSecret(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--iscsi-listen", "127.0.0.1:3260", + "--iscsi-iqn", "iqn.2026-05.io.seaweedfs:test-v1", + "--iscsi-chap-username", "user1", + ) + _, err := parseFlags(args) + if err == nil { + t.Fatal("parseFlags succeeded; want username without secret rejected") + } + if !strings.Contains(err.Error(), "must be set together") { + t.Fatalf("error = %q, want paired CHAP flag requirement", err) + } +} + +func TestParseFlags_IscsiCHAPPlumbed(t *testing.T) { + args := append(requiredBlockvolumeArgs(), + "--iscsi-listen", "127.0.0.1:3260", + "--iscsi-iqn", "iqn.2026-05.io.seaweedfs:test-v1", + "--iscsi-chap-username", "user1", + "--iscsi-chap-secret", "secret1", + ) + got, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if got.iscsiCHAPUser != "user1" || got.iscsiCHAPSecret != "secret1" { + t.Fatalf("CHAP flags = %q/%q", got.iscsiCHAPUser, got.iscsiCHAPSecret) + } +} + +func TestParseFlags_IscsiCHAPFromEnvironment(t *testing.T) { + t.Setenv("SW_BLOCK_ISCSI_CHAP_USERNAME", "env-user") + t.Setenv("SW_BLOCK_ISCSI_CHAP_SECRET", "env-secret") + args := append(requiredBlockvolumeArgs(), + "--iscsi-listen", "127.0.0.1:3260", + "--iscsi-iqn", "iqn.2026-05.io.seaweedfs:test-v1", + ) + got, err := parseFlags(args) + if err != nil { + t.Fatalf("parseFlags: %v", err) + } + if got.iscsiCHAPUser != "env-user" || got.iscsiCHAPSecret != "env-secret" { + t.Fatalf("CHAP env = %q/%q", got.iscsiCHAPUser, got.iscsiCHAPSecret) + } +} + +func requiredBlockvolumeArgs() []string { + return []string{ + "--master", "127.0.0.1:9333", + "--server-id", "s1", + "--volume-id", "v1", + "--replica-id", "r1", + "--data-addr", "127.0.0.1:18080", + "--ctrl-addr", "127.0.0.1:18081", + } +} diff --git a/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go b/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go new file mode 100644 index 0000000000..21b87a9494 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go @@ -0,0 +1,189 @@ +//go:build subprocess + +package main_test + +import ( + "bytes" + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "testing" + "time" +) + +// Power loss with real binaries (INV-FE-FLUSH-SYNC-001): +// blockvolume keeps its durable root on a dm-log-writes device. The guest +// writes over iSCSI and issues SYNCHRONIZE CACHE; once the last sync returns, +// the harness marks the log "acknowledged". Later writes and their sync must +// not survive the replay. The +// volume is killed, and the harness replays the log only up to that mark onto +// a fresh device mounted at the same path: the disk as a power cut at the +// mark would have left it, with no page cache. A restarted blockvolume must +// read back every block acknowledged by a sync. +// +// Environment, set by the external replay harness (root, dm_log_writes): +// +// SWBLOCK_REPLAY_ROOT mount point of the dm-log-writes filesystem +// SWBLOCK_REPLAY_CUT executable: "mark" marks the log, "replay" +// unmounts, replays to the mark and remounts +// SWBLOCK_TEST_BINS optional dir with prebuilt blockmaster/blockvolume +// SWBLOCK_REPLAY_LOGS optional existing dir for master state and logs +// SWBLOCK_REPLAY_DROP_SYNC "1" = negative control: after one SYNCHRONIZE +// CACHE makes the store durable, the measured +// writes get none, so blocks must be lost (the test +// passes and prints REPLAY_control_RED) +// +// The harness is cmd/blockvolume/testdata/powerloss-replay.sh. +func TestPowerLossReplayAckedWritesSurvive(t *testing.T) { + root, cut := os.Getenv("SWBLOCK_REPLAY_ROOT"), os.Getenv("SWBLOCK_REPLAY_CUT") + if root == "" && cut == "" { + t.Skip("requires the isolated dm-log-writes replay harness") + } + if root == "" || cut == "" { + t.Fatalf("SWBLOCK_REPLAY_ROOT=%q and SWBLOCK_REPLAY_CUT=%q must be set together", root, cut) + } + dropSync := os.Getenv("SWBLOCK_REPLAY_DROP_SYNC") == "1" + bins := powerLossBins(t) + art := t.TempDir() // master state and logs stay off the replayed device + if d := os.Getenv("SWBLOCK_REPLAY_LOGS"); d != "" { + art = d // kept for the receipts + } + _, masterAddr := startSingleSlotMaster(t, bins, art) + + iqn := "iqn.2026-11.example.powerloss:v1" + store := filepath.Join(root, "r1-store") + dataAddr, ctrlAddr := pickAddr(t), pickAddr(t) + statusAddr, iscsiAddr := pickAddr(t), pickAddr(t) + opts := volOpts{ + masterAddr: masterAddr, + serverID: "s1", + replicaID: "r1", + dataAddr: dataAddr, + ctrlAddr: ctrlAddr, + statusAddr: statusAddr, + iscsiAddr: iscsiAddr, + iscsiIQN: iqn, + durableRoot: store, + logTag: "powerloss-r1-initial", + } + r1 := startG54Volume(t, bins, art, opts) + waitHealthyReplica(t, statusAddr, "r1", 10*time.Second) + waitProductIscsiReady(t, iscsiAddr, 5*time.Second) + + const ( + bs = 4096 + acked = 160 // LBAs 0..159 are written and synced before the mark + afterBy = 32 // LBAs 160..191 are written after the mark, never synced + ) + block := func(lba uint32, gen byte) []byte { + b := bytes.Repeat([]byte{byte(lba) ^ gen}, bs) + copy(b, fmt.Sprintf("powerloss lba=%d gen=%d", lba, gen)) + return b + } + cli := dialG8Iscsi(t, iscsiAddr, iqn) + // The store and one block are durable before the measured writes, so a + // red control shows block loss in an existing store, not a lost store. + base := block(acked+afterBy, 9) + cli.write10(t, acked+afterBy, base) + cli.syncCache10(t) + want := map[uint32][]byte{} + for lba := uint32(0); lba < acked; lba++ { + b := block(lba, 1) + cli.write10(t, lba, b) + want[lba] = b + if !dropSync && (lba+1)%8 == 0 { + cli.syncCache10(t) + } + } + if !dropSync { + cli.syncCache10(t) + } + runReplayCut(t, cut, "mark") + for lba := uint32(acked); lba < acked+afterBy; lba++ { + cli.write10(t, lba, block(lba, 2)) + } + if !dropSync { + cli.syncCache10(t) // after the mark: the replay must exclude it + } + cli.close(t) + + // Power cut: no shutdown, no page cache. The replay stops at the mark. + if err := r1.cmd.Process.Kill(); err != nil { + t.Fatalf("kill blockvolume: %v", err) + } + _ = r1.cmd.Wait() + runReplayCut(t, cut, "replay") + + opts.logTag = "powerloss-r1-after-replay" + _ = startG54Volume(t, bins, art, opts) + waitHealthyReplica(t, statusAddr, "r1", 20*time.Second) + waitProductIscsiReady(t, iscsiAddr, 5*time.Second) + + cli2 := dialG8Iscsi(t, iscsiAddr, iqn) + defer cli2.close(t) + if got := cli2.read10(t, acked+afterBy, 1, bs); !bytes.Equal(got, base) { + t.Fatalf("the block synced before the measured writes is gone: the store did not survive the replay") + } + lost := 0 + first := -1 + for lba := uint32(0); lba < acked; lba++ { + if got := cli2.read10(t, lba, 1, bs); !bytes.Equal(got, want[lba]) { + if first < 0 { + first = int(lba) + } + lost++ + } + } + after := 0 + for lba := uint32(acked); lba < acked+afterBy; lba++ { + if bytes.Equal(cli2.read10(t, lba, 1, bs), block(lba, 2)) { + after++ + } + } + t.Logf("drop_sync=%v: acked blocks lost %d of %d (first %d); post-mark blocks present %d of %d", + dropSync, lost, acked, first, after, afterBy) + if after != 0 { + t.Fatalf("%d of %d post-mark blocks survived: the replay did not stop at the mark", after, afterBy) + } + if dropSync { + if lost == 0 { + t.Fatalf("CONTROL_NOT_RED: no block lost without SYNCHRONIZE CACHE; the replay cannot show a missing sync") + } + fmt.Printf("REPLAY_control_RED lost=%d of %d first=%d\n", lost, acked, first) + return + } + if lost > 0 { + t.Fatalf("REPLAY_BYTES_MISMATCH volume: %d of %d acknowledged blocks lost after power-loss replay (first LBA %d)", + lost, acked, first) + } + fmt.Printf("REPLAY_volume_OK acked=%d post_mark_present=%d\n", acked, after) +} + +func powerLossBins(t *testing.T) l2bins { + t.Helper() + if d := os.Getenv("SWBLOCK_TEST_BINS"); d != "" { + b := l2bins{master: filepath.Join(d, "blockmaster"), volume: filepath.Join(d, "blockvolume")} + for _, p := range []string{b.master, b.volume} { + if _, err := os.Stat(p); err != nil { + t.Fatalf("prebuilt binary: %v", err) + } + } + return b + } + return buildG54Binaries(t) +} + +func runReplayCut(t *testing.T, cut string, step ...string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, cut, step...) + cmd.WaitDelay = 5 * time.Second // a hung child keeping the pipe open does not outlive the kill + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("replay harness %s: %v\n%s", step, err, out) + } + t.Logf("replay harness %s: %s", step, bytes.TrimSpace(out)) +} diff --git a/seaweed-block/cmd/blockvolume/iscsi_probe_provider.go b/seaweed-block/cmd/blockvolume/iscsi_probe_provider.go new file mode 100644 index 0000000000..ad4055b50b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/iscsi_probe_provider.go @@ -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) +} diff --git a/seaweed-block/cmd/blockvolume/iscsi_restart_l2_test.go b/seaweed-block/cmd/blockvolume/iscsi_restart_l2_test.go new file mode 100644 index 0000000000..82cf36c78c --- /dev/null +++ b/seaweed-block/cmd/blockvolume/iscsi_restart_l2_test.go @@ -0,0 +1,348 @@ +//go:build subprocess + +package main_test + +import ( + "bufio" + "bytes" + "encoding/json" + "fmt" + "io" + "net" + "os" + "os/exec" + "path/filepath" + "testing" + "time" +) + +func TestISCSI_L2DurableRestartReconnect_PreservesData(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess durable restart test; -short skip") + } + bins := buildG54Binaries(t) + art := t.TempDir() + + _, masterAddr := startSingleSlotMaster(t, bins, art) + + iqn := "iqn.2026-05.example.restart:v1" + store := filepath.Join(art, "r1-store") + dataAddr, ctrlAddr := pickAddr(t), pickAddr(t) + statusAddr, iscsiAddr := pickAddr(t), pickAddr(t) + + r1 := startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s1", + replicaID: "r1", + dataAddr: dataAddr, + ctrlAddr: ctrlAddr, + statusAddr: statusAddr, + iscsiAddr: iscsiAddr, + iscsiIQN: iqn, + durableRoot: store, + logTag: "iscsi-restart-r1-initial", + }) + waitHealthyReplica(t, statusAddr, "r1", 10*time.Second) + waitProductIscsiReady(t, iscsiAddr, 5*time.Second) + + const durableBlockSize = 4096 + payload := bytes.Repeat([]byte{0x6d}, durableBlockSize) + copy(payload, []byte("iscsi-durable-restart-reconnect-payload")) + + c1 := dialG8Iscsi(t, iscsiAddr, iqn) + c1.write10(t, 11, payload) + c1.close(t) + + r1.stop(t) + time.Sleep(500 * time.Millisecond) + + r1Restart := startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s1", + replicaID: "r1", + dataAddr: dataAddr, + ctrlAddr: ctrlAddr, + statusAddr: statusAddr, + iscsiAddr: iscsiAddr, + iscsiIQN: iqn, + durableRoot: store, + logTag: "iscsi-restart-r1-restarted", + }) + _ = r1Restart + waitHealthyReplica(t, statusAddr, "r1", 10*time.Second) + waitProductIscsiReady(t, iscsiAddr, 5*time.Second) + + c2 := dialG8Iscsi(t, iscsiAddr, iqn) + got := c2.read10(t, 11, 1, durableBlockSize) + c2.close(t) + if !bytes.Equal(got, payload) { + t.Fatalf("read after blockvolume durable restart mismatch: got prefix=%x want prefix=%x", bytePrefix(got, 32), bytePrefix(payload, 32)) + } +} + +func TestISCSI_L2DurableRestartReconnect_RepeatedCycles(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess durable restart cycle test; -short skip") + } + bins := buildG54Binaries(t) + art := t.TempDir() + + _, masterAddr := startSingleSlotMaster(t, bins, art) + + iqn := "iqn.2026-05.example.restart-cycles:v1" + store := filepath.Join(art, "r1-store") + dataAddr, ctrlAddr := pickAddr(t), pickAddr(t) + statusAddr, iscsiAddr := pickAddr(t), pickAddr(t) + + var r1 *proc + start := func(tag string) { + t.Helper() + r1 = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s1", + replicaID: "r1", + dataAddr: dataAddr, + ctrlAddr: ctrlAddr, + statusAddr: statusAddr, + iscsiAddr: iscsiAddr, + iscsiIQN: iqn, + durableRoot: store, + logTag: tag, + }) + waitHealthyReplica(t, statusAddr, "r1", 10*time.Second) + waitProductIscsiReady(t, iscsiAddr, 5*time.Second) + } + stop := func() { + t.Helper() + r1.stop(t) + time.Sleep(500 * time.Millisecond) + } + + start("iscsi-restart-cycle-0") + const durableBlockSize = 4096 + writes := make(map[uint32][]byte) + for cycle := 0; cycle < 3; cycle++ { + lba := uint32(20 + cycle) + payload := bytes.Repeat([]byte{byte(0x70 + cycle)}, durableBlockSize) + copy(payload, []byte("iscsi-durable-restart-repeated-cycle")) + payload[len(payload)-1] = byte(cycle) + + cli := dialG8Iscsi(t, iscsiAddr, iqn) + cli.write10(t, lba, payload) + for priorLBA, want := range writes { + got := cli.read10(t, priorLBA, 1, durableBlockSize) + if !bytes.Equal(got, want) { + cli.close(t) + t.Fatalf("cycle %d prior LBA %d mismatch: got prefix=%x want prefix=%x", cycle, priorLBA, bytePrefix(got, 32), bytePrefix(want, 32)) + } + } + cli.close(t) + + writes[lba] = payload + stop() + start(fmt.Sprintf("iscsi-restart-cycle-%d", cycle+1)) + } + + cli := dialG8Iscsi(t, iscsiAddr, iqn) + defer cli.close(t) + for lba, want := range writes { + got := cli.read10(t, lba, 1, durableBlockSize) + if !bytes.Equal(got, want) { + t.Fatalf("final LBA %d mismatch: got prefix=%x want prefix=%x", lba, bytePrefix(got, 32), bytePrefix(want, 32)) + } + } +} + +func TestISCSI_L2DurableSyncCacheRestart_AcceptsSyncAndPreservesWrites(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess durable sync-cache restart test; -short skip") + } + bins := buildG54Binaries(t) + art := t.TempDir() + + _, masterAddr := startSingleSlotMaster(t, bins, art) + + iqn := "iqn.2026-05.example.sync-restart:v1" + store := filepath.Join(art, "r1-store") + dataAddr, ctrlAddr := pickAddr(t), pickAddr(t) + statusAddr, iscsiAddr := pickAddr(t), pickAddr(t) + + r1 := startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s1", + replicaID: "r1", + dataAddr: dataAddr, + ctrlAddr: ctrlAddr, + statusAddr: statusAddr, + iscsiAddr: iscsiAddr, + iscsiIQN: iqn, + durableRoot: store, + logTag: "iscsi-sync-restart-r1-initial", + }) + waitHealthyReplica(t, statusAddr, "r1", 10*time.Second) + waitProductIscsiReady(t, iscsiAddr, 5*time.Second) + + const durableBlockSize = 4096 + expected := make(map[uint32][]byte) + cli := dialG8Iscsi(t, iscsiAddr, iqn) + for i := 0; i < 12; i++ { + lba := uint32(40 + i) + payload := bytes.Repeat([]byte{byte(0x30 + i)}, durableBlockSize) + copy(payload, []byte("iscsi-durable-sync-cache-restart-payload")) + payload[len(payload)-1] = byte(i) + cli.write10(t, lba, payload) + expected[lba] = payload + if (i+1)%4 == 0 { + cli.syncCache10(t) + } + } + cli.syncCache10(t) + cli.close(t) + + r1.stop(t) + time.Sleep(500 * time.Millisecond) + + _ = startG54Volume(t, bins, art, volOpts{ + masterAddr: masterAddr, + serverID: "s1", + replicaID: "r1", + dataAddr: dataAddr, + ctrlAddr: ctrlAddr, + statusAddr: statusAddr, + iscsiAddr: iscsiAddr, + iscsiIQN: iqn, + durableRoot: store, + logTag: "iscsi-sync-restart-r1-restarted", + }) + waitHealthyReplica(t, statusAddr, "r1", 10*time.Second) + waitProductIscsiReady(t, iscsiAddr, 5*time.Second) + + cli2 := dialG8Iscsi(t, iscsiAddr, iqn) + defer cli2.close(t) + for lba, want := range expected { + got := cli2.read10(t, lba, 1, durableBlockSize) + if !bytes.Equal(got, want) { + t.Fatalf("synced LBA %d mismatch after restart: got prefix=%x want prefix=%x", lba, bytePrefix(got, 32), bytePrefix(want, 32)) + } + } +} + +func startSingleSlotMaster(t *testing.T, bins l2bins, art string) (*proc, string) { + t.Helper() + storeDir := filepath.Join(art, "master-store") + if err := os.MkdirAll(storeDir, 0o755); err != nil { + t.Fatalf("master store dir %s: %v", storeDir, err) + } + topo := writeSingleSlotTopology(t, art) + logPath := filepath.Join(art, "master-single-slot.log") + lf, err := os.Create(logPath) + if err != nil { + t.Fatalf("master log: %v", err) + } + cmd := exec.Command(bins.master, + "--authority-store", storeDir, + "--listen", "127.0.0.1:0", + "--topology", topo, + "--expected-slots-per-volume", "1", + "--freshness-window", "800ms", + "--pending-grace", "100ms", + "--t0-print-ready", + ) + stdout, err := cmd.StdoutPipe() + if err != nil { + lf.Close() + t.Fatalf("master stdout pipe: %v", err) + } + cmd.Stderr = lf + if err := cmd.Start(); err != nil { + lf.Close() + t.Fatalf("master start: %v", err) + } + p := &proc{cmd: cmd, logPath: logPath} + t.Cleanup(func() { p.stop(t); lf.Close() }) + + br := bufio.NewReader(stdout) + type readyResult struct { + line []byte + err error + } + readyCh := make(chan readyResult, 1) + go func() { + line, err := br.ReadBytes('\n') + readyCh <- readyResult{line: line, err: err} + }() + var ready readyResult + select { + case ready = <-readyCh: + case <-time.After(5 * time.Second): + t.Fatalf("master ready line timeout") + } + if ready.err != nil { + t.Fatalf("master ready line: %v", ready.err) + } + go func() { _, _ = io.Copy(io.Discard, br) }() + var rl struct { + Component, Phase, Addr string + } + if err := json.Unmarshal(ready.line, &rl); err != nil { + t.Fatalf("parse master ready %q: %v", ready.line, err) + } + if rl.Addr == "" { + t.Fatalf("master ready: empty addr (line=%q)", ready.line) + } + return p, rl.Addr +} + +func writeSingleSlotTopology(t *testing.T, dir string) string { + t.Helper() + path := filepath.Join(dir, "topology-single-slot.yaml") + body := `volumes: + - volume_id: v1 + slots: + - replica_id: r1 + server_id: s1 +` + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatalf("single-slot topology: %v", err) + } + return path +} + +func waitHealthyReplica(t *testing.T, statusAddr, replicaID string, deadline time.Duration) map[string]any { + t.Helper() + got := pollStatus(t, statusAddr, deadline, func(b map[string]any) bool { + h, _ := b["Healthy"].(bool) + rid, _ := b["ReplicaID"].(string) + return h && rid == replicaID + }) + if got == nil { + t.Fatalf("%s: no Healthy status within %s", replicaID, deadline) + } + if h, _ := got["Healthy"].(bool); !h { + t.Fatalf("%s: Healthy=true expected; got status=%v", replicaID, got) + } + return got +} + +func waitProductIscsiReady(t *testing.T, iscsiAddr string, deadline time.Duration) { + t.Helper() + end := time.Now().Add(deadline) + var lastErr error + for time.Now().Before(end) { + conn, err := net.DialTimeout("tcp", iscsiAddr, 200*time.Millisecond) + if err == nil { + _ = conn.Close() + return + } + lastErr = err + time.Sleep(100 * time.Millisecond) + } + t.Fatalf("iSCSI listener %s not reachable within %s: last error: %v", iscsiAddr, deadline, lastErr) +} + +func bytePrefix(b []byte, n int) []byte { + if len(b) < n { + return b + } + return b[:n] +} diff --git a/seaweed-block/cmd/blockvolume/keep_log_test.go b/seaweed-block/cmd/blockvolume/keep_log_test.go new file mode 100644 index 0000000000..918c634fb2 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/keep_log_test.go @@ -0,0 +1,83 @@ +package main_test + +import ( + "bytes" + "math/rand" + "os" + "path/filepath" + "strings" + "testing" +) + +// keepLogCopy copies a daemon's whole log at logPath into +// $SWBLOCK_TEST_LOG_DIR (unset: nothing is copied) as +// -.log. +func keepLogCopy(testName, daemon, logPath string) error { + dir := os.Getenv("SWBLOCK_TEST_LOG_DIR") + if dir == "" { + return nil + } + data, err := os.ReadFile(logPath) + if err == nil { + err = os.MkdirAll(dir, 0o755) + } + if err == nil { + name := strings.NewReplacer("/", "_", " ", "_").Replace(testName) + "-" + daemon + ".log" + err = os.WriteFile(filepath.Join(dir, name), data, 0o644) + } + return err +} + +// keptLogFixture is a log longer than the test output keeps (16 KB), with a +// decision line at its head and one at its tail. +func keptLogFixture(t *testing.T) (path string, data []byte) { + t.Helper() + var b bytes.Buffer + b.WriteString("head: the decision at bring-up\n") + body := make([]byte, 40<<10) + rand.New(rand.NewSource(1)).Read(body) + b.Write(body) + b.WriteString("\ntail: the last line\n") + path = filepath.Join(t.TempDir(), "master.log") + if err := os.WriteFile(path, b.Bytes(), 0o644); err != nil { + t.Fatal(err) + } + return path, b.Bytes() +} + +// sameLog reports whether kept is the whole log: every byte, head to tail. +func sameLog(kept, log []byte) bool { return bytes.Equal(kept, log) } + +func TestKeptLogIsTheWholeLog(t *testing.T) { + path, data := keptLogFixture(t) + dir := filepath.Join(t.TempDir(), "evidence") + t.Setenv("SWBLOCK_TEST_LOG_DIR", dir) + if err := keepLogCopy("TestX/sub case", "master", path); err != nil { + t.Fatal(err) + } + kept, err := os.ReadFile(filepath.Join(dir, "TestX_sub_case-master.log")) + if err != nil { + t.Fatal(err) + } + if !sameLog(kept, data) { + t.Fatalf("kept %d bytes; want the whole %d-byte log", len(kept), len(data)) + } + // Control: the check refuses a copy that kept only the tail, or lost the + // last byte. + if sameLog(data[len(data)-16<<10:], data) || sameLog(data[:len(data)-1], data) { + t.Fatal("the check accepted a truncated copy") + } +} + +func TestKeptLogUnsetDirCopiesNothing(t *testing.T) { + path, _ := keptLogFixture(t) + t.Setenv("SWBLOCK_TEST_LOG_DIR", "") + cwd := t.TempDir() + t.Chdir(cwd) + if err := keepLogCopy("TestX", "master", path); err != nil { + t.Fatal(err) + } + if entries, _ := os.ReadDir(cwd); len(entries) != 0 { + t.Fatalf("with the directory unset, %d files were written", len(entries)) + } +} diff --git a/seaweed-block/cmd/blockvolume/known_zero_acceptance_integration_test.go b/seaweed-block/cmd/blockvolume/known_zero_acceptance_integration_test.go new file mode 100644 index 0000000000..8472ee3f81 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/known_zero_acceptance_integration_test.go @@ -0,0 +1,839 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// TestKnownZeroAcceptance is the KNOWN-ZERO acceptance test of a fresh volume, +// gated by KZ_RUN=1. Source role (this file, steps 1-2): +// +// (1) a fresh volume of KZ_SIZE (default 1T) and an empty first snapshot S0: +// it finishes in seconds, stages and uploads nothing, and HEAD names no +// segment; the fresh attach certified chunks known-zero. +// (2) mkfs (KZ_FS: ext4 and xfs, one volume each) on the kernel NVMe/TCP +// device, small files with known sha256, sync, snapshot S1: the chunks +// mkfs dirtied, staged chunks, uploaded bytes and HEAD size, bounded by +// the touched chunks. +// +// Device steps run only with KZ_DEVICE=1 (root through sudo -n, nvme-cli, +// mkfs). Every device path comes from kzResolve on this run's own NQN; a path +// given by name is never formatted. Without KZ_DEVICE the test writes known +// blocks through the user-space NVMe client instead (a smoke of the counters, +// not the acceptance run). Each step prints one "KZ STEP n PASS|FAIL " +// line and its counters into KZ_REPORT. +func TestKnownZeroAcceptance(t *testing.T) { + if os.Getenv("KZ_RUN") != "1" { + t.Skip("KZ_RUN=1 not set") + } + size := os.Getenv("KZ_SIZE") + if size == "" { + size = "1T" + } + bytes := headSzParse(t, size) + fss := strings.Split(os.Getenv("KZ_FS"), ",") + if os.Getenv("KZ_FS") == "" { + fss = []string{"ext4", "xfs"} + } + device := os.Getenv("KZ_DEVICE") == "1" + run := os.Getenv("KZ_RUN_ID") + if run == "" { + run = fmt.Sprintf("local-%d", time.Now().Unix()) + } + // KZ_ROLE: "" = every step in this process (the smoke); "source" = steps + // 1, 2 and 5 here, the restore target on KZ_TARGET_HOST (the + // second host), handed over through KZ_HANDOFF; "target" = steps + // 3 and 4 on this host against the source's cluster named in KZ_HANDOFF. + role := os.Getenv("KZ_ROLE") + rep := &kzReport{Run: run, Size: size, Bytes: bytes, Device: device, Role: role, StartedAt: time.Now().UTC()} + defer rep.write(t) + if role == "target" { + kzTargetRole(t, rep, bytes, device, run) + return + } + targetHost := "" + if role == "source" { + if targetHost = os.Getenv("KZ_TARGET_HOST"); targetHost == "" || os.Getenv("KZ_HANDOFF") == "" { + t.Fatal("KZ_ROLE=source needs KZ_TARGET_HOST and KZ_HANDOFF") + } + } else if role != "" { + t.Fatalf("KZ_ROLE %q: want source, target or unset", role) + } + // per file system: the source and a restore target of its S1 on its own + // server node (on KZ_TARGET_HOST in the source role); fork is not in v1 + var vols []headSzVol + for _, fs := range fss { + vols = append(vols, headSzVol{id: "kz" + fs, bytes: bytes}, + headSzVol{id: "kz" + fs + "r", bytes: bytes, server: "t-" + fs + "r", host: targetHost, restoreTarget: true}) + } + // step 5: up to kzCrashTries fresh volumes (a try whose stop lands after the + // attach commit has committed that store, so a retry needs a new one) + for i := 1; i <= kzCrashTries; i++ { + vols = append(vols, headSzVol{id: fmt.Sprintf("kzc%d", i), bytes: bytes}) + } + env, _ := headSzStartCluster(t, "kz", vols) + rep.ChunkPath = env.chunkPath + ho := kzHandoff{Run: run, Bytes: bytes, FilerGRPC: env.cluster.filerGRPC, FilerHTTP: env.cluster.filerHTTP, + Master: env.h.masterAddr, ChunkPath: env.chunkPath} + for _, fs := range fss { + v := kzSource(t, env, rep, env.hosts["kz"+fs], fs, bytes, device, run) + rep.Volumes = append(rep.Volumes, v) + if !v.S1.Completed { + continue + } + for _, kind := range []string{"restore"} { + tb := env.hosts["kz"+fs+kind[:1]] + if role == "source" { + ho.Targets = append(ho.Targets, kzHandoffTarget{Kind: kind, Volume: tb.volume, Server: tb.server, Data: tb.data, Ctrl: tb.ctrl, + Source: v.Volume, S1: v.S1Name, Dirty1: v.Dirty1, Files: v.Files, Blocks: kzHexBlocks(v.Blocks)}) + continue + } + rep.Targets = append(rep.Targets, kzTarget(t, env, rep, v, kind, tb, bytes, device, run)) + } + } + if role == "source" { + kzWriteHandoff(t, ho) + kzWaitTargetDone(t) + } + rep.Crash = kzCrashFirstStart(t, env, rep, bytes, run) +} + +// kzHandoff is what the source role hands to the target role (KZ_HANDOFF): +// the cluster to use and, per target, the S1 to restore and what the +// source wrote into it. +type kzHandoff struct { + Run string `json:"run"` + Bytes uint64 `json:"bytes"` + FilerGRPC string `json:"filer_grpc"` + FilerHTTP string `json:"filer_http"` + Master string `json:"master"` + ChunkPath string `json:"chunk_path"` + Targets []kzHandoffTarget `json:"targets"` +} + +type kzHandoffTarget struct { + Kind string `json:"kind"` + Volume string `json:"volume"` + Server string `json:"server"` + Data string `json:"data_addr"` + Ctrl string `json:"ctrl_addr"` + Source string `json:"source"` + S1 string `json:"s1"` + Dirty1 int `json:"dirty1"` + Files map[string]string `json:"files_sha256"` + Blocks map[string]string `json:"blocks_hex"` +} + +func kzHexBlocks(b map[uint64][]byte) map[string]string { + out := map[string]string{} + for lba, d := range b { + out[fmt.Sprint(lba)] = hex.EncodeToString(d) + } + return out +} + +func kzWriteHandoff(t *testing.T, ho kzHandoff) { + t.Helper() + b, _ := json.MarshalIndent(ho, "", " ") + p := os.Getenv("KZ_HANDOFF") + if err := os.WriteFile(p+".tmp", append(b, '\n'), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Rename(p+".tmp", p); err != nil { + t.Fatal(err) + } + t.Logf("KZ HANDOFF written: %s (%d targets)", p, len(ho.Targets)) +} + +// kzWaitTargetDone waits for KZ_TARGET_DONE (the window script creates it +// after the target role ended), at most KZ_TARGET_WAIT (default 90m). The +// source's cluster must stay up while the targets run. +func kzWaitTargetDone(t *testing.T) { + t.Helper() + done := os.Getenv("KZ_TARGET_DONE") + if done == "" { + t.Fatal("KZ_ROLE=source needs KZ_TARGET_DONE") + } + wait := 90 * time.Minute + if v := os.Getenv("KZ_TARGET_WAIT"); v != "" { + d, err := time.ParseDuration(v) + if err != nil { + t.Fatalf("KZ_TARGET_WAIT=%q: %v", v, err) + } + wait = d + } + poll(t, wait, "the target role never finished ("+done+" absent)", func() bool { + _, err := os.Stat(done) + return err == nil + }) +} + +// kzTargetEnv reserves the data and ctrl ports the source's cluster spec names +// for the targets BEFORE the harness picks any port of its own (its +// constructor allocates five), then builds the env on the source's filer and +// blockmaster. +func kzTargetEnv(t *testing.T, ho kzHandoff, newHarness func(*testing.T) *plannedHandoffHarness) *handoffEnv { + t.Helper() + handoffPorts.Lock() + if handoffPorts.used == nil { + handoffPorts.used = map[int]bool{} + } + for _, ht := range ho.Targets { + if err := kzReserve(handoffPorts.used, ht.Data, ht.Ctrl); err != nil { + handoffPorts.Unlock() + t.Fatalf("KZ_HANDOFF target %s: %v", ht.Volume, err) + } + } + handoffPorts.Unlock() + h := newHarness(t) + h.masterAddr = ho.Master + return &handoffEnv{h: h, cluster: &w4WeedCluster{filerGRPC: ho.FilerGRPC, filerHTTP: ho.FilerHTTP}, chunkPath: ho.ChunkPath, hosts: map[string]bvHost{}} +} + +// TestKnownZeroTargetReservesBeforeHarness: when the harness constructor runs, +// every handed-off port is already reserved, so none of its own five ports can +// be one of them (and then be refused as a collision). +func TestKnownZeroTargetReservesBeforeHarness(t *testing.T) { + ho := kzHandoff{Master: "10.9.9.1:1", Targets: []kzHandoffTarget{{Volume: "v", Data: "10.9.9.2:19991", Ctrl: "10.9.9.2:19992"}}} + called := false + kzTargetEnv(t, ho, func(t *testing.T) *plannedHandoffHarness { + called = true + handoffPorts.Lock() + defer handoffPorts.Unlock() + if !handoffPorts.used[19991] || !handoffPorts.used[19992] { + t.Fatal("the harness was built before the handed-off ports were reserved") + } + return &plannedHandoffHarness{dir: t.TempDir()} + }) + if !called { + t.Fatal("the harness constructor was never called") + } +} + +// kzTargetRole runs steps 3 and 4 on this host: no weed cluster or +// blockmaster of its own; every blockvolume uses the source's filer and +// blockmaster from KZ_HANDOFF, with the data and ctrl addresses the source's +// cluster spec names for it. +func kzTargetRole(t *testing.T, rep *kzReport, bytes uint64, device bool, run string) { + t.Helper() + b, err := os.ReadFile(os.Getenv("KZ_HANDOFF")) + if err != nil { + t.Fatalf("KZ_HANDOFF: %v", err) + } + var ho kzHandoff + if err := json.Unmarshal(b, &ho); err != nil { + t.Fatalf("KZ_HANDOFF: %v", err) + } + if ho.Run != run || ho.Bytes != bytes || len(ho.Targets) == 0 { + t.Fatalf("KZ_HANDOFF run %q bytes %d targets %d; this run %q bytes %d", ho.Run, ho.Bytes, len(ho.Targets), run, bytes) + } + env := kzTargetEnv(t, ho, newPlannedHandoffHarness) + h := env.h + rep.ChunkPath = ho.ChunkPath + for _, ht := range ho.Targets { + tb := bvHost{id: ht.Volume, server: ht.Server, replica: "r1", volume: ht.Volume, root: filepath.Join(h.dir, "vol-"+ht.Volume), + data: ht.Data, ctrl: ht.Ctrl, status: headSzLoopbackAddr(t), nvme: headSzLoopbackAddr(t)} + env.hosts[ht.Volume] = tb + src := kzVolume{Volume: ht.Source, S1Name: ht.S1, Dirty1: ht.Dirty1, Files: ht.Files, Blocks: map[uint64][]byte{}} + for k, v := range ht.Blocks { + var lba uint64 + if _, err := fmt.Sscan(k, &lba); err != nil { + t.Fatalf("KZ_HANDOFF block %q: %v", k, err) + } + d, err := hex.DecodeString(v) + if err != nil { + t.Fatalf("KZ_HANDOFF block %q: %v", k, err) + } + src.Blocks[lba] = d + } + rep.Targets = append(rep.Targets, kzTarget(t, env, rep, src, ht.Kind, tb, bytes, device, run)) + } +} + +type kzTargetRecord struct { + Volume string `json:"volume"` + Kind string `json:"kind"` + Source string `json:"source"` + Snapshot string `json:"snapshot"` + NQN string `json:"nqn"` + Identity string `json:"device_identity,omitempty"` + Before kzStats `json:"stats_before_reads"` + After kzStats `json:"stats_after_reads"` + ReadsEqual int `json:"reads_equal"` + ReadsZero int `json:"reads_zero"` + Reads int `json:"reads"` + FilesEqual int `json:"files_equal"` + FirstCut kzCutRecord `json:"first_snapshot"` +} + +// kzTarget restores the source's S1 into tb, then runs step 4 (read +// the S1-named blocks BEFORE hydration: data, never zeros; the read itself +// waits for its chunk) and step 3 (all contents equal the source; the target's +// first snapshot completes without a full scan). +func kzTarget(t *testing.T, env *handoffEnv, rep *kzReport, src kzVolume, kind string, tb bvHost, bytes uint64, device bool, run string) kzTargetRecord { + t.Helper() + r := kzTargetRecord{Volume: tb.volume, Kind: kind, Source: src.Volume, Snapshot: src.S1Name, + NQN: fmt.Sprintf("nqn.2026-11.io.seaweedfs:kz-%s-%s", run, tb.volume)} + // The target is placement only: before its restore the master has no + // record of it, so the restore creates it. + if out, errOut, code := env.h.run(t, "ops", "chunk", "show", "--master", env.h.masterAddr, "--volume", tb.volume, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath); code == 0 || !strings.Contains(out+errOut, "resolve --volume") || !strings.Contains(out+errOut, "not found") { + t.Fatalf("restore target %s has a volume record before its restore: exit %d %s %s", tb.volume, code, out, errOut) + } + env.h.command(t, "ops", "chunk", "restore", "--source", src.Volume, "--snapshot", src.S1Name, "--target", tb.volume, + "--master", env.h.masterAddr, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--request-id", "kz-"+kind+"-"+tb.volume) + d, refusal := headSzStartVolume(t, env, tb, bytes, "--nvme-subsysnqn", r.NQN) + if d == nil { + rep.step(t, 3, tb.volume, false, kind+" target refused: "+refusal) + return r + } + defer d.term(t, 60*time.Second) + + // (4) wrong-zero guard, before any hydration (a restore is driven only after) + r.Before = kzReadStats(t, tb) + c := dialNVMe(t, tb.nvme, r.NQN) + zero := make([]byte, 4096) + for lba, want := range src.Blocks { + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + got := c.read(t, lba, 4096) + r.Reads++ + switch { + case string(got) == string(want): + r.ReadsEqual++ + case string(got) == string(zero): + r.ReadsZero++ + } + } + c.close() + r.After = kzReadStats(t, tb) + waited := r.After.Hydration.WaitCalls - r.Before.Hydration.WaitCalls + ok4 := r.Reads > 0 && r.ReadsEqual == r.Reads && r.ReadsZero == 0 && r.Before.AbsentChunks > 0 && waited > 0 + rep.step(t, 4, tb.volume, ok4, fmt.Sprintf("%s reads=%d equal=%d zero=%d absent_before=%d absent_after=%d read_waits=%d fetches=%d", + kind, r.Reads, r.ReadsEqual, r.ReadsZero, r.Before.AbsentChunks, r.After.AbsentChunks, waited, + r.After.Hydration.Fetches-r.Before.Hydration.Fetches)) + + // (3) contents equal + first snapshot without a full scan (v1 fills a + // restore target on access: the reads below fetch any chunk still absent) + if device { + r.Identity, r.FilesEqual = kzDeviceVerify(t, tb, r.NQN, src, run) + } else { + c := dialNVMe(t, tb.nvme, r.NQN) + for lba, want := range src.Blocks { + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + if string(c.read(t, lba, 4096)) == string(want) { + r.FilesEqual++ + } + } + c.close() + } + total := int((bytes + kzChunkBytes - 1) / kzChunkBytes) + r.FirstCut = kzCut(t, env, headSzConfig{snapshotTimeout: "120s", attempts: 3, name: "kz-" + tb.volume + "-s"}, tb, 0, total) + want := len(src.Files) + cand := kzLC(r.FirstCut.Stats).CandidateChunks + ok3 := r.FilesEqual == want && want > 0 && r.FirstCut.Completed && cand <= src.Dirty1 + rep.step(t, 3, tb.volume, ok3, fmt.Sprintf("%s files_equal=%d/%d first_snapshot completed=%v candidates=%d (source dirtied %d) of %d chunks wall_ms=%.0f", + kind, r.FilesEqual, want, r.FirstCut.Completed, cand, src.Dirty1, total, r.FirstCut.WallMs)) + return r +} + +// kzWaitDevice resolves this run's NQN from sysfs for up to 30 s; on timeout +// the last refusal is in the failure, so a lab log names the check that held. +func kzWaitDevice(t *testing.T, nqn string) kzDevice { + t.Helper() + sys := os.DirFS("/sys/class") + var last error + deadline := time.Now().Add(30 * time.Second) + for time.Now().Before(deadline) { + d, err := kzResolve(sys, nqn, "") + if err == nil { + return d + } + last = err + time.Sleep(200 * time.Millisecond) + } + t.Fatalf("kernel device for %s never appeared: %v", nqn, last) + return kzDevice{} +} + +// kzDeviceVerify connects the target through the kernel, resolves it by +// NQN, mounts it read-only under the run's scratch, compares every source +// file's sha256, unmounts and disconnects. +func kzDeviceVerify(t *testing.T, tb bvHost, nqn string, src kzVolume, run string) (string, int) { + t.Helper() + host, port := kzSplit(t, tb.nvme) + kzSudo(t, "nvme", "connect", "-t", "tcp", "-n", nqn, "-a", host, "-s", port) + defer kzSudo(t, "nvme", "disconnect", "-n", nqn) + var dev kzDevice + dev = kzWaitDevice(t, nqn) + t.Log(dev.Identity()) + mnt := filepath.Join(os.TempDir(), "kz-"+run, tb.volume) + if err := os.MkdirAll(mnt, 0o755); err != nil { + t.Fatal(err) + } + kzSudo(t, "mount", "-o", "ro", dev.Path, mnt) + defer kzSudo(t, "umount", mnt) + equal := 0 + for name, want := range src.Files { + out := kzSudo(t, "sha256sum", filepath.Join(mnt, name)) + if f := strings.Fields(out); len(f) > 0 && f[0] == want { + equal++ + } + } + return dev.Identity(), equal +} + +// kzReport is the JSON evidence (KZ_REPORT); Lines are the step verdicts. +type kzReport struct { + Run string `json:"run"` + Size string `json:"size"` + Bytes uint64 `json:"bytes"` + Device bool `json:"device"` + Role string `json:"role,omitempty"` + ChunkPath string `json:"chunk_path"` + StartedAt time.Time `json:"started_at"` + Volumes []kzVolume `json:"volumes"` + Targets []kzTargetRecord `json:"targets"` + Crash kzCrashRecord `json:"crash"` + HoldBin string `json:"hold_bin,omitempty"` + Lines []string `json:"lines"` +} + +const kzCrashTries = 3 + +type kzCrashTry struct { + Volume string `json:"volume"` + Markers []string `json:"markers_at_stop"` + Before bool `json:"stopped_before_commit"` +} + +type kzCrashRecord struct { + Tries []kzCrashTry `json:"tries"` + Volume string `json:"volume,omitempty"` + FreshLine string `json:"fresh_line_after_restart,omitempty"` + S0 kzCutRecord `json:"s0_after_restart"` + Dirty1 int `json:"dirty_chunks_before_s1"` + S1 kzCutRecord `json:"s1_after_restart"` + Equal int `json:"blocks_equal"` + Blocks int `json:"blocks"` +} + +// kzHoldBin is KZ_HOLD_BIN: the kzhold-tagged blockvolume (go build -tags kzhold +// ./cmd/blockvolume), test-only and never released; its sha256 goes into the +// report so the evidence names exactly which binary held. +func kzHoldBin(t *testing.T, rep *kzReport) string { + t.Helper() + p := os.Getenv("KZ_HOLD_BIN") + if p == "" { + t.Fatal("step 5 needs KZ_HOLD_BIN (a blockvolume built with -tags kzhold)") + } + b, err := os.ReadFile(p) + if err != nil { + t.Fatalf("KZ_HOLD_BIN: %v", err) + } + sum := sha256.Sum256(b) + rep.HoldBin = p + " sha256:" + hex.EncodeToString(sum[:]) + return p +} + +// kzFreshAtStop reads, after the held first start was killed, whether b's +// store is still fresh: the fresh state is in the store's descriptor +// (WALStore.LayoutIdentity), set before the first claim and cleared only by +// the attach commit; the .chunkfresh sidecar the step once looked for no +// longer exists. The store is the one under b's layout directory +// (/-/, --layout-id), or under b's root without one. The +// returned record (markers_at_stop) names the store read and what it held. +func kzFreshAtStop(b bvHost) (bool, []string) { + stores, _ := filepath.Glob(filepath.Join(b.root, b.volume+"-*", b.volume+".bin")) + if len(stores) == 0 { + stores, _ = filepath.Glob(filepath.Join(b.root, b.volume+".bin")) + } + if len(stores) != 1 { + return false, []string{fmt.Sprintf("%d stores for %s under %s", len(stores), b.volume, b.root)} + } + ws, err := storage.OpenWALStore(stores[0]) + if err != nil { + return false, []string{fmt.Sprintf("%s: open: %v", stores[0], err)} + } + defer ws.Close() + claim, fresh, ok := ws.LayoutIdentity() + return ok && fresh, []string{fmt.Sprintf("%s layout_identity set=%t fresh=%t claim=%s", stores[0], ok, fresh, claim)} +} + +// kzCrashFirstStart is step 5: +// the first start of a fresh volume runs the kzhold test binary, which holds +// at the boundary before the fresh marker is retired; the test SIGKILLs it +// there and requires the store still fresh (kzFreshAtStop). More than one try fails +// the step. Then restart that volume and +// repeat steps 1-2: nothing certified known-zero (KnownZeroChunks 0, no +// fresh-attach line), the first cut scans every chunk once, the next cut only +// the touched ones, and the written blocks read back exactly. +func kzCrashFirstStart(t *testing.T, env *handoffEnv, rep *kzReport, bytes uint64, run string) kzCrashRecord { + t.Helper() + var r kzCrashRecord + total := int((bytes + kzChunkBytes - 1) / kzChunkBytes) + var b bvHost + for i := 1; i <= kzCrashTries; i++ { + b = env.hosts[fmt.Sprintf("kzc%d", i)] + nqn := fmt.Sprintf("nqn.2026-11.io.seaweedfs:kz-%s-%s", run, b.volume) + env.volExtra = []string{"--durable-blocks", fmt.Sprint(bytes / 4096), "--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off", "--nvme-subsysnqn", nqn} + // Deterministic, with no hook in a release binary: the + // first start runs KZ_HOLD_BIN, a blockvolume built with the kzhold tag + // (test-only, never released), which holds at the provider's existing + // boundary after presence and before the fresh marker is retired (the + // attach commit) and writes /reached there. The release stays + // absent: the process is killed while held. + holdDir := filepath.Join(env.h.dir, "kzhold-"+b.id) + if err := os.MkdirAll(holdDir, 0o755); err != nil { + t.Fatal(err) + } + reached := filepath.Join(holdDir, "reached") + os.Setenv("SWBLOCK_KZHOLD_DIR", holdDir) + d := env.h.start(t, "blockvolume-"+b.id+"-first", kzHoldBin(t, rep), env.volArgsFor(b)...) + os.Unsetenv("SWBLOCK_KZHOLD_DIR") + end := time.Now().Add(120 * time.Second) + for { + if _, err := os.Stat(reached); err == nil { + break + } + select { + case <-d.done: + t.Fatalf("%s exited before the hold was reached: %v", b.id, d.err) + case <-time.After(20 * time.Millisecond): + } + if time.Now().After(end) { + t.Fatalf("%s never reached the hold (%s)", b.id, reached) + } + } + if !d.has("TEST-ONLY build (kzhold)") { + t.Fatalf("%s: the first start is not the kzhold build", b.id) + } + if err := d.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatalf("SIGSTOP %s: %v", b.id, err) + } + d.kill(t) + fresh, markers := kzFreshAtStop(b) + try := kzCrashTry{Volume: b.volume, Markers: markers, Before: fresh} + r.Tries = append(r.Tries, try) + if try.Before { + break + } + } + last := r.Tries[len(r.Tries)-1] + if !last.Before { + rep.step(t, 5, "kzc", false, fmt.Sprintf("no try stopped before the attach commit in %d tries (marker always gone)", len(r.Tries))) + return r + } + r.Volume = b.volume + nqn := fmt.Sprintf("nqn.2026-11.io.seaweedfs:kz-%s-%s", run, b.volume) + d, refusal := headSzStartVolume(t, env, b, bytes, "--nvme-subsysnqn", nqn) + if d == nil { + rep.step(t, 5, b.volume, false, "restart refused: "+refusal) + return r + } + defer d.term(t, 60*time.Second) + r.FreshLine = strings.TrimSpace(d.line("known-zero")) + cfg := headSzConfig{snapshotTimeout: "120s", attempts: 3, name: "kz-" + b.volume + "-s"} + r.S0 = kzCut(t, env, cfg, b, 0, total) + _, blocks := kzUserSpaceFiles(t, b, nqn, bytes) + r.Dirty1 = kzReadStats(t, b).DirtyChunks + r.S1 = kzCut(t, env, cfg, b, 1, total) + c := dialNVMe(t, b.nvme, nqn) + for lba, want := range blocks { + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + r.Blocks++ + if string(c.read(t, lba, 4096)) == string(want) { + r.Equal++ + } + } + c.close() + s0, s1 := kzLC(r.S0.Stats), kzLC(r.S1.Stats) + // the stop is deterministic (the kzhold hold), so an acceptance run must catch the marker on the FIRST try + ok := len(r.Tries) == 1 && r.S0.Completed && r.S1.Completed && r.S0.Stats.KnownZeroChunks == 0 && r.FreshLine == "" && + s0.CandidateChunks == total && s1.CandidateChunks <= r.Dirty1 && r.Equal == r.Blocks && r.Blocks > 0 + rep.step(t, 5, b.volume, ok, fmt.Sprintf("tries=%d marker_at_stop=%v known_zero=%d fresh_line=%t s0_candidates=%d/%d s0_uploaded=%d s1_candidates=%d (dirtied %d) blocks_equal=%d/%d", + len(r.Tries), last.Markers, r.S0.Stats.KnownZeroChunks, r.FreshLine != "", s0.CandidateChunks, total, s0.UploadedChunks, s1.CandidateChunks, r.Dirty1, r.Equal, r.Blocks)) + return r +} + +func (r *kzReport) step(t *testing.T, n int, vol string, pass bool, why string) { + t.Helper() + v := "FAIL" + if pass { + v = "PASS" + } + l := fmt.Sprintf("KZ STEP %d %s %s %s", n, v, vol, why) + r.Lines = append(r.Lines, l) + t.Log(l) + if !pass { + t.Error(l) + } +} + +func (r *kzReport) write(t *testing.T) { + if p := os.Getenv("KZ_REPORT"); p != "" { + b, _ := json.MarshalIndent(r, "", " ") + if err := os.WriteFile(p, append(b, '\n'), 0o644); err != nil { + t.Errorf("KZ_REPORT: %v", err) + } + } +} + +type kzVolume struct { + Volume string `json:"volume"` + FS string `json:"fs"` + NQN string `json:"nqn"` + Identity string `json:"device_identity,omitempty"` + Fresh string `json:"fresh_attach_line"` + S0 kzCutRecord `json:"s0"` + Dirty1 int `json:"dirty_chunks_before_s1"` + Discard string `json:"discard,omitempty"` + S1 kzCutRecord `json:"s1"` + Files map[string]string `json:"files_sha256,omitempty"` + S1Name string `json:"s1_name"` + Blocks map[uint64][]byte `json:"-"` +} + +type kzCutRecord struct { + Cut headSzCut `json:"cut"` + Stats kzStats `json:"stats_after"` + Total int `json:"total_chunks"` + WallMs float64 `json:"wall_ms"` + Completed bool `json:"completed"` +} + +func kzReadStats(t *testing.T, b bvHost) kzStats { + t.Helper() + var c struct{ Stats kzStats } + raw := headSzChunkStatus(t, b) + if raw == nil { + t.Fatalf("%s: durable status has no chunk section", b.volume) + } + if err := json.Unmarshal(raw, &c); err != nil { + t.Fatalf("%s: chunk status: %v", b.volume, err) + } + return c.Stats +} + +const kzChunkBytes = 4 << 20 + +func kzSource(t *testing.T, env *handoffEnv, rep *kzReport, b bvHost, fs string, bytes uint64, device bool, run string) kzVolume { + t.Helper() + total := int((bytes + kzChunkBytes - 1) / kzChunkBytes) + v := kzVolume{Volume: b.volume, FS: fs, NQN: fmt.Sprintf("nqn.2026-11.io.seaweedfs:kz-%s-%s", run, b.volume)} + d, refusal := headSzStartVolume(t, env, b, bytes, "--nvme-subsysnqn", v.NQN) + if d == nil { + rep.step(t, 1, b.volume, false, "volume refused: "+refusal) + return v + } + defer d.term(t, 60*time.Second) + v.Fresh = strings.TrimSpace(d.line("known-zero")) + + // (1) empty S0 + cfg := headSzConfig{snapshotTimeout: "120s", attempts: 3, name: "kz-" + b.volume + "-s"} + v.S0 = kzCut(t, env, cfg, b, 0, total) + st := v.S0.Stats + ok1, why1 := kzStep1Pass(st, v.S0.Completed, v.S0.Cut.HeadSegments, total, v.Fresh != "") + rep.step(t, 1, b.volume, ok1, fmt.Sprintf("%s s0 completed=%v wall_ms=%.0f candidates=%d staged=%d uploaded_chunks=%d head_segments=%d head_bytes=%d known_zero=%d/%d fresh_line=%t", + why1, v.S0.Completed, v.S0.WallMs, kzLC(st).CandidateChunks, kzLC(st).StagedChunks, kzLC(st).UploadedChunks, v.S0.Cut.HeadSegments, v.S0.Cut.HeadBytes, st.KnownZeroChunks, total, v.Fresh != "")) + + // (2) mkfs + files + S1 + if device { + var first map[string]uint64 + v.Identity, v.Discard, v.Files, first = kzDeviceFiles(t, b, v.NQN, fs, run) + v.Blocks = kzDeviceWitnesses(t, b, v.NQN, first) + } else { + v.Files, v.Blocks = kzUserSpaceFiles(t, b, v.NQN, bytes) + } + v.Dirty1 = kzReadStats(t, b).DirtyChunks + v.S1 = kzCut(t, env, cfg, b, 1, total) + v.S1Name = cfg.name + "-1" + st = v.S1.Stats + touched := v.Dirty1 + ok2 := v.S1.Completed && st.LastCut != nil && touched > 0 && st.LastCut.CandidateChunks <= touched && + st.LastCut.StagedChunks <= touched && st.LastCut.UploadedBytes <= int64(touched)*kzChunkBytes && len(v.Files) > 0 && + len(v.Blocks) == len(v.Files) // one block witness per written file or block, for step 4 + rep.step(t, 2, b.volume, ok2, fmt.Sprintf("s1 completed=%v wall_ms=%.0f dirtied=%d candidates=%d staged=%d uploaded_bytes=%d head_bytes=%d files=%d discard=%q", + v.S1.Completed, v.S1.WallMs, touched, kzLC(st).CandidateChunks, kzLC(st).StagedChunks, kzLC(st).UploadedBytes, v.S1.Cut.HeadBytes, len(v.Files), v.Discard)) + return v +} + +// kzLC returns the last cut or a zero value, for printing only. +func kzLC(s kzStats) struct { + CandidateChunks, StagedChunks, UploadedChunks, ZeroedChunks, UnchangedChunks int + UploadedBytes int64 +} { + if s.LastCut == nil { + return struct { + CandidateChunks, StagedChunks, UploadedChunks, ZeroedChunks, UnchangedChunks int + UploadedBytes int64 + }{} + } + return *s.LastCut +} + +func kzCut(t *testing.T, env *handoffEnv, cfg headSzConfig, b bvHost, n, total int) kzCutRecord { + t.Helper() + start := time.Now() + c := headSzCutOnce(t, env, cfg, b, n, 0) + return kzCutRecord{Cut: c, Stats: kzReadStats(t, b), Total: total, WallMs: ms(time.Since(start)), Completed: c.Completed} +} + +// kzUserSpaceFiles writes three known 4 KiB blocks (the first, middle and last +// block of the volume, so three different chunks) through the user-space +// client and flushes (smoke only: no file system). +func kzUserSpaceFiles(t *testing.T, b bvHost, nqn string, bytes uint64) (map[string]string, map[uint64][]byte) { + t.Helper() + c := dialNVMe(t, b.nvme, nqn) + out, blocks := map[string]string{}, map[uint64][]byte{} + last := bytes/4096 - 1 + for i, lba := range []uint64{0, last / 2, last} { + blk := f1Block(b.id, 0, "kz", lba) + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + c.write(t, lba, blk) + blocks[lba] = blk + sum := sha256.Sum256(blk) + out[fmt.Sprintf("block-%d", i)] = hex.EncodeToString(sum[:]) + } + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + c.flush(t) + return out, blocks +} + +// kzDeviceFiles connects this run's NQN through the kernel, resolves the +// device by NQN, formats it, writes files with known sha256, syncs, unmounts +// and disconnects. It returns the identity line, whether mkfs sent a discard, +// the files' sha256 and each file's first device block (FIEMAP, 4 KiB blocks). +func kzDeviceFiles(t *testing.T, b bvHost, nqn, fs, run string) (string, string, map[string]string, map[string]uint64) { + t.Helper() + host, port := kzSplit(t, b.nvme) + kzSudo(t, "nvme", "connect", "-t", "tcp", "-n", nqn, "-a", host, "-s", port) + defer kzSudo(t, "nvme", "disconnect", "-n", nqn) + var dev kzDevice + dev = kzWaitDevice(t, nqn) + t.Log(dev.Identity()) + mkfs := map[string][]string{"ext4": {"mkfs.ext4", "-F", "-v"}, "xfs": {"mkfs.xfs", "-f"}}[fs] + if mkfs == nil { + t.Fatalf("KZ_FS %q: want ext4 or xfs", fs) + } + out := kzSudo(t, append(mkfs, dev.Path)...) + discard := "no" + if strings.Contains(strings.ToLower(out), "discard") { + discard = "yes: " + kzFirstLine(out, "iscard") + } + mnt := filepath.Join(os.TempDir(), "kz-"+run, b.volume) + if err := os.MkdirAll(mnt, 0o755); err != nil { + t.Fatal(err) + } + kzSudo(t, "mount", dev.Path, mnt) + files, first := map[string]string{}, map[string]uint64{} + func() { + defer kzSudo(t, "umount", mnt) + if bs := strings.TrimSpace(kzSudo(t, "stat", "-f", "-c", "%S", mnt)); bs != "4096" { + t.Fatalf("%s: file-system block size %s, the witness mapping needs 4096", mnt, bs) + } + for i := 0; i < 4; i++ { + name := fmt.Sprintf("kz-%d.bin", i) + data := make([]byte, (i+1)*64*1024) + for j := range data { + data[j] = byte(i*31 + j%251) + } + kzSudoWrite(t, filepath.Join(mnt, name), data) + sum := sha256.Sum256(data) + files[name] = hex.EncodeToString(sum[:]) + } + kzSudo(t, "sync") + for name := range files { + pb, err := kzFirstPhysical(kzSudo(t, "filefrag", "-e", filepath.Join(mnt, name))) + if err != nil { + t.Fatalf("filefrag %s: %v", name, err) + } + first[name] = pb + } + }() + return dev.Identity(), discard, files, first +} + +// kzDeviceWitnesses reads, through the user-space client after the kernel +// disconnected, the first block of every file and requires it to be that +// file's first 4 KiB as written: the block witnesses step 4 reads on the +// targets before hydration. +func kzDeviceWitnesses(t *testing.T, b bvHost, nqn string, first map[string]uint64) map[uint64][]byte { + t.Helper() + c := dialNVMe(t, b.nvme, nqn) + defer c.close() + out := map[uint64][]byte{} + for name, lba := range first { + var i int + if _, err := fmt.Sscanf(name, "kz-%d.bin", &i); err != nil { + t.Fatalf("file %q: %v", name, err) + } + want := make([]byte, 4096) + for j := range want { + want[j] = byte(i*31 + j%251) + } + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + got := c.read(t, lba, 4096) + if string(got) != string(want) { + t.Fatalf("%s: device block %d is not the file's first 4 KiB (the witness mapping is wrong)", name, lba) + } + out[lba] = got + } + return out +} + +func kzSudo(t *testing.T, args ...string) string { + t.Helper() + out, err := exec.Command("sudo", append([]string{"-n"}, args...)...).CombinedOutput() + if err != nil { + t.Fatalf("sudo %s: %v: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out))) + } + return string(out) +} + +func kzSudoWrite(t *testing.T, path string, data []byte) { + t.Helper() + c := exec.Command("sudo", "-n", "tee", path) + c.Stdin = strings.NewReader(string(data)) + out, err := c.CombinedOutput() + sum := sha256.Sum256(data) + back := "" + if err == nil { + if f := strings.Fields(kzSudo(t, "sha256sum", path)); len(f) > 0 { + back = f[0] + } + } + if err := kzCheckWrite(out, err, hex.EncodeToString(sum[:]), back); err != nil { + t.Fatalf("%s: %v", path, err) + } +} + +func kzSplit(t *testing.T, addr string) (string, string) { + t.Helper() + i := strings.LastIndex(addr, ":") + if i < 0 { + t.Fatalf("address %q has no port", addr) + } + return addr[:i], addr[i+1:] +} + +func kzFirstLine(s, sub string) string { + for _, l := range strings.Split(s, "\n") { + if strings.Contains(l, sub) { + return strings.TrimSpace(l) + } + } + return "" +} diff --git a/seaweed-block/cmd/blockvolume/known_zero_checks_test.go b/seaweed-block/cmd/blockvolume/known_zero_checks_test.go new file mode 100644 index 0000000000..2541ec9972 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/known_zero_checks_test.go @@ -0,0 +1,176 @@ +package main_test + +import ( + "errors" + "fmt" + "net" + "regexp" + "strconv" + "strings" + "testing" +) + +// kzStats is the part of the chunk layer's durable status the KNOWN-ZERO +// acceptance test reads. +type kzStats struct { + DirtyChunks int + StagedChunks uint64 + KnownZeroChunks uint64 + AbsentChunks int + Hydration struct{ WaitCalls, Fetches, Completed, FetchErrors uint64 } + LastCut *struct { + CandidateChunks, StagedChunks, UploadedChunks, ZeroedChunks, UnchangedChunks int + UploadedBytes int64 + } +} + +// kzStep1Pass is step 1's verdict: the empty first snapshot completed, +// considered no chunk, staged and uploaded nothing, HEAD names no segment, and +// the fresh attach certified EVERY chunk known-zero (a partial certification +// means the first cut scanned the rest). +func kzStep1Pass(s kzStats, completed bool, headSegments, total int, freshLine bool) (bool, string) { + switch { + case !completed: + return false, "s0 did not complete" + case s.LastCut == nil: + return false, "no last cut" + case s.LastCut.CandidateChunks != 0: + return false, fmt.Sprintf("s0 considered %d chunks (want 0: no scan)", s.LastCut.CandidateChunks) + case s.LastCut.StagedChunks != 0 || s.LastCut.UploadedChunks != 0: + return false, "s0 staged or uploaded chunks" + case headSegments != 0: + return false, fmt.Sprintf("HEAD names %d segments", headSegments) + case s.KnownZeroChunks != uint64(total): + return false, fmt.Sprintf("known-zero %d of %d chunks (want all)", s.KnownZeroChunks, total) + case !freshLine: + return false, "no fresh-attach line" + } + return true, "" +} + +// kzCheckWrite: a file write is good only when the writer exited 0 (any +// error fails, also one that came with output, as tee prints the data it was +// given) and the file read back has the sha256 of what was written. +func kzCheckWrite(out []byte, err error, want, readBack string) error { + if err != nil { + return fmt.Errorf("write failed: %v (%d bytes of output)", err, len(out)) + } + if readBack != want { + return fmt.Errorf("read back sha256 %s, wrote %s", readBack, want) + } + return nil +} + +var kzExtentRE = regexp.MustCompile(`^\s*\d+:\s+\d+\.\.\s*\d+:\s+(\d+)\.\.\s*\d+:\s+\d+:`) + +// kzFirstPhysical parses `filefrag -e FILE` and returns the physical start +// (in file-system blocks) of the file's first extent: where its first block +// lives on the device. ext4 and XFS print the same table. +func kzFirstPhysical(out string) (uint64, error) { + for _, l := range strings.Split(out, "\n") { + if m := kzExtentRE.FindStringSubmatch(l); m != nil { + return strconv.ParseUint(m[1], 10, 64) + } + } + return 0, errors.New("no extent in filefrag output") +} + +// kzReserve marks the ports of addrs used, refusing one already taken: the +// target role reserves the data and ctrl ports the source's cluster spec +// names for it before it picks its own local ports. +func kzReserve(used map[int]bool, addrs ...string) error { + for _, a := range addrs { + _, p, err := net.SplitHostPort(a) + if err != nil { + return fmt.Errorf("address %q: %v", a, err) + } + n, err := strconv.Atoi(p) + if err != nil { + return fmt.Errorf("address %q: %v", a, err) + } + if used[n] { + return fmt.Errorf("port %d of %q is already taken", n, a) + } + used[n] = true + } + return nil +} + +func TestKnownZeroStep1Verdict(t *testing.T) { + lc := func(cand, staged, up int) *struct { + CandidateChunks, StagedChunks, UploadedChunks, ZeroedChunks, UnchangedChunks int + UploadedBytes int64 + } { + return &struct { + CandidateChunks, StagedChunks, UploadedChunks, ZeroedChunks, UnchangedChunks int + UploadedBytes int64 + }{CandidateChunks: cand, StagedChunks: staged, UploadedChunks: up} + } + cases := []struct { + name string + s kzStats + segs int + fresh bool + want bool + }{ + {"all-certified", kzStats{KnownZeroChunks: 256, LastCut: lc(0, 0, 0)}, 0, true, true}, + {"partial-certification", kzStats{KnownZeroChunks: 1, LastCut: lc(255, 0, 0)}, 0, true, false}, + {"partial-certification-no-candidates-shown", kzStats{KnownZeroChunks: 255, LastCut: lc(0, 0, 0)}, 0, true, false}, + {"full-zero-scan", kzStats{KnownZeroChunks: 0, LastCut: lc(256, 0, 0)}, 0, true, false}, + {"all-certified-but-scanned", kzStats{KnownZeroChunks: 256, LastCut: lc(3, 0, 0)}, 0, true, false}, + {"uploaded", kzStats{KnownZeroChunks: 256, LastCut: lc(0, 0, 1)}, 0, true, false}, + {"head-names-a-segment", kzStats{KnownZeroChunks: 256, LastCut: lc(0, 0, 0)}, 1, true, false}, + {"no-fresh-line", kzStats{KnownZeroChunks: 256, LastCut: lc(0, 0, 0)}, 0, false, false}, + {"no-last-cut", kzStats{KnownZeroChunks: 256}, 0, true, false}, + } + for _, c := range cases { + if got, why := kzStep1Pass(c.s, true, c.segs, 256, c.fresh); got != c.want { + t.Errorf("%s: got %v (%s), want %v", c.name, got, why, c.want) + } + } + if ok, _ := kzStep1Pass(kzStats{KnownZeroChunks: 256, LastCut: lc(0, 0, 0)}, false, 0, 256, true); ok { + t.Error("an incomplete s0 passed") + } +} + +func TestKnownZeroWriteCheck(t *testing.T) { + if err := kzCheckWrite([]byte("data"), nil, "aa", "aa"); err != nil { + t.Errorf("good write refused: %v", err) + } + if err := kzCheckWrite([]byte("data echoed by tee"), errors.New("exit status 1"), "aa", "aa"); err == nil { + t.Error("a failed write that produced output passed") + } + if err := kzCheckWrite(nil, nil, "aa", "bb"); err == nil { + t.Error("a short or wrong file (read-back sha256 differs) passed") + } +} + +func TestKnownZeroFirstPhysical(t *testing.T) { + ext4 := "Filesystem type is: ef53\nFile size of /m/kz-0.bin is 65536 (16 blocks of 4096 bytes)\n ext: logical_offset: physical_offset: length: expected: flags:\n 0: 0.. 15: 34816.. 34831: 16: last,eof\n/m/kz-0.bin: 1 extent found\n" + xfs := "Filesystem type is: 58465342\nFile size of /m/kz-1.bin is 131072 (32 blocks of 4096 bytes)\n ext: logical_offset: physical_offset: length: expected: flags:\n 0: 0.. 31: 24.. 55: 32: last,eof\n/m/kz-1.bin: 1 extent found\n" + for name, c := range map[string]struct { + out string + want uint64 + }{"ext4": {ext4, 34816}, "xfs": {xfs, 24}} { + got, err := kzFirstPhysical(c.out) + if err != nil || got != c.want { + t.Errorf("%s: got %d %v, want %d", name, got, err, c.want) + } + } + if _, err := kzFirstPhysical("Filesystem type is: ef53\n/m/x: 0 extents found\n"); err == nil { + t.Error("an empty file (no extent) gave a block") + } +} + +func TestKnownZeroImportedPortReservation(t *testing.T) { + used := map[int]bool{} + if err := kzReserve(used, "10.0.0.2:12001", "10.0.0.2:12002"); err != nil { + t.Fatalf("fresh ports refused: %v", err) + } + if err := kzReserve(used, "10.0.0.2:12002"); err == nil { + t.Error("a port collision with an imported address passed") + } + if err := kzReserve(used, "no-port"); err == nil { + t.Error("an address without a port passed") + } +} diff --git a/seaweed-block/cmd/blockvolume/known_zero_device_test.go b/seaweed-block/cmd/blockvolume/known_zero_device_test.go new file mode 100644 index 0000000000..4502a30ce0 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/known_zero_device_test.go @@ -0,0 +1,224 @@ +package main_test + +import ( + "fmt" + "io/fs" + "path" + "regexp" + "sort" + "strings" + "testing" + "testing/fstest" +) + +// kzDevice is the only way the KNOWN-ZERO acceptance test gets a block +// device path. It reads sysfs (the same source the CSI node uses) and returns +// /dev/ only when exactly one subsystem has subsysnqn == nqn (string +// equality, never a prefix), it has exactly one controller with transport tcp +// (and serial == serial when serial is not empty), and exactly one namespace. +// mkfs and mount take its result; a path given by name alone is never +// formatted. +type kzDevice struct { + Path, Ctrl, NQN, Serial string +} + +// Identity is the evidence line recorded before any mkfs. +func (d kzDevice) Identity() string { + s := d.Serial + if s == "" { + s = "-" + } + return fmt.Sprintf("DEVICE-IDENTITY nqn=%s serial=%s ctrl=%s transport=tcp namespace=%s match=exact", d.NQN, s, d.Ctrl, d.Path) +} + +var ( + kzCtrlName = regexp.MustCompile(`^nvme[0-9]+$`) + kzNSName = regexp.MustCompile(`^nvme[0-9]+n[0-9]+$`) +) + +// kzRead and kzNames return every read error: an unreadable entry is not +// an empty one, so a partial inventory can never look like exactly one device. +func kzRead(sys fs.FS, p string) (string, error) { + b, err := fs.ReadFile(sys, p) + if err != nil { + return "", fmt.Errorf("refused: incomplete sysfs inventory: %v", err) + } + return strings.TrimSpace(string(b)), nil +} + +func kzNames(sys fs.FS, dir string, re *regexp.Regexp) ([]string, error) { + ents, err := fs.ReadDir(sys, dir) + if err != nil { + return nil, fmt.Errorf("refused: incomplete sysfs inventory: %v", err) + } + var out []string + for _, e := range ents { + if re.MatchString(e.Name()) { + out = append(out, e.Name()) + } + } + return out, nil +} + +// kzResolve reads a sysfs class tree (/sys/class): nvme-subsystem/*/subsysnqn +// names the subsystem, its nvmeN entries are its controllers, and namespaces +// are nvmeXnY entries under the subsystem (native multipath) or under the +// controller (nvme//), whichever the kernel uses. +func kzResolve(sys fs.FS, nqn, serial string) (kzDevice, error) { + if !strings.HasPrefix(nqn, "nqn.") { + return kzDevice{}, fmt.Errorf("refused: %q is not an NQN (a device path is never accepted)", nqn) + } + // discovery lists the class directory itself (fs.Glob drops directory + // errors) and reads every subsystem's NQN; any failure refuses + ents, err := fs.ReadDir(sys, "nvme-subsystem") + if err != nil { + return kzDevice{}, fmt.Errorf("refused: incomplete sysfs inventory: %v", err) + } + var subs, hits []string + for _, e := range ents { + d := path.Join("nvme-subsystem", e.Name()) + subs = append(subs, d) + got, err := kzRead(sys, d+"/subsysnqn") + if err != nil { + return kzDevice{}, err + } + if got == nqn { + hits = append(hits, d) + } + } + if len(hits) != 1 { + return kzDevice{}, fmt.Errorf("refused: %d subsystems with NQN == %s (want exactly 1; %d subsystems seen)", len(hits), nqn, len(subs)) + } + dir := hits[0] + ctrls, err := kzNames(sys, dir, kzCtrlName) + if err != nil { + return kzDevice{}, err + } + if len(ctrls) != 1 { + return kzDevice{}, fmt.Errorf("refused: subsystem %s has %d controllers %v (want exactly 1)", nqn, len(ctrls), ctrls) + } + c := ctrls[0] + tr, err := kzRead(sys, "nvme/"+c+"/transport") + if err != nil { + return kzDevice{}, err + } + if tr != "tcp" { + return kzDevice{}, fmt.Errorf("refused: controller %s transport %q (want tcp)", c, tr) + } + got, err := kzRead(sys, "nvme/"+c+"/serial") + if err != nil { + return kzDevice{}, err + } + if serial != "" && got != serial { + return kzDevice{}, fmt.Errorf("refused: controller %s serial %q != %q", c, got, serial) + } + set := map[string]bool{} + for _, d := range []string{dir, "nvme/" + c} { + names, err := kzNames(sys, d, kzNSName) + if err != nil { + return kzDevice{}, err + } + for _, n := range names { + set[n] = true + } + } + if len(set) != 1 { + ns := make([]string, 0, len(set)) + for n := range set { + ns = append(ns, n) + } + sort.Strings(ns) + return kzDevice{}, fmt.Errorf("refused: subsystem %s has %d namespaces %v (want exactly 1)", nqn, len(set), ns) + } + var dev string + for n := range set { + dev = "/dev/" + n + } + return kzDevice{Path: dev, Ctrl: c, NQN: nqn, Serial: serial}, nil +} + +// kzSub adds one subsystem to a fake /sys/class tree. nsUnderSub puts the +// namespaces under the subsystem (native multipath), otherwise under the +// controller. +func kzSub(m fstest.MapFS, idx int, nqn, ctrl, transport, serial string, nsUnderSub bool, ns ...string) { + d := fmt.Sprintf("nvme-subsystem/nvme-subsys%d", idx) + m[d+"/subsysnqn"] = &fstest.MapFile{Data: []byte(nqn + "\n")} + m[d+"/"+ctrl] = &fstest.MapFile{Mode: fs.ModeDir} + m["nvme/"+ctrl+"/transport"] = &fstest.MapFile{Data: []byte(transport + "\n")} + m["nvme/"+ctrl+"/serial"] = &fstest.MapFile{Data: []byte(serial + " \n")} + for _, n := range ns { + if nsUnderSub { + m[d+"/"+n] = &fstest.MapFile{Mode: fs.ModeDir} + } else { + m["nvme/"+ctrl+"/"+n] = &fstest.MapFile{Mode: fs.ModeDir} + } + } +} + +func kzTree(f ...func(fstest.MapFS)) fstest.MapFS { + m := fstest.MapFS{} + for _, x := range f { + x(m) + } + return m +} + +// TestKnownZeroDeviceResolver: each refusal is the only check that can refuse +// its case (a real local disk, a longer or shorter NQN, duplicates, two +// controllers, two namespaces, a wrong serial, a path instead of an NQN). +func TestKnownZeroDeviceResolver(t *testing.T) { + const ours = "nqn.2026-11.io.seaweedfs:kz-r1-v1" + real := func(m fstest.MapFS) { + kzSub(m, 0, "nqn.2014.08.org.nvmexpress:uuid:real-disk", "nvme0", "pcie", "S1", false, "nvme0n1") + } + one := func(ns bool) func(fstest.MapFS) { + return func(m fstest.MapFS) { kzSub(m, 1, ours, "nvme1", "tcp", "SWB1", ns, "nvme1n1") } + } + cases := []struct { + name, nqn, serial string + sys fstest.MapFS + want, refusal string + }{ + {"exact-single-match-ns-under-subsystem", ours, "", kzTree(real, one(true)), "/dev/nvme1n1", ""}, + {"exact-single-match-ns-under-controller", ours, "", kzTree(real, one(false)), "/dev/nvme1n1", ""}, + {"serial-match", ours, "SWB1", kzTree(real, one(true)), "/dev/nvme1n1", ""}, + {"absent", ours, "", kzTree(real), "", "0 subsystems"}, + {"duplicate", ours, "", kzTree(func(m fstest.MapFS) { + kzSub(m, 1, ours, "nvme1", "tcp", "A", true, "nvme1n1") + kzSub(m, 2, ours, "nvme2", "tcp", "B", true, "nvme2n1") + }), "", "2 subsystems"}, + {"longer-nqn-not-ours", ours, "", kzTree(func(m fstest.MapFS) { kzSub(m, 1, ours+"-other", "nvme1", "tcp", "A", true, "nvme1n1") }), "", "0 subsystems"}, + {"shorter-nqn-not-ours", ours, "", kzTree(func(m fstest.MapFS) { + kzSub(m, 1, "nqn.2026-11.io.seaweedfs:kz-r1", "nvme1", "tcp", "A", true, "nvme1n1") + }), "", "0 subsystems"}, + {"pcie-real-disk", ours, "", kzTree(func(m fstest.MapFS) { kzSub(m, 0, ours, "nvme0", "pcie", "A", true, "nvme0n1") }), "", `transport "pcie"`}, + {"two-controllers", ours, "", kzTree(one(true), func(m fstest.MapFS) { + m["nvme-subsystem/nvme-subsys1/nvme3"] = &fstest.MapFile{Mode: fs.ModeDir} + }), "", "2 controllers"}, + {"two-namespaces", ours, "", kzTree(func(m fstest.MapFS) { kzSub(m, 1, ours, "nvme1", "tcp", "A", true, "nvme1n1", "nvme1n2") }), "", "2 namespaces"}, + {"no-namespace", ours, "", kzTree(func(m fstest.MapFS) { kzSub(m, 1, ours, "nvme1", "tcp", "A", true) }), "", "0 namespaces"}, + {"wrong-serial", ours, "SWB9", kzTree(one(true)), "", `serial "SWB1" != "SWB9"`}, + {"literal-path", "/dev/nvme1n1", "", kzTree(func(m fstest.MapFS) { kzSub(m, 1, "/dev/nvme1n1", "nvme1", "tcp", "A", true, "nvme1n1") }), "", "is not an NQN"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + d, err := kzResolve(c.sys, c.nqn, c.serial) + if c.refusal != "" { + if err == nil || !strings.Contains(err.Error(), c.refusal) { + t.Fatalf("want refusal containing %q, got path %q err %v", c.refusal, d.Path, err) + } + return + } + if err != nil || d.Path != c.want { + t.Fatalf("want %s, got %q err %v", c.want, d.Path, err) + } + }) + } + d, err := kzResolve(kzTree(one(true)), ours, "SWB1") + if err != nil { + t.Fatal(err) + } + if got, want := d.Identity(), "DEVICE-IDENTITY nqn="+ours+" serial=SWB1 ctrl=nvme1 transport=tcp namespace=/dev/nvme1n1 match=exact"; got != want { + t.Fatalf("identity line\n got %s\nwant %s", got, want) + } +} diff --git a/seaweed-block/cmd/blockvolume/known_zero_partial_inventory_test.go b/seaweed-block/cmd/blockvolume/known_zero_partial_inventory_test.go new file mode 100644 index 0000000000..f73c01a6bf --- /dev/null +++ b/seaweed-block/cmd/blockvolume/known_zero_partial_inventory_test.go @@ -0,0 +1,74 @@ +package main_test + +import ( + "io/fs" + "strings" + "testing" + "testing/fstest" +) + +type kzFaultFS struct { + tree fstest.MapFS + denyDir, denyFile string +} + +func (s kzFaultFS) Open(name string) (fs.File, error) { return s.tree.Open(name) } + +func (s kzFaultFS) ReadDir(name string) ([]fs.DirEntry, error) { + if name == s.denyDir { + return nil, fs.ErrPermission + } + return s.tree.ReadDir(name) +} + +func (s kzFaultFS) ReadFile(name string) ([]byte, error) { + if name == s.denyFile { + return nil, fs.ErrPermission + } + return s.tree.ReadFile(name) +} + +func TestKnownZeroPartialNamespaceInventoryMustRefuse(t *testing.T) { + const nqn = "nqn.2026-11.io.seaweedfs:kz-review" + m := kzTree(func(m fstest.MapFS) { + kzSub(m, 1, nqn, "nvme1", "tcp", "S1", true, "nvme1n1") + m["nvme/nvme1/nvme1n2"] = &fstest.MapFile{Mode: fs.ModeDir} + }) + if _, err := kzResolve(m, nqn, ""); err == nil || !strings.Contains(err.Error(), "2 namespaces") { + t.Fatalf("complete inventory control must refuse two namespaces: %v", err) + } + d, err := kzResolve(kzFaultFS{tree: m, denyDir: "nvme/nvme1"}, nqn, "") + if err == nil { + t.Fatalf("partial inventory accepted %s; unreadable controller namespace listing is not an empty listing", d.Path) + } +} + +func TestKnownZeroUnreadableMatchingSubsystemMustRefuse(t *testing.T) { + const nqn = "nqn.2026-11.io.seaweedfs:kz-review" + m := kzTree(func(m fstest.MapFS) { + kzSub(m, 1, nqn, "nvme1", "tcp", "S1", true, "nvme1n1") + kzSub(m, 2, nqn, "nvme2", "tcp", "S2", true, "nvme2n1") + }) + if _, err := kzResolve(m, nqn, ""); err == nil || !strings.Contains(err.Error(), "2 subsystems") { + t.Fatalf("complete inventory control must refuse two subsystems: %v", err) + } + d, err := kzResolve(kzFaultFS{tree: m, denyFile: "nvme-subsystem/nvme-subsys2/subsysnqn"}, nqn, "") + if err == nil { + t.Fatalf("partial inventory accepted %s; unreadable subsystem identity is not proof of no match", d.Path) + } +} + +func TestKnownZeroGlobSuppressedInventoryErrorMustRefuse(t *testing.T) { + const nqn = "nqn.2026-11.io.seaweedfs:kz-review" + m := kzTree(func(m fstest.MapFS) { + kzSub(m, 1, nqn, "nvme1", "tcp", "S1", true, "nvme1n1") + kzSub(m, 2, nqn, "nvme2", "tcp", "S2", true, "nvme2n1") + }) + if _, err := kzResolve(m, nqn, ""); err == nil || !strings.Contains(err.Error(), "2 subsystems") { + t.Fatalf("complete inventory control must refuse two subsystems: %v", err) + } + d, err := kzResolve(kzFaultFS{tree: m, denyDir: "nvme-subsystem/nvme-subsys2"}, nqn, "") + if err == nil { + t.Fatalf("partial discovery accepted %s; fs.Glob hid a directory error", d.Path) + } +} diff --git a/seaweed-block/cmd/blockvolume/kzhold_release_symbols_test.go b/seaweed-block/cmd/blockvolume/kzhold_release_symbols_test.go new file mode 100644 index 0000000000..a33e8d4fba --- /dev/null +++ b/seaweed-block/cmd/blockvolume/kzhold_release_symbols_test.go @@ -0,0 +1,38 @@ +package main_test + +import ( + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// TestKZHoldNeverInReleaseBuild: the kzhold hold (a test-only stop before the +// fresh marker is retired) exists only in a binary built with -tags kzhold. +// A normal build of blockvolume must contain no symbol of it; the kzhold build +// must (the positive control: a check that finds nothing in either build would +// prove nothing). +func TestKZHoldNeverInReleaseBuild(t *testing.T) { + dir := t.TempDir() + syms := func(name string, tags ...string) string { + t.Helper() + out := filepath.Join(dir, name) + args := append([]string{"build"}, tags...) + args = append(args, "-o", out, "github.com/seaweedfs/seaweed-block/cmd/blockvolume") + if b, err := exec.Command("go", args...).CombinedOutput(); err != nil { + t.Fatalf("go %s: %v\n%s", strings.Join(args, " "), err, b) + } + b, err := exec.Command("go", "tool", "nm", out).CombinedOutput() + if err != nil { + t.Fatalf("go tool nm %s: %v\n%s", out, err, b) + } + return string(b) + } + const hold = "HoldBeforeChunkFreshRetireForTest" + if s := syms("release"); strings.Contains(s, hold) || strings.Contains(strings.ToLower(s), "kzhold") { + t.Fatalf("a normal build of blockvolume contains the test-only kzhold hold") + } + if s := syms("kzhold", "-tags", "kzhold"); !strings.Contains(s, hold) { + t.Fatalf("the kzhold build lacks %s: this check would pass blindly", hold) + } +} diff --git a/seaweed-block/cmd/blockvolume/layout_id_refusal_test.go b/seaweed-block/cmd/blockvolume/layout_id_refusal_test.go new file mode 100644 index 0000000000..429a582825 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/layout_id_refusal_test.go @@ -0,0 +1,156 @@ +package main + +import ( + "bytes" + "context" + "errors" + "go/ast" + "go/parser" + "go/token" + "path" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// The directory suffix is only id8: the full master id must match both records. +func TestLayoutIDMismatchIsTypedAndExits78(t *testing.T) { + for _, record := range []string{"VOLUME", "HEAD"} { + t.Run(record, func(t *testing.T) { + ctx := context.Background() + actual, _ := layout.ParseVolumeID("1234567890abcdef1234567890abcdef") + wrong, _ := layout.ParseVolumeID("1234567890abcdef1234567890abcdee") + f := &layoutAttachFiler{MemFiler: chunkstore.NewMemFiler()} + cat, err := chunkstore.NewBCatalog(f, f, "/identity") + if err != nil { + t.Fatal(err) + } + launch, err := parseFlags(append(phase150RequiredBlockvolumeArgs(), "--volume-id=v", "--durable-root="+t.TempDir(), "--layout-id="+actual.String())) + if err != nil { + t.Fatal(err) + } + supplied, err := layout.ParseVolumeID(launch.layoutID) + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: launch.volumeID, ID: supplied} + foreign := chunkstore.VolumeRef{Name: "v", ID: wrong} + if ref.Dir() != foreign.Dir() { + t.Fatal("fixture needs an id8 collision") + } + geometry := layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096} + if _, err := cat.CreateVolume(ctx, ref, geometry); err != nil { + t.Fatal(err) + } + // Leave the other record correct to prove each boundary independently. + entry, err := f.LookupEntry(ctx, path.Join("/identity", ref.Dir()), record) + if err != nil { + t.Fatal(err) + } + if record == "VOLUME" { + entry.Content, err = (layout.Volume{ID: wrong, Name: "v", Format: layout.VolumeFormat, Geometry: geometry}).Encode() + } else { + entry.Content, err = layout.Unclaimed(wrong, nil).Encode() + entry.Extended["swb.layout.volume"] = []byte(wrong.String()) + } + if err != nil { + t.Fatal(err) + } + if err := f.UpdateEntry(ctx, path.Join("/identity", ref.Dir()), entry, nil); err != nil { + t.Fatal(err) + } + g := durable.ChunkGeometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4} + if err := chunkAttachCheck(cat, ref)(ctx, "v", g); !errors.Is(err, layout.ErrIdentity) { + t.Errorf("%s mismatch attach check = %v; want typed ErrIdentity", record, err) + } + if record == "VOLUME" { + if _, code := geometryFlagsRefusal(ctx, cat, ref, 64, 4096, 4); code != 78 { + t.Errorf("pre-open refusal exit = %d, want 78", code) + } + } + before, err := f.LookupEntry(ctx, path.Join("/identity", ref.Dir()), "HEAD") + if err != nil { + t.Fatal(err) + } + st, _ := cat.Store(ref) + view := &claimExitView{} + view.assigned.Store(true) + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r", + ChunkAttachCheck: chunkAttachCheck(cat, ref), + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return st, nil }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, ref, me) + }, + }, view) + if err != nil { + t.Fatal(err) + } + defer p.Close() + if _, err := p.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(ctx, "v"); !errors.Is(err, layout.ErrIdentity) { + t.Fatalf("recover = %v, want ErrIdentity", err) + } + h, _ := exitAuthorityHost(t) + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) { + t.Fatal("identity refusal did not terminate startup") + } + if out := <-e.decision; out.code != 78 || out.reason != "layout_identity_mismatch" { + t.Fatalf("identity refusal exit = %+v", out) + } + gen, ended := p.ChunkStartupOutcome("v") + if !ended || p.ChunkStartupIdentityRefused("v", gen+1) { + t.Fatal("identity refusal escaped its recovery generation") + } + after, err := f.LookupEntry(ctx, path.Join("/identity", ref.Dir()), "HEAD") + if err != nil || !bytes.Equal(after.Content, before.Content) { + t.Fatal("refusal changed HEAD", err) + } + + }) + } +} + +// This latched refusal has one decision writer and one reset for a new recovery. +// A new reader/writer must be reviewed together with the recovery-generation gate. +func TestLayoutIdentityStartupSitesAreEnumerated(t *testing.T) { + files, err := filepath.Glob("../../core/frontend/durable/*.go") + if err != nil { + t.Fatal(err) + } + got := map[string]int{} + for _, name := range files { + if strings.HasSuffix(name, "_test.go") { + continue + } + f, err := parser.ParseFile(token.NewFileSet(), name, nil, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range f.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + if s, ok := n.(*ast.SelectorExpr); ok && s.Sel.Name == "startupIdentityRefused" { + got[filepath.Base(name)+":"+fn.Name.Name]++ + } + return true + }) + } + } + want := map[string]int{"provider.go:RecoverVolume": 1, "provider_startup.go:endChunkStartup": 1, "provider_startup.go:ChunkStartupIdentityRefused": 1} + if !reflect.DeepEqual(got, want) { + t.Fatalf("identity refusal sites = %v, want %v", got, want) + } +} diff --git a/seaweed-block/cmd/blockvolume/layout_identity_test.go b/seaweed-block/cmd/blockvolume/layout_identity_test.go new file mode 100644 index 0000000000..e011b481ed --- /dev/null +++ b/seaweed-block/cmd/blockvolume/layout_identity_test.go @@ -0,0 +1,24 @@ +package main + +import ( + "path/filepath" + "testing" +) + +func TestBlockvolumeLayoutIdentitySelectsTheLocalRoot(t *testing.T) { + base := []string{"--master=127.0.0.1:9333", "--server-id=s1", "--volume-id=v", "--replica-id=r1", "--data-addr=127.0.0.1:19101", "--ctrl-addr=127.0.0.1:19102", "--durable-root=" + t.TempDir()} + first, err := parseFlags(append(append([]string{}, base...), "--layout-id=1234567890abcdef1234567890abcdef")) + if err != nil { + t.Fatal(err) + } + if filepath.Base(first.durableRoot) != "v-12345678" { + t.Fatal(first.durableRoot) + } + second, err := parseFlags(append(append([]string{}, base...), "--layout-id=abcdef1290abcdef1234567890abcdef")) + if err != nil || second.durableRoot == first.durableRoot { + t.Fatalf("different incarnation reused local root: %v", err) + } + if _, err := parseFlags(append(append([]string{}, base...), "--layout-id=bad")); err == nil { + t.Fatal("malformed identity accepted") + } +} diff --git a/seaweed-block/cmd/blockvolume/layout_master_fixture_test.go b/seaweed-block/cmd/blockvolume/layout_master_fixture_test.go new file mode 100644 index 0000000000..28973b1e8a --- /dev/null +++ b/seaweed-block/cmd/blockvolume/layout_master_fixture_test.go @@ -0,0 +1,68 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +// layoutMasterWriter gives an in-process master the layout writer a +// production master gets from --chunk-filer: CreateVolume writes the VOLUME +// and the unclaimed HEAD under base on the test filer before the record is +// store-ready. +func layoutMasterWriter(t *testing.T, cluster *w4WeedCluster, base string) func(context.Context, lifecycle.VolumeSpec) error { + t.Helper() + cat, client, err := chunkstore.DialBCatalog(context.Background(), chunkstore.SWFSConfig{FilerGRPC: cluster.filerGRPC, AssignPath: base}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { client.Close() }) + return func(ctx context.Context, spec lifecycle.VolumeSpec) error { + id, err := layout.ParseVolumeID(spec.LayoutID) + if err != nil { + return err + } + _, err = cat.CreateVolume(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}, layout.Geometry{ + SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes}) + return err + } +} + +// createStoreReadyVolume creates a volume through the master's public create, +// the path production uses, and requires the record to come back store-ready. +func createStoreReadyVolume(t *testing.T, h *master.Host, volume string, sizeBytes uint64) layout.VolumeID { + t.Helper() + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + resp, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: volume, SizeBytes: sizeBytes, ReplicationFactor: 1}) + if err != nil { + t.Fatalf("create %s through the master: %v", volume, err) + } + if !resp.GetStoreReady() { + t.Fatalf("create %s: the master answered store_ready=false", volume) + } + id, err := layout.ParseVolumeID(resp.GetLayoutId()) + if err != nil { + t.Fatalf("master-minted layout id %q: %v", resp.GetLayoutId(), err) + } + if rec, ok := h.Lifecycle().Volumes.GetVolume(volume); !ok || !rec.StoreReady { + t.Fatal(fmt.Sprintf("lifecycle record of %s is not store-ready after the create", volume)) + } + return id +} diff --git a/seaweed-block/cmd/blockvolume/lines_name_their_process_test.go b/seaweed-block/cmd/blockvolume/lines_name_their_process_test.go new file mode 100644 index 0000000000..6184f44f65 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/lines_name_their_process_test.go @@ -0,0 +1,14 @@ +package main + +import "testing" + +// The volume this command runs adopts no primary line that names no +// process: the master stamps every line with the process it was issued +// for, and an unnamed one is re-issued for this process on its first +// report. Off, a restarted process could take an unnamed line and reuse a +// dead process's sessions. +func TestHostConfigAdoptsOnlyLinesNamingThisProcess(t *testing.T) { + if !hostConfig(flags{}, nil).LinesNameTheirProcess { + t.Fatal("the shipping command adopts primary lines that name no process") + } +} diff --git a/seaweed-block/cmd/blockvolume/log_level_test.go b/seaweed-block/cmd/blockvolume/log_level_test.go new file mode 100644 index 0000000000..772c954a29 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/log_level_test.go @@ -0,0 +1,15 @@ +package main + +import "testing" + +func TestLogLevelFlag(t *testing.T) { + for _, level := range []string{"info", "debug"} { + f, err := parseFlags([]string{"--version", "--log-level=" + level}) + if err != nil || f.logLevel != level { + t.Fatalf("%s: flags=%+v error=%v", level, f, err) + } + } + if _, err := parseFlags([]string{"--version", "--log-level=quiet"}); err == nil { + t.Fatal("invalid log level accepted") + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go new file mode 100644 index 0000000000..26991e2a2e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/main.go @@ -0,0 +1,1772 @@ +// Command blockvolume is the block volume daemon — the product +// host for per-volume observation reporting and assignment +// subscription. +package main + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "log" + "math" + "net" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/iscsi" + "github.com/seaweedfs/seaweed-block/core/frontend/memback" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/frontend/nvmerdma" + "github.com/seaweedfs/seaweed-block/core/frontend/ublk" + "github.com/seaweedfs/seaweed-block/core/geometry" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "github.com/seaweedfs/seaweed-block/core/recovery" + "github.com/seaweedfs/seaweed-block/core/replication" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/storeident" + "github.com/seaweedfs/seaweed-block/core/transport" + "github.com/seaweedfs/seaweed-block/internal/buildinfo" + "github.com/seaweedfs/seaweed-block/internal/logging" +) + +type flags struct { + walHold frontend.WALHoldConfig + logLevel string + cpuProfileDir string + memoryLimitMiB int64 + masterAddr string + serverID string + volumeID string + layoutID string + replicaID string + dataAddr string + ctrlAddr string + hbInterval time.Duration + workspaceLease bool + // recoverTimeout: #128 rule 6 recovery watchdog. + recoverTimeout time.Duration + // printReadyLine: test-only flag — emits one structured JSON + // line to stdout on the FIRST received assignment with + // Epoch > 0. L2 subprocess smoke uses this to assert route + // closure. + printReadyLine bool + + // T1 closure-loop flags: enable the minimum readiness bridge + // (HealthyPathExecutor) and expose a status HTTP endpoint. + // statusAddr ":0" is for tests — the process prints the bound + // addr on the ready line so the test harness can discover it. + enableT1Readiness bool + statusAddr string + // statusRecovery — opt-in: enable /status/recovery?volume=v1 + // endpoint exposing engine.ReplicaProjection (Mode/R/S/H/Decision). + // Default off; production binaries do NOT enable. Used by hardware + // orchestration scripts for catch-up verification (R/H polling). + statusRecovery bool + // External status bind is off by default. Node-loss gates opt in so + // blockmaster can probe surviving replicas across Kubernetes nodes. + allowExternalStatusBind bool + masterTLS link.TLSFiles // the master link's mutual TLS (phase 0) + runtimeRebuildEndpoint bool + + // iSCSI frontend flags. iscsiListen is the TCP address the iSCSI + // target binds on; empty disables the frontend. The safe default + // rejects non-loopback binds. Node-loss gates must opt into + // external bind and provide CHAP. + iscsiListen string + iscsiIQN string + iscsiPortalAddr string + iscsiDataOutTTL time.Duration + iscsiLUN uint + iscsiCHAPUser string + iscsiCHAPSecret string + allowExternalISCSIBind bool + + // NVMe frontend flags. Symmetric with iSCSI flags: same + // loopback-only safe-default rule, same auto-enable of + // --t1-readiness so the symmetry stays clean. + nvmeListen string + nvmeSubsysNQN string + nvmeNS uint + nvmeTransport string + nvmeMaxH2C uint + // External NVMe bind is explicit because the current target has no + // authentication. Phase 106 uses it for controlled Kubernetes cross-node + // gates; default installs remain loopback-only. + allowExternalNVMeBind bool + + // ublk frontend: serve the volume as the local block device + // /dev/ublkbN (Linux ublk_drv, root). -1 disables. + ublkDevice int + ublkQueues int + ublkQueueDepth int + + // Durable-backend flags. When --durable-root is set, the iSCSI + // and NVMe providers use DurableProvider instead of memback. + // --durable-impl selects walstore or walstore-chunk. Empty (default) = + // auto: an existing volume opens with its on-disk format, a new one is + // walstore. The removed experimental engines' names are refused typed. + // --durable-blocks + --durable-blocksize are used on first-time + // storage create. + durableRoot string + durableImpl string // "" (auto) | "walstore" | "walstore-chunk" + // --chunk-*: the SeaweedFS remote of --durable-impl=walstore-chunk. + chunk chunkFlags + durableBlocks uint + durableBlockSize uint + durableWALMultiBlockRecords bool + durableWALRecoveryTestDisableFlusher bool + // volumeLockDirTestOnly replaces durable.HostVolumeLockDir (hidden, + // test-only; refused under systemd). + volumeLockDirTestOnly string + + // WAL retention window past checkpoint LSN. Zero = strict + // checkpoint-driven recycle. Non-zero = walstore relaxes the + // recovery-scan recycle gate to fromLSN > checkpointLSN - + // walRetentionLSNs, giving a slow replica room to catch up while + // it lags within the window. Substrate semantics differ: see + // ProviderConfig.WALRetentionLSNs godoc. + walRetentionLSNs uint64 + + // Degraded-peer probe loop (primary-side runtime recovery trigger). + // Off by default; --degraded-probe-interval=0 keeps the loop + // disabled. When enabled (interval > 0), the loop iterates over + // peers in ReplicaDegraded at the given interval and dispatches + // an engine-ingress probe per peer (with per-peer cooldown). + degradedProbeInterval time.Duration + degradedProbeCooldownBase time.Duration + degradedProbeCooldownCap time.Duration + + // Recovery mode selector. "legacy" (default) keeps the single-lane + // core/transport rebuild path. "dual-lane" routes StartRebuild + // through core/recovery's PrimaryBridge, binding a separate + // listener at port=data-addr-port+1. + // + // Default flip from legacy → dual-lane is a separate operations + // change after dual-lane is GREEN in CI / hardware. + recoveryMode string + + // Replication acknowledgement profile. best-effort is the beta + // default. sync-quorum / sync-all opt into foreground write ACK + // gating through the durable WriteObserver seam. + replicationAck string + version bool + + // memoryLimitFallback says why the default soft memory limit is in + // force instead of a cgroup-derived one: the derivation's error. Empty + // when a limit was derived, given, or not needed. + memoryLimitFallback string +} + +// volumeLockDirTestOnlyFlag is hidden from --help (printVisibleUsage). +const volumeLockDirTestOnlyFlag = "volume-lock-dir-test-only" + +// printVisibleUsage is the default usage without the hidden test flag. +func printVisibleUsage(fs *flag.FlagSet) { + visible := flag.NewFlagSet(fs.Name(), flag.ContinueOnError) + visible.SetOutput(fs.Output()) + fs.VisitAll(func(fl *flag.Flag) { + if fl.Name != volumeLockDirTestOnlyFlag { + visible.Var(fl.Value, fl.Name, fl.Usage) + } + }) + fmt.Fprintf(fs.Output(), "Usage of %s:\n", fs.Name()) + visible.PrintDefaults() +} + +func parseFlags(args []string) (flags, error) { + return parseFlagsWithCgroup(args, os.ReadFile) +} + +func parseFlagsWithCgroup(args []string, readFile func(string) ([]byte, error)) (flags, error) { + var f flags + fs := flag.NewFlagSet("blockvolume", flag.ContinueOnError) + writePolicy := frontend.DefaultWALHoldConfig() + fs.DurationVar(&f.walHold.MaxHold, "wal-hold-timeout", writePolicy.MaxHold, "maximum per-command WAL-pressure hold; positive and at least 5s below --host-io-timeout") + fs.DurationVar(&f.walHold.HostIOTimeout, "host-io-timeout", writePolicy.HostIOTimeout, "operator-declared host I/O timeout (host_io_timeout); set to match your hosts when changing io_timeout") + fs.StringVar(&f.logLevel, "log-level", "info", "log verbosity: info or debug; timestamps are UTC with microseconds") + fs.Int64Var(&f.memoryLimitMiB, "memory-limit-mib", 4*storage.DefaultCutPayloadMemoryBudget/(1<<20), "process Go soft memory limit in MiB; unset: 90% of the effective cgroup v2 memory.max, or 256 MiB without a limit or when it cannot be derived (one WARN says why); 0 preserves GOMEMLIMIT; explicit GOMEMLIMIT is preserved unless this flag is set") + fs.StringVar(&f.masterAddr, "master", "", "master gRPC address (required)") + fs.StringVar(&f.serverID, "server-id", "", "this server identity (required)") + fs.StringVar(&f.masterTLS.Cert, "master-tls-cert", "", "this node's certificate (PEM) for mutual TLS to blockmaster; its CN must equal --server-id") + fs.StringVar(&f.masterTLS.Key, "master-tls-key", "", "the key of --master-tls-cert (PEM)") + fs.StringVar(&f.masterTLS.CA, "master-ca", "", "CA (PEM) blockmaster's certificate must verify against") + fs.StringVar(&f.volumeID, "volume-id", "", "served volume (required)") + fs.StringVar(&f.layoutID, "layout-id", "", "master-minted layout identity; when set, durable-root is the base for -") + fs.StringVar(&f.replicaID, "replica-id", "", "served replica (required)") + fs.StringVar(&f.dataAddr, "data-addr", "", "data-path address (required)") + fs.StringVar(&f.ctrlAddr, "ctrl-addr", "", "control-path address (required)") + fs.DurationVar(&f.hbInterval, "heartbeat-interval", 2*time.Second, "heartbeat send interval") + fs.DurationVar(&f.recoverTimeout, "recover-timeout", volume.DefaultRecoverTimeout, "maximum inactivity without new completed recovery or attach work for a primary-assigned replica before it reports unhealthy (recovery_stalled); a wait for master authority pauses it; not a total startup deadline") + fs.BoolVar(&f.workspaceLease, "workspace-lease", false, "required for walstore-chunk: require host-owned master lease; fail closed when unavailable") + fs.BoolVar(&f.printReadyLine, "t0-print-ready", false, "internal test-only: emit one structured JSON line on stdout on first assignment") + fs.BoolVar(&f.enableT1Readiness, "t1-readiness", false, "enable readiness bridge (HealthyPathExecutor) so adapter projection reaches Healthy") + fs.StringVar(&f.statusAddr, "status-addr", "", "address for the status HTTP endpoint (e.g. 127.0.0.1:0); empty disables") + fs.StringVar(&f.cpuProfileDir, "cpu-profile-dir", os.Getenv(cpuProfileEnv), "diagnostics: an existing directory; SIGUSR1 then toggles a CPU profile written there (default $"+cpuProfileEnv+"; empty disables)") + fs.BoolVar(&f.statusRecovery, "status-recovery", false, "expose /status/recovery?volume= with engine.ReplicaProjection (Mode/R/S/H/RecoveryDecision); off by default; loopback-only; intended for hardware test orchestration") + fs.BoolVar(&f.allowExternalStatusBind, "allow-external-status-bind", false, "allow the unauthenticated status endpoint to bind and serve non-loopback addresses; intended only for explicit Kubernetes node-loss gates") + fs.BoolVar(&f.runtimeRebuildEndpoint, "runtime-rebuild-endpoint", false, "expose POST /runtime/rebuild on the status HTTP listener; off by default; starts primary-side rebuild/catch-up traffic only after request lineage validation") + fs.StringVar(&f.iscsiListen, "iscsi-listen", "", "iSCSI target bind address (e.g. 127.0.0.1:0); empty disables. Loopback-only unless paired with an operator-managed proxy") + fs.StringVar(&f.iscsiIQN, "iscsi-iqn", "", "iSCSI target IQN (required if --iscsi-listen is set)") + fs.StringVar(&f.iscsiPortalAddr, "iscsi-portal-addr", "", "iSCSI TargetAddress advertised in SendTargets responses (e.g. 203.0.113.10:3260,1). Defaults to the bound listen address. Does not change the loopback-only bind policy") + fs.DurationVar(&f.iscsiDataOutTTL, "iscsi-dataout-timeout", 0, "iSCSI R2T/Data-Out wait timeout. 0 uses the target default. Bounds how long a session waits for solicited Data-Out from an initiator") + fs.UintVar(&f.iscsiLUN, "iscsi-lun", 0, "iSCSI LUN id (default 0)") + fs.StringVar(&f.iscsiCHAPUser, "iscsi-chap-username", "", "iSCSI target-side CHAP username. Requires --iscsi-chap-secret and --iscsi-listen") + fs.StringVar(&f.iscsiCHAPSecret, "iscsi-chap-secret", "", "iSCSI target-side CHAP secret. Requires --iscsi-chap-username and --iscsi-listen") + fs.BoolVar(&f.allowExternalISCSIBind, "allow-external-iscsi-bind", false, "allow iSCSI to bind a non-loopback address; requires CHAP and is intended for explicit Kubernetes node-loss gates") + fs.StringVar(&f.nvmeListen, "nvme-listen", "", "NVMe/TCP target bind address (e.g. 127.0.0.1:0); empty disables. Loopback-only (no auth)") + fs.StringVar(&f.nvmeSubsysNQN, "nvme-subsysnqn", "", "NVMe subsystem NQN (required if --nvme-listen is set)") + fs.UintVar(&f.nvmeNS, "nvme-ns", 1, "NVMe namespace id (default 1)") + fs.StringVar(&f.nvmeTransport, "nvme-transport", "tcp", "NVMe-oF transport: tcp or the explicit Linux-only standalone rdma target") + fs.UintVar(&f.nvmeMaxH2C, "nvme-max-h2c-data-length", 0, "NVMe/TCP MaxH2CDataLength in bytes. 0 preserves the target default") + fs.BoolVar(&f.allowExternalNVMeBind, "allow-external-nvme-bind", false, "allow NVMe to bind a non-loopback address; unauthenticated, intended only for explicit gates") + fs.IntVar(&f.ublkDevice, "ublk-device", -1, "serve the volume as the local block device /dev/ublkbN (Linux ublk_drv, root); -1 disables. Same-host alternative to the NVMe/TCP loopback") + fs.IntVar(&f.ublkQueues, "ublk-queues", 0, "ublk hardware queues (one server thread each); 0 = default 1. Requires --ublk-device") + fs.IntVar(&f.ublkQueueDepth, "ublk-queue-depth", 0, "ublk in-flight requests per queue; 0 = default 64. Requires --ublk-device") + fs.StringVar(&f.durableRoot, "durable-root", "", "directory for persistent storage files; empty = memback (non-durable)") + fs.StringVar(&f.durableImpl, "durable-impl", "", "LogicalStorage impl: empty (default) = auto: an existing volume opens with its on-disk format (a walstore-chunk root needs the explicit walstore-chunk selector), a new volume is created as walstore; or walstore, or opt-in walstore-chunk (walstore published to SeaweedFS; proof of concept); ignored unless --durable-root is set") + registerHostLimitFlags(fs, &f.chunk.hostLimit) + chunkstore.RegisterSWFSFlags(fs, &f.chunk.filer, &f.chunk.path, &f.chunk.collection, &f.chunk.replication) + fs.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)") + fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: not supported in this release; blockvolume refuses to start when it is set") + fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least "+durable.MinCaptureInterval.String()+")") + f.chunk.snapshotSchedule = defaultSnapshotSchedule + fs.Var(&f.chunk.snapshotSchedule, "chunk-snapshot-schedule", "walstore-chunk: scheduled snapshots, daily:N or weekly:N (once per period at a per-volume offset, the newest N kept) or off") + fs.DurationVar(&f.chunk.maintenanceInterval, "chunk-maintenance-interval", defaultChunkMaintenanceInterval, "walstore-chunk: interval of the holder's maintenance pass (retention, then the cleaning); 0 disables the whole pass") + fs.BoolVar(&f.chunk.automaticGC, "chunk-maintenance-gc", defaultChunkMaintenanceGC, "walstore-chunk: the holder's maintenance pass removes chunks no root of the volume reaches (cleaning), every --chunk-maintenance-interval and after each snapshot delete; on by default, =false turns the cleaning off") + fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)") + fs.IntVar(&f.chunk.hydrationWorkers, "chunk-hydration-workers", 2, "walstore-chunk: concurrent lazy chunk fetches per volume (1..64)") + fs.IntVar(&f.chunk.hydrationQueueDepth, "chunk-hydration-queue-depth", 64, "walstore-chunk: distinct queued/in-flight hydration chunks per volume (1..65536)") + fs.BoolVar(&f.chunk.controlEndpoint, "chunk-control-endpoint", false, "walstore-chunk: expose the /chunk/* control routes (cut, snapshot, snapshots, snapshot/delete, detach) on the status HTTP listener; off by default; loopback-only like the listener") + fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)") + fs.UintVar(&f.durableBlockSize, "durable-blocksize", 4096, "block size in bytes on first create") + fs.BoolVar(&f.durableWALMultiBlockRecords, "durable-wal-multiblock-records", false, "enable experimental walstore multi-block WAL records; default false; requires --durable-impl=walstore") + fs.BoolVar(&f.durableWALRecoveryTestDisableFlusher, "durable-wal-recovery-test-disable-flusher", false, "test-only: stop walstore's automatic WAL checkpoint flusher so recovery gates can prove WAL replay; default false; requires --durable-root and --durable-impl=walstore") + fs.Uint64Var(&f.walRetentionLSNs, "wal-retention-lsns", 0, + "WAL retention window past checkpoint LSN (walstore only). "+ + "Zero (default) preserves strict checkpoint-driven recycle. "+ + "Non-zero relaxes the recovery-scan recycle gate so a replica lagging "+ + "within the configured envelope still has a catch-up scan path; once a "+ + "replica falls past this window the engine escalates to rebuild. "+ + "Recommended starting value for sustained-write "+ + "workloads on walstore: 10000 LSNs (sized to expected replica lag).") + fs.DurationVar(&f.degradedProbeInterval, "degraded-probe-interval", 5*time.Second, + "primary-side degraded-peer probe loop interval; 0 = OFF. "+ + "On by default: a replica that fell out of the volume rejoins without an operator. Distinct from --degraded-probe-cooldown-base: this is how often "+ + "the loop wakes up; cooldown-base is how long a single peer is gated AFTER a probe attempt.") + fs.DurationVar(&f.degradedProbeCooldownBase, "degraded-probe-cooldown-base", 5*time.Second, + "per-peer cooldown after a probe attempt (also the reset value after a successful probe). "+ + "Doubled on consecutive failures up to --degraded-probe-cooldown-cap. "+ + "Ignored when --degraded-probe-interval=0.") + fs.DurationVar(&f.degradedProbeCooldownCap, "degraded-probe-cooldown-cap", 60*time.Second, + "per-peer cooldown ceiling for the consecutive-failure backoff. "+ + "Must be >= --degraded-probe-cooldown-base; values below base are normalized up to base. "+ + "Ignored when --degraded-probe-interval=0.") + fs.StringVar(&f.recoveryMode, "recovery-mode", "legacy", + "recovery path. \"legacy\" (default) = single-lane "+ + "core/transport rebuild. \"dual-lane\" = core/recovery PrimaryBridge "+ + "with separate listener at data-addr port+1. Default flip is a "+ + "separate change after dual-lane is GREEN in CI/hardware.") + fs.StringVar(&f.replicationAck, "replication-ack", "best-effort", + "replication acknowledgement profile: \"best-effort\" (default), \"sync-quorum\", or \"sync-all\". "+ + "sync-* modes fail foreground writes when required replica acknowledgement is unavailable.") + fs.BoolVar(&f.version, "version", false, "print build provenance and exit") + fs.StringVar(&f.volumeLockDirTestOnly, volumeLockDirTestOnlyFlag, "", "") + fs.SetOutput(os.Stderr) + fs.Usage = func() { printVisibleUsage(fs) } + if err := fs.Parse(args); err != nil { + return flags{}, err + } + if err := f.walHold.Validate(); err != nil { + return flags{}, err + } + if err := logging.ValidateLevel(f.logLevel); err != nil { + return flags{}, err + } + memoryFlagSet := false + fs.Visit(func(fl *flag.Flag) { + if fl.Name == "memory-limit-mib" { + memoryFlagSet = true + } + }) + if !memoryFlagSet && os.Getenv("GOMEMLIMIT") != "" { + f.memoryLimitMiB = 0 + } else if !memoryFlagSet && !f.version { + // An underivable cgroup limit is the no-limit case: the default stays + // in force and applyMemoryLimit warns why. Only an explicit limit + // (the flag, or GOMEMLIMIT read by the runtime) may refuse. + limit, err := cgroupMemoryLimitMiB(readFile) + if err != nil { + f.memoryLimitFallback = err.Error() + } else if limit != 0 { + f.memoryLimitMiB = limit + } + } + if f.memoryLimitMiB < 0 || f.memoryLimitMiB > math.MaxInt64>>20 { + return flags{}, fmt.Errorf("--memory-limit-mib out of range") + } + if f.cpuProfileDir != "" { // before anything starts: run() has no side effect yet + if !cpuProfileSupported { + return flags{}, fmt.Errorf("--cpu-profile-dir needs SIGUSR1 (unix only)") + } + if err := checkCPUProfileDir(f.cpuProfileDir); err != nil { + return flags{}, err + } + } + if f.version { + return f, nil + } + if err := checkMasterTLS(f); err != nil { + return flags{}, err + } + if f.volumeLockDirTestOnly != "" && os.Getenv("INVOCATION_ID") != "" { + return flags{}, fmt.Errorf("--%s is test-only and refused under systemd (INVOCATION_ID is set): the one-process-per-host guarantee needs %s", volumeLockDirTestOnlyFlag, durable.HostVolumeLockDir) + } + if f.recoveryMode != "legacy" && f.recoveryMode != "dual-lane" { + return flags{}, fmt.Errorf("--recovery-mode=%q invalid; want \"legacy\" or \"dual-lane\"", f.recoveryMode) + } + if _, _, err := parseReplicationAckProfile(f.replicationAck); err != nil { + return flags{}, err + } + if err := durable.RemovedEngineName(f.durableImpl); err != nil { + return flags{}, fmt.Errorf("--durable-impl: %w", err) + } + switch f.durableImpl { + case "", "walstore", "walstore-chunk": + default: + return flags{}, fmt.Errorf("--durable-impl=%q invalid; want empty (auto), walstore, or walstore-chunk", f.durableImpl) + } + if f.workspaceLease && (f.durableRoot == "" || f.durableImpl != "walstore-chunk") { + return flags{}, fmt.Errorf("--workspace-lease requires --durable-root and --durable-impl=walstore-chunk") + } + if err := validateChunkFlags(f); err != nil { + return flags{}, err + } + if f.durableImpl == "walstore-chunk" && !f.workspaceLease { + return flags{}, fmt.Errorf("--workspace-lease is required for walstore-chunk: without a master lease two writers can acknowledge I/O and an old holder can lose acknowledged writes after a forced move; restart with --workspace-lease") + } + if f.durableWALMultiBlockRecords { + if f.durableRoot == "" { + return flags{}, fmt.Errorf("--durable-wal-multiblock-records requires --durable-root") + } + if f.durableImpl != "walstore" { + return flags{}, fmt.Errorf("--durable-wal-multiblock-records requires --durable-impl=walstore") + } + } + if f.durableWALRecoveryTestDisableFlusher { + if f.durableRoot == "" { + return flags{}, fmt.Errorf("--durable-wal-recovery-test-disable-flusher requires --durable-root") + } + if f.durableImpl != "walstore" { + return flags{}, fmt.Errorf("--durable-wal-recovery-test-disable-flusher requires --durable-impl=walstore") + } + } + if f.layoutID != "" { + id, err := layout.ParseVolumeID(f.layoutID) + if err != nil { + return flags{}, fmt.Errorf("--layout-id: %w", err) + } + if f.durableRoot == "" { + return flags{}, fmt.Errorf("--layout-id requires --durable-root") + } + if err := (layout.Volume{ID: id, Name: f.volumeID, Format: layout.VolumeFormat}).CheckIdentity(); err != nil { + return flags{}, err + } + f.durableRoot = filepath.Join(f.durableRoot, layout.VolumeDir(f.volumeID, id)) + } + if f.durableRoot != "" { + if _, _, err := durableCreateGeometry(f); err != nil { + return flags{}, err + } + } + if f.iscsiCHAPUser == "" { + f.iscsiCHAPUser = os.Getenv("SW_BLOCK_ISCSI_CHAP_USERNAME") + } + if f.iscsiCHAPSecret == "" { + f.iscsiCHAPSecret = os.Getenv("SW_BLOCK_ISCSI_CHAP_SECRET") + } + missing := []string{} + for name, val := range map[string]string{ + "master": f.masterAddr, "server-id": f.serverID, + "volume-id": f.volumeID, "replica-id": f.replicaID, + "data-addr": f.dataAddr, "ctrl-addr": f.ctrlAddr, + } { + if val == "" { + missing = append(missing, "--"+name) + } + } + if len(missing) > 0 { + return flags{}, fmt.Errorf("required: %v", missing) + } + if f.iscsiListen != "" { + if f.iscsiIQN == "" { + return flags{}, fmt.Errorf("--iscsi-iqn is required when --iscsi-listen is set") + } + if err := enforceISCSIBindPolicy(f); err != nil { + return flags{}, err + } + // iSCSI needs a Healthy adapter projection to open a + // memback backend. Auto-enable the T1 readiness bridge + // rather than failing — safer default for the beta + // product host. Emits a one-line stderr notice so + // operators don't misread the auto-enable as an + // invisible side effect. + if !f.enableT1Readiness { + fmt.Fprintln(os.Stderr, "blockvolume: iscsi enabled: t1-readiness auto-enabled") + } + f.enableT1Readiness = true + if (f.iscsiCHAPUser == "") != (f.iscsiCHAPSecret == "") { + return flags{}, fmt.Errorf("--iscsi-chap-username and --iscsi-chap-secret must be set together") + } + } else if f.iscsiPortalAddr != "" { + return flags{}, fmt.Errorf("--iscsi-portal-addr requires --iscsi-listen") + } else if f.iscsiDataOutTTL != 0 { + return flags{}, fmt.Errorf("--iscsi-dataout-timeout requires --iscsi-listen") + } else if f.iscsiCHAPUser != "" || f.iscsiCHAPSecret != "" { + return flags{}, fmt.Errorf("--iscsi-chap-username/--iscsi-chap-secret require --iscsi-listen") + } + if f.nvmeListen != "" { + if f.nvmeTransport != "tcp" && f.nvmeTransport != "rdma" { + return flags{}, fmt.Errorf("--nvme-transport=%q unsupported; use \"tcp\" or \"rdma\"", f.nvmeTransport) + } + if f.nvmeSubsysNQN == "" { + return flags{}, fmt.Errorf("--nvme-subsysnqn is required when --nvme-listen is set") + } + if err := enforceNVMeBindPolicy(f); err != nil { + return flags{}, err + } + if f.nvmeMaxH2C > uint(^uint32(0)) { + return flags{}, fmt.Errorf("--nvme-max-h2c-data-length=%d exceeds uint32", f.nvmeMaxH2C) + } + if f.nvmeTransport == "rdma" && f.nvmeMaxH2C != 0 { + return flags{}, fmt.Errorf("--nvme-max-h2c-data-length applies only to --nvme-transport=tcp") + } + if err := nvme.ValidateMaxH2CDataLength(uint32(f.nvmeMaxH2C)); err != nil { + return flags{}, fmt.Errorf("--nvme-max-h2c-data-length=%d invalid: %w", f.nvmeMaxH2C, err) + } + // Symmetric with iSCSI auto-enable per QA checkpoint-7 + // note: keep the two protocols' safe-default behavior + // identical so the closure report doesn't have to + // explain asymmetry. + if !f.enableT1Readiness { + fmt.Fprintln(os.Stderr, "blockvolume: nvme enabled: t1-readiness auto-enabled") + } + f.enableT1Readiness = true + } else if f.nvmeMaxH2C != 0 { + return flags{}, fmt.Errorf("--nvme-max-h2c-data-length requires --nvme-listen") + } + if f.ublkDevice >= 0 { + if f.ublkQueues < 0 || f.ublkQueues > 64 { + return flags{}, fmt.Errorf("--ublk-queues=%d, want 0..64", f.ublkQueues) + } + if f.ublkQueueDepth < 0 || f.ublkQueueDepth > 4096 { + return flags{}, fmt.Errorf("--ublk-queue-depth=%d, want 0..4096", f.ublkQueueDepth) + } + // Like iSCSI and NVMe: the device serves only through a healthy + // projection. + if !f.enableT1Readiness { + fmt.Fprintln(os.Stderr, "blockvolume: ublk enabled: t1-readiness auto-enabled") + } + f.enableT1Readiness = true + } else if f.ublkDevice < -1 { + return flags{}, fmt.Errorf("--ublk-device=%d, want -1 (off) or a device id >= 0", f.ublkDevice) + } else if f.ublkQueues != 0 || f.ublkQueueDepth != 0 { + return flags{}, fmt.Errorf("--ublk-queues/--ublk-queue-depth require --ublk-device") + } + return f, nil +} + +func parseReplicationAckProfile(profile string) (replication.DurabilityMode, durable.WriteAckPolicy, error) { + switch profile { + case "best-effort": + return replication.DurabilityBestEffort, durable.WriteAckBestEffort, nil + case "sync-quorum": + return replication.DurabilitySyncQuorum, durable.WriteAckRequireObserverAck, nil + case "sync-all": + return replication.DurabilitySyncAll, durable.WriteAckRequireObserverAck, nil + default: + return replication.DurabilityBestEffort, durable.WriteAckBestEffort, + fmt.Errorf("--replication-ack=%q invalid; want \"best-effort\", \"sync-quorum\", or \"sync-all\"", profile) + } +} + +// computeFrontendVolumeSize returns the byte capacity an iSCSI/NVMe +// target should advertise: durableBlocks × blockSize. +// +// iSCSI/NVMe externally-visible volume capacity and block count must +// derive from --durable-blocks × --durable-blocksize, not silently +// fall back to frontend defaults — otherwise the frontend would use +// 1 MiB defaults regardless of the daemon's actual durable config, +// breaking any workload above 1 MiB. +// +// Overflow guard: blocks × blockSize is computed in uint64 and a +// fits-in-uint64 check is applied (32×32 → 64 cannot overflow today +// since both fit in uint32, but keep the guard for future +// hardening). +func computeFrontendVolumeSize(blocks uint, blockSize uint) (uint64, error) { + if blocks == 0 { + return 0, fmt.Errorf("computeFrontendVolumeSize: --durable-blocks must be > 0") + } + if blockSize == 0 { + return 0, fmt.Errorf("computeFrontendVolumeSize: --durable-blocksize must be > 0") + } + bs := uint64(blockSize) + bk := uint64(blocks) + out := bk * bs + if out/bs != bk { + return 0, fmt.Errorf("computeFrontendVolumeSize: blocks(%d) * blockSize(%d) overflows uint64", blocks, blockSize) + } + return out, nil +} + +// enforceFrontendLoopbackBind mirrors volume.StatusServer's guard for +// any frontend (iscsi / nvme): refuses to bind on anything other than +// 127.0.0.1 / ::1. Frontends are currently unauthenticated; +// real-network exposure waits on the security track. +func enforceFrontendLoopbackBind(kind, addr string) error { + host, _, err := net.SplitHostPort(addr) + if err != nil { + return fmt.Errorf("--%s-listen %q not host:port: %w", kind, addr, err) + } + if host == "" { + return fmt.Errorf("--%s-listen %q has empty host; must be a loopback address (127.0.0.1 or ::1)", kind, addr) + } + ip := net.ParseIP(host) + if ip == nil || !ip.IsLoopback() { + return fmt.Errorf("--%s-listen %q is not loopback; %s target is unauthenticated and refuses external binds", kind, addr, kind) + } + return nil +} + +func enforceISCSIBindPolicy(f flags) error { + if !f.allowExternalISCSIBind { + return enforceFrontendLoopbackBind("iscsi", f.iscsiListen) + } + if f.iscsiCHAPUser == "" || f.iscsiCHAPSecret == "" { + return fmt.Errorf("--allow-external-iscsi-bind requires CHAP") + } + host, _, err := net.SplitHostPort(f.iscsiListen) + if err != nil { + return fmt.Errorf("--iscsi-listen %q not host:port: %w", f.iscsiListen, err) + } + if host == "" { + return fmt.Errorf("--iscsi-listen %q has empty host; external iSCSI bind requires an explicit node address", f.iscsiListen) + } + if isLocalhostOrLoopbackHost(host) { + return fmt.Errorf("--iscsi-listen %q is loopback; external iSCSI bind requires a non-loopback node address", f.iscsiListen) + } + return nil +} + +func enforceNVMeBindPolicy(f flags) error { + if !f.allowExternalNVMeBind { + return enforceFrontendLoopbackBind("nvme", f.nvmeListen) + } + host, _, err := net.SplitHostPort(f.nvmeListen) + if err != nil { + return fmt.Errorf("--nvme-listen %q not host:port: %w", f.nvmeListen, err) + } + if host == "" { + return fmt.Errorf("--nvme-listen %q has empty host; external NVMe/TCP bind requires an explicit node address", f.nvmeListen) + } + if isLocalhostOrLoopbackHost(host) { + return fmt.Errorf("--nvme-listen %q is loopback; external NVMe/TCP bind requires a non-loopback node address", f.nvmeListen) + } + return nil +} + +func isLocalhostOrLoopbackHost(host string) bool { + if strings.EqualFold(host, "localhost") { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + +func main() { + f, err := parseFlags(os.Args[1:]) + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume:", err) + os.Exit(2) + } + if f.version { + fmt.Println(buildinfo.Version("blockvolume")) + return + } + if err := logging.Configure(f.logLevel); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + applyMemoryLimit(f, log.Printf) + os.Exit(run(f)) +} + +type readyLine struct { + Component string `json:"component"` + Phase string `json:"phase"` + VolumeID string `json:"volume_id"` + ReplicaID string `json:"replica_id"` + Epoch uint64 `json:"epoch"` + EndpointVersion uint64 `json:"endpoint_version"` +} + +type statusReadyLine struct { + Component string `json:"component"` + Phase string `json:"phase"` + StatusAddr string `json:"status_addr"` +} + +type iscsiReadyLine struct { + Component string `json:"component"` + Phase string `json:"phase"` + IscsiAddr string `json:"iscsi_addr"` + IQN string `json:"iqn"` +} + +// ublkReadyLine reports the ublk block device once it serves. +type ublkReadyLine struct { + Component string `json:"component"` + Phase string `json:"phase"` + Device string `json:"device"` +} + +type nvmeReadyLine struct { + Component string `json:"component"` + Phase string `json:"phase"` + NvmeAddr string `json:"nvme_addr"` + SubsysNQN string `json:"subsys_nqn"` +} + +// durableCreateGeometry leaves existing volumes in open-only mode. If the +// observed file disappears before Open, NumBlocks=0 prevents a replacement +// from being created using narrowed or otherwise ignored CLI values. +func durableCreateGeometry(f flags) (uint32, int, error) { + path := filepath.Join(f.durableRoot, f.volumeID+".bin") + if _, err := os.Stat(path); err == nil { + return 0, 0, nil + } else if !os.IsNotExist(err) { + return 0, 0, fmt.Errorf("durable volume geometry: %w", err) + } + if err := geometry.ValidateBlockGeometry(uint64(f.durableBlocks), uint64(f.durableBlockSize)); err != nil { + return 0, 0, fmt.Errorf("--durable-blocks/--durable-blocksize: %w", err) + } + return uint32(f.durableBlocks), int(f.durableBlockSize), nil +} + +func runVolume(f flags, exits *processExit) int { + // Diagnostics first: parseFlags validated the directory, and nothing + // has been activated yet, so a failure here leaves nothing to clean up. + stopProfile, err := startCPUProfileSignal(f.cpuProfileDir) + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume:", err) + return 1 + } + defer stopProfile() + readyCh := make(chan adapter.AssignmentInfo, 16) + + dialTLS, err := masterDialTLS(f) + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume:", err) + return 1 + } + hc := hostConfig(f, readyCh) + hc.MasterTLS = dialTLS + h, err := volume.New(hc) + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume:", err) + return 1 + } + if f.durableRoot != "" { + h.BlockLocalReadiness("awaiting durable recovery") + } + h.Start() + + var status *volume.StatusServer + if f.statusAddr != "" { + status = volume.NewStatusServer(h.ProjectionView()) + status.SetMasterWait(h.MasterWaitStatus) + if f.nvmeListen != "" { + status.SetNVMeListenerReady(false) + } + if f.statusRecovery { + status.EnableRecoveryEndpoint() + } + if f.runtimeRebuildEndpoint { + status.EnableRuntimeEndpoint() + } + if f.chunk.controlEndpoint { + status.EnableChunkControlEndpoint() + } + if f.allowExternalStatusBind { + status.AllowExternalAccess() + } + status.SetFrontendCapabilities(nvmeFrontendCapabilities(f.nvmeListen, f.nvmeTransport, false)) + bound, err := status.Start(f.statusAddr) + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: status server:", err) + _ = h.Close() + return 1 + } + // Emit a discoverable ready line so subprocess harnesses + // can learn the bound port when --status-addr is ":0". + _ = json.NewEncoder(os.Stdout).Encode(statusReadyLine{ + Component: "blockvolume", + Phase: "status-listening", + StatusAddr: bound, + }) + } + + // T3b: pick Provider per --durable-root flag. When the flag is + // unset, fall back to memback (non-durable, legacy behavior). + // When set, DurableProvider opens (or creates) on-disk storage + // per --durable-impl and runs Recovery before the frontends + // accept connections. + var provider frontend.Provider + var durableProv *durable.DurableProvider + var workspaceLayoutHead layout.HeadStore + if f.durableRoot != "" { + blocks, blockSize, geometryErr := durableCreateGeometry(f) + var dp *durable.DurableProvider + cfg := durable.ProviderConfig{ + WALHold: f.walHold, + RecoveryProgress: h.ReportRecoveryProgress, + AuthorityWait: h.ReportAuthorityWait, + Impl: durable.ImplName(f.durableImpl), + StorageRoot: f.durableRoot, + BlockSize: blockSize, + NumBlocks: blocks, + ChunkBlocks: durable.DefaultChunkBlocks, + WALRetentionLSNs: f.walRetentionLSNs, + WALMultiBlockRecords: f.durableWALMultiBlockRecords, + WALRecoveryTestDisableFlusher: f.durableWALRecoveryTestDisableFlusher, + // Host-lock rule: one live process per volume per host. + HostVolumeLock: true, + VolumeLockDirTestOnly: f.volumeLockDirTestOnly, + } + if f.volumeLockDirTestOnly != "" { + fmt.Fprintf(os.Stderr, "blockvolume: volume lock directory %s is a test override: the one-process-per-host guarantee does not hold\n", f.volumeLockDirTestOnly) + } + var chunkErr error + var chunk chunkWiring + if cfg.Impl == durable.ImplWALStoreChunk { + chunk, chunkErr = newChunkWiring(f.chunk, dialTLS, f.masterAddr) + cfg.ChunkCaptureInterval = f.chunk.captureInterval + cfg.ChunkCutTimeout = defaultChunkCutTimeout + cfg.ChunkMaintenanceInterval = f.chunk.maintenanceInterval + cfg.ChunkMaintenanceTimeout = defaultChunkMaintenanceTimeout + if f.workspaceLease { + // The startup wait does not run out while the master gives no + // reply; it ends 30 s after the first reply received after the + // local open and recovery (or the master's barrier time), or at + // once on a moved/deleted refusal. + cfg.ChunkMasterWait = func(start time.Time) (time.Time, bool) { + deadline, final := h.MasterWaitBound(start) + return deadline, final != "" + } + } + if chunk.bCatalog != nil && f.chunk.snapshotSchedule.period > 0 { + cfg.ChunkSnapshotPeriod = f.chunk.snapshotSchedule.period + cfg.ChunkScheduledSnapshot = volume.ScheduledSnapshot(func(ctx context.Context, name, snapshot string, meta layout.SnapshotMeta) (chunkstore.SnapshotInfo, error) { + p, ok := any(dp).(interface { + SnapshotVolume(context.Context, string, string, layout.SnapshotMeta) (layout.Head, error) + }) + if !ok { + return chunkstore.SnapshotInfo{}, errors.New("chunk snapshot data path is not configured") + } + h, err := p.SnapshotVolume(ctx, name, snapshot, meta) + if err != nil { + return chunkstore.SnapshotInfo{}, err + } + return chunkstore.SnapshotInfoFromHead(name, snapshot, h), nil + }, f.chunk.snapshotSchedule.keep) + } + cfg.ChunkDetachPrecopy = f.chunk.detachPrecopy + cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency + cfg.ChunkHydrationWorkers = f.chunk.hydrationWorkers + cfg.ChunkHydrationQueueDepth = f.chunk.hydrationQueueDepth + cfg.ChunkHolder = chunkHolder(f) + cfg.ChunkStagger = true + if f.chunk.hostLimit.Directory != "" { + limitErr := hostlimit.CheckLaunch(f.chunk.hostLimit) + var limiter *hostlimit.Limiter + if limitErr == nil { + limiter, limitErr = hostlimit.New(f.chunk.hostLimit) + } + if limitErr != nil { + chunkErr = errors.Join(chunkErr, limitErr) + } else { + defer limiter.Close() + cfg.ChunkBudget = limiter + cfg.ChunkPayloadMemoryBudget = f.chunk.hostLimit.PayloadBytes + cfg.ChunkCOWSpillLimit = f.chunk.hostLimit.COWBytes + } + } + // A detach is a graceful stop: the lease guard renews at a short + // cadence for the revocation that follows instead of waiting out + // its renewal delay, until the detach provably aborts and resumes. + cfg.OnChunkDetach = h.WorkspaceStopPending + cfg.OnChunkDetachResumed = h.WorkspaceStopResumed + if chunkErr == nil { + + layoutID, _ := layout.ParseVolumeID(f.layoutID) // parseFlags validates a supplied id + ref := chunkstore.VolumeRef{Name: f.volumeID, ID: layoutID} + cfg.ChunkAttachCheck = chunkAttachCheck(chunk.bCatalog, ref) + cfg.ChunkLayoutHeadFor = func(name string) (layout.StartStore, error) { + if name != ref.Name { + return nil, layout.ErrIdentity + } + return chunk.bCatalog.Store(ref) + } + cfg.ChunkLayoutRemoteFor = func(name string, me layout.HolderID) (storage.ChunkRemote, error) { + if name != ref.Name { + return nil, layout.ErrIdentity + } + return chunkstore.NewLayoutRemote(chunk.bCatalog, ref, me) + } + workspaceLayoutHead, chunkErr = chunk.bCatalog.Store(ref) + // The holder identity comes from Start (until it is wired, the + // pass retains and does not clean). + cfg.ChunkMaintenance = newChunkMaintenance(chunk.bCatalog, ref, func(ctx context.Context) (layoutCleaner, error) { + if dp == nil { + return nil, errNoLayoutHolder + } + r, err := dp.LayoutRemote(ctx, f.volumeID) + if err != nil { + return nil, fmt.Errorf("%w: %w", errNoLayoutHolder, err) + } + c, ok := r.(layoutCleaner) + if !ok { + return nil, fmt.Errorf("%w: the attachment's remote (%T) cannot clean", errNoLayoutHolder, r) + } + return c, nil + }, f.chunk.automaticGC, time.Now) + defer chunk.close() + } + } + // Only a store about to be created takes its geometry from the flags; + // an existing store opens with its own (blocks == 0), and a mismatch + // between it and the record is the attach check's. + if chunkErr == nil && geometryErr == nil && blocks != 0 && chunk.bCatalog != nil { + readCtx, readCancel := context.WithTimeout(context.Background(), 10*time.Second) + layoutID, _ := layout.ParseVolumeID(f.layoutID) + refusal, code := geometryFlagsRefusal(readCtx, chunk.bCatalog, chunkstore.VolumeRef{Name: f.volumeID, ID: layoutID}, uint64(blocks), uint32(blockSize), cfg.ChunkBlocks) + readCancel() + if refusal != "" { + fmt.Fprintln(os.Stderr, refusal) + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return code + } + } + err := geometryErr + if err == nil { + dp, err = durable.NewDurableProvider(cfg, h.ProjectionView()) + if err == nil { + applyBuildTagHold(dp) // a no-op except in a kzhold (test-only) build + } + } + if chunkErr != nil { + err = chunkErr + } + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: durable provider:", err) + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + durableProv = dp + watchCtx, stopWatch := context.WithCancel(exits.parent) + defer stopWatch() + go watchChunkStartup(watchCtx, exits, f, h, dp) + go watchChunkRuntimeFence(watchCtx, exits, f, dp) + provider = dp + if status != nil { + status.SetDurableStatusSource(dp) + if f.chunk.controlEndpoint && chunk.bCatalog != nil { + layoutID, _ := layout.ParseVolumeID(f.layoutID) + status.SetChunkControl(volume.NewChunkControl(dp, chunk.bCatalog, chunkstore.VolumeRef{Name: f.volumeID, ID: layoutID})) + } + } + + // Open storage role-agnostically via EnsureStorage so replica + // roles (assigned to SUPPORTING, never reach Healthy via + // projection) can still expose LogicalStorage to + // ReplicaListener. The Healthy-gated dp.Open path is reserved + // for frontend consumers (iSCSI / NVMe targets); they call it + // when they accept their first I/O. Primary role: dp.Open + // will succeed at frontend bind. Replica role: frontends are + // not enabled (operator doesn't pass --iscsi-listen / + // --nvme-listen for replicas), so dp.Open is never called. + // G1: a volume about to be created gets its replica floor record + // (epoch 0) FIRST, so every later start can require the record and + // an existing volume is never mistaken for a fresh one. A crash + // between the two keeps the record; the volume is created next time. + exists, xErr := dp.VolumeExists(f.volumeID) + if xErr == nil && !exists { + xErr = transport.InitReplicaFloor(replicaFloorPath(f), f.volumeID) + } + if xErr != nil { + fmt.Fprintln(os.Stderr, "blockvolume: replica floor init:", xErr) + _ = closeProviderAfterSnapshotOperations(status, dp.Close) + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + // Open and replay (#133): a classifiable failure in either step + // (wal_corrupt / io_error) faults fail-closed and is reported at + // once by a primary assignment; see openAndRecoverDurable. + outcome, evidence, sErr := openAndRecoverDurable(dp, h, f.volumeID, 10*time.Second) + chooseChunkStartupExit(exits, f, h, dp) + switch outcome { + case durableStartupFatal: + fmt.Fprintln(os.Stderr, "blockvolume: durable storage open:", sErr) + _ = closeProviderAfterSnapshotOperations(status, dp.Close) + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + code, reason := durableOpenFatalExit(sErr) + if reason != "" { + return reportWorkspaceExit(workspaceExit{code: code, reason: reason, detail: "the local store was written by a newer version: run a newer binary"}) + } + return code + case durableStartupFaulted: + fmt.Fprintln(os.Stderr, "blockvolume: durable recovery failed:", evidence) + return waitFaultedDurableRecovery(exits.done, h, status, durableProv, evidence) + default: + fmt.Fprintln(os.Stderr, "blockvolume: durable recovered:", evidence) + } + } else { + // memback fallback — wraps the volume's AdapterProjectionView + // so per-op lineage fence + supersede fence still apply at + // SCSI command granularity. + provider = memback.NewProvider(h.ProjectionView()) + } + startReadyAssignmentLoop(readyCh, f, durableProv, os.Stdout, os.Stderr) + + // Bind the replication stack — ReplicationVolume for outbound peer + // fan-out (primary role) + ReplicaListener for incoming WAL traffic + // (replica role). Incoming listeners are bound only when the master + // assignment includes replica slots; RF=1 never opens either lane. Construction + // is post-dp.RecoverVolume because both borrow the same + // LogicalStorage the durable Backend wraps; the LogicalStorage + // isn't usable until recovery completes. + // + // ReplicaListener bind = --data-addr (NOT --ctrl-addr): the + // transport executor's Probe + Ship paths dial peer.DataAddr + // (executor.go:303); for the listener to be reachable from + // remote primaries, it must bind on the address the master + // will mint into AssignmentFact.peers[*].DataAddr — i.e., the + // volume's --data-addr. --ctrl-addr stays reserved for future + // control-plane split (no current binder). + var ( + replVolume *replication.ReplicationVolume + replListen *replicationIngress + ) + if durableProv != nil { + store := durableProv.LogicalStorage(f.volumeID) + if store == nil { + fmt.Fprintln(os.Stderr, "blockvolume: replication wire: LogicalStorage(", f.volumeID, ") returned nil") + _ = closeProviderAfterSnapshotOperations(status, durableProv.Close) + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + replVolume = replication.NewReplicationVolume(f.volumeID, store) + if status != nil { + status.SetPeerStatusSource(replVolume) + h.SetProbeRoleSource(status.ProbeRoles) + status.SetRuntimeRecoverySource(replVolume) + } + repMode, writeAck, err := parseReplicationAckProfile(f.replicationAck) + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume:", err) + _ = closeProviderAfterSnapshotOperations(status, durableProv.Close) + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + replVolume.SetDurabilityMode(repMode) + h.SetReplicationVolume(replVolume) + + // When --recovery-mode=dual-lane, inject the dual-lane executor + // factory so per-peer BlockExecutors route StartRebuild through + // core/recovery's PrimaryBridge. Per-volume coordinator is + // shared across all peers so MinPinAcrossActiveSessions + // reflects the true minimum. + // + // Dual-lane address derivation: peer.DataAddr's port + 1. + // Convention only — production may eventually carry a separate + // dual-lane field in AssignmentFact. + if f.recoveryMode == "dual-lane" { + recoveryCoord := recovery.NewPeerShipCoordinator() + replVolume.SetDualLaneExecutorFactory(func(s storage.LogicalStorage, replicaAddr, replicaID string) *transport.BlockExecutor { + peerDualLane, err := deriveDualLaneAddr(replicaAddr) + if err != nil { + // Fall back to legacy ctor; the executor will not + // have a dual-lane path. Logged for diagnostics. + fmt.Fprintf(os.Stderr, + "blockvolume: recovery-mode=dual-lane but peer addr %q has no port+1 form (%v); falling back to legacy executor for this peer\n", + replicaAddr, err) + return transport.NewBlockExecutor(s, replicaAddr) + } + return transport.NewBlockExecutorWithDualLane(s, replicaAddr, peerDualLane, recoveryCoord, recovery.ReplicaID(replicaID)) + }) + // Install the recycle-floor gate on the substrate so the + // WAL recycle path consults the per-volume coordinator's + // MinPinAcrossActiveSessions. Skipped silently when + // substrate doesn't implement RecycleFloorGate. + // walstore + memorywal both satisfy. + if gate, ok := store.(storage.RecycleFloorGate); ok { + gate.SetRecycleFloorSource(recoveryCoord) + fmt.Fprintln(os.Stderr, "blockvolume: dual-lane recycle gate installed (substrate honors min(pin_floor))") + } else { + fmt.Fprintln(os.Stderr, "blockvolume: dual-lane substrate does not implement RecycleFloorGate; pin_floor advances unenforced at recycle") + } + fmt.Fprintln(os.Stderr, "blockvolume: recovery-mode=dual-lane (PrimaryBridge per-peer; coord per-volume)") + } + + // Configure + start the degraded-peer probe loop if the + // operator opted in via --degraded-probe-interval > 0. Off by + // default. The probe loop is owned by ReplicationVolume + // lifecycle; volume.Close stops the loop before peer teardown. + // + // Notes: + // - interval=0 → don't Configure (loop stays absent) + // - cooldown-base/cap normalized in NewProbeLoop (cap < base + // is bumped up to base; 0 → defaults) + // - production probeFn from volume.ProductionProbeFn — + // releases peer.mu before transport call; transport failure + // → non-nil err (advances backoff); transport success → + // nil err (resets cooldown). + // - Configure→Start ordering — both here (peers may or may + // not exist yet; empty peer set is safely no-op). + if f.degradedProbeInterval > 0 { + // Per-peer adapter registry is the engine state holder for + // each admitted peer (NOT for the host's own slot, which + // already has h.Adapter()). The probe loop's + // ProductionProbeFn routes per-peer via this registry so + // engine.checkReplicaID accepts the events. + peerRegistry := volume.NewPeerAdapterRegistry(f.volumeID, f.replicaID) + peerRegistry.SetFrontier(store.Sync) + if err := replVolume.ConfigurePeerLifecycleHook(peerRegistry.OnPeerAdded, peerRegistry.OnPeerRemoved); err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: peer lifecycle hook:", err) + _ = replVolume.Close() + _ = closeProviderAfterSnapshotOperations(status, durableProv.Close) + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + + loopCfg := replication.ProbeLoopConfig{ + Interval: f.degradedProbeInterval, + MaxConcurrent: 1, // only 1 supported in this version + CooldownBase: f.degradedProbeCooldownBase, + CooldownCap: f.degradedProbeCooldownCap, + } + probeFn := volume.ProductionProbeFnWithPrime(peerRegistry.AdapterForPeer, peerRegistry.PrimePendingFor) + if err := replVolume.ConfigureProbeLoop(loopCfg, probeFn, time.Now); err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: probe loop configure:", err) + _ = replVolume.Close() + _ = closeProviderAfterSnapshotOperations(status, durableProv.Close) + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + if err := replVolume.StartProbeLoop(); err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: probe loop start:", err) + _ = replVolume.Close() + _ = closeProviderAfterSnapshotOperations(status, durableProv.Close) + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + fmt.Fprintf(os.Stderr, + "blockvolume: G5-5C probe loop started (interval=%s cooldown-base=%s cooldown-cap=%s)\n", + f.degradedProbeInterval, f.degradedProbeCooldownBase, f.degradedProbeCooldownCap) + } + + // Wire the backend's WriteObserver eagerly via the Backend + // accessor (same StorageBackend instance dp.Open returns later + // for primary-role frontend bind). Without this hook, primary + // writes would land locally but never ship to peers. + if sb := durableProv.Backend(f.volumeID); sb != nil { + if err := sb.SetWriteObserver(replVolume); err != nil { + // The backend now refuses all I/O; the volume cannot serve. + fmt.Fprintln(os.Stderr, "blockvolume: write-observer wire:", err) + } + sb.SetWriteAckPolicy(writeAck) + } else { + fmt.Fprintln(os.Stderr, "blockvolume: write-observer wire: Backend(", f.volumeID, ") returned nil; replication fan-out disabled") + } + + // No replication socket exists until a master assignment includes + // replica slots. The role gate starts/fences both lanes before admission. + replListen = newReplicationIngress(f, store) + replVolume.SetEpochTable(replListen.EpochTable()) + if err := h.SetSelfFence(replListen); err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: replica listener role:", err) + replListen.Stop() + _ = replVolume.Close() + _ = closeProviderAfterSnapshotOperations(status, durableProv.Close) + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + } + + // Frontend volume capacity MUST derive from the daemon's + // --durable-blocks × --durable-blocksize when --durable-root is + // set, not silently fall back to frontend defaults. Without this + // plumb-through, iSCSI/NVMe advertise 1 MiB regardless of the + // daemon's actual durable capacity, which breaks any workload + // > 1 MiB. + // + // Memback path (--durable-root unset): keep frontend defaults. + // The frontend HandlerConfig zero-value path picks + // DefaultBlockSize=512 + DefaultVolumeBlocks=2048 (1 MiB) which + // is the historical memback contract. + var ( + frontendBlockSize uint32 + frontendVolumeSize uint64 + ) + if f.durableRoot != "" { + bs, err := computeFrontendVolumeSize(f.durableBlocks, f.durableBlockSize) + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: frontend volume size:", err) + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + frontendBlockSize = uint32(f.durableBlockSize) + frontendVolumeSize = bs + } + // frontendBlockSize / frontendVolumeSize are zero on memback — + // HandlerConfig zero-value defaulting kicks in inside iscsi / + // nvme construction (preserves T2 historical 1 MiB / 512 B + // behavior). + + var iscsiTarget *iscsi.Target + var frontendTargets []*control.FrontendTarget + var nvmeTarget interface { + Start() (string, error) + Close() error + } + var ublkTarget *ublk.Target + + // One startup order (INV-FE-PRIMARY-READY-OPERATIONAL-001 with + // INV-WS-STARTUP-RETRY-001): the workspace lease guard and the process's + // one stop waiter (waitWorkspaceStop: signal, lease drain request, lease + // end, or the latched startup outcome) run from here, before any frontend; + // the frontends start only when the backend first admits I/O, and never + // if a stop wins that race. + shutdownCtx := exits.parent + var leaseRequests <-chan workspaceStopRequest + var leaseDone <-chan error + if f.workspaceLease { + leaseRequests, leaseDone = startWorkspaceLease(shutdownCtx, h) + } + stopWait := make(chan workspaceStopWait, 1) + go func(requests <-chan workspaceStopRequest, done <-chan error) { + ls, ld := waitWorkspaceStop(exits, f, h, requests, done) + stopWait <- workspaceStopWait{leaseStop: ls, leaseDone: ld} + }(leaseRequests, leaseDone) + var serving <-chan struct{} // nil: no durable backend, start at once + if durableProv != nil { + if b := durableProv.Backend(f.volumeID); b != nil { + serving = frontendStartSignal(f, b, exits.done) + } + } + stopped, startFrontends := awaitFrontendStart(serving, stopWait) + if startFrontends { + 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() + negotiation.CHAP = iscsi.CHAPConfig{ + Username: f.iscsiCHAPUser, + Secret: f.iscsiCHAPSecret, + } + } + iscsiTarget = iscsi.NewTarget(iscsi.TargetConfig{ + Listen: f.iscsiListen, + IQN: f.iscsiIQN, + 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() + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: iscsi target:", err) + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + if status != nil { + status.SetGuestSource("iscsi", iscsiTarget.NormalSessions) + } + _ = json.NewEncoder(os.Stdout).Encode(iscsiReadyLine{ + Component: "blockvolume", + Phase: "iscsi-listening", + IscsiAddr: iscsiAddr, + IQN: f.iscsiIQN, + }) + frontendTargets = append(frontendTargets, &control.FrontendTarget{ + Protocol: "iscsi", + Addr: iscsiAddr, + Iqn: f.iscsiIQN, + Lun: uint32(f.iscsiLUN), + }) + h.SetFrontendTargets(frontendTargets) + } + + if f.nvmeListen != "" { + if f.nvmeTransport == "rdma" { + start := nvmeRDMAListenerStartDecision(true, nvmeRDMAPreflightFacts(f.nvmeListen)) + if !start.allowed { + fmt.Fprintf(os.Stderr, "blockvolume: nvme rdma start refused: reason=%s\n", start.reason) + if iscsiTarget != nil { + _ = iscsiTarget.Close() + } + if replListen != nil { + replListen.Stop() + } + if replVolume != nil { + _ = replVolume.Close() + } + if durableProv != nil { + _ = closeProviderAfterSnapshotOperations(status, durableProv.Close) + } + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + blockSize := frontendBlockSize + volumeSize := frontendVolumeSize + if blockSize == 0 { + blockSize = nvme.DefaultBlockSize + } + if volumeSize == 0 { + volumeSize = nvme.DefaultVolumeBlocks * uint64(blockSize) + } + nvmeTarget = nvmerdma.NewTarget(nvmerdma.TargetConfig{ + Listen: f.nvmeListen, + SubsysNQN: f.nvmeSubsysNQN, + VolumeID: f.volumeID, + NSID: uint32(f.nvmeNS), + BlockSize: blockSize, + VolumeSize: volumeSize, + Provider: provider, + }) + } else { + var probeProvider nvme.ProbeBackendProvider + if durableProv != nil { + probeProvider = &durableProbeProvider{provider: durableProv} + } + nvmeTarget = nvme.NewTarget(nvme.TargetConfig{ + Transport: nvme.TransportTCP, + Listen: f.nvmeListen, + SubsysNQN: f.nvmeSubsysNQN, + VolumeID: f.volumeID, + Provider: provider, + ProbeProvider: probeProvider, + ControllerID: nvmeControllerIDFromReplicaID(f.replicaID), + MaxH2CDataLength: uint32(f.nvmeMaxH2C), + Handler: nvme.HandlerConfig{ + NSID: uint32(f.nvmeNS), + BlockSize: frontendBlockSize, + VolumeSize: frontendVolumeSize, + ANA: newProjectionANAProvider(h.ProjectionView(), f.volumeID, f.replicaID, f.nvmeSubsysNQN), + }, + }) + } + nvmeAddr, err := nvmeTarget.Start() + if err != nil { + if f.nvmeTransport == "rdma" { + fmt.Fprintf(os.Stderr, "blockvolume: nvme rdma start refused: reason=%s error=%v\n", nvmeRDMATargetStartFailureReason(err), err) + } else { + fmt.Fprintln(os.Stderr, "blockvolume: nvme target:", err) + } + if iscsiTarget != nil { + _ = iscsiTarget.Close() + } + if replListen != nil { + replListen.Stop() + } + if replVolume != nil { + _ = replVolume.Close() + } + if durableProv != nil { + _ = closeProviderAfterSnapshotOperations(status, durableProv.Close) + } + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + if status != nil { + status.SetNVMeListenerReady(true) + } + _ = json.NewEncoder(os.Stdout).Encode(nvmeReadyLine{ + Component: "blockvolume", + Phase: "nvme-listening", + NvmeAddr: nvmeAddr, + SubsysNQN: f.nvmeSubsysNQN, + }) + if shouldPublishNVMeFrontendTarget(f.nvmeTransport) { + frontendTargets = append(frontendTargets, &control.FrontendTarget{ + Protocol: "nvme", + Transport: f.nvmeTransport, + Addr: nvmeAddr, + Nqn: f.nvmeSubsysNQN, + Nsid: uint32(f.nvmeNS), + }) + h.SetFrontendTargets(frontendTargets) + } + if status != nil { + status.SetFrontendCapabilities(nvmeFrontendCapabilities(f.nvmeListen, f.nvmeTransport, true)) + if source, ok := nvmeTarget.(interface{ Stats() nvme.Stats }); ok { + status.SetNVMeStatusSource(source) + } + if source, ok := nvmeTarget.(interface{ ConnectedHosts() int }); ok { + status.SetGuestSource("nvme", source.ConnectedHosts) + } + } + } + + if f.ublkDevice >= 0 { + blockSize := frontendBlockSize + volumeSize := frontendVolumeSize + if blockSize == 0 { + blockSize = nvme.DefaultBlockSize + } + if volumeSize == 0 { + volumeSize = nvme.DefaultVolumeBlocks * uint64(blockSize) + } + ublkTarget = ublk.NewTarget(ublk.TargetConfig{ + VolumeID: f.volumeID, + Provider: provider, + DevID: f.ublkDevice, + BlockSize: blockSize, + VolumeSize: volumeSize, + Queues: f.ublkQueues, + QueueDepth: f.ublkQueueDepth, + }) + ublkPath, err := ublkTarget.Start() + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: ublk device:", err) + if nvmeTarget != nil { + _ = nvmeTarget.Close() + } + if iscsiTarget != nil { + _ = iscsiTarget.Close() + } + if replListen != nil { + replListen.Stop() + } + if replVolume != nil { + _ = replVolume.Close() + } + if durableProv != nil { + _ = closeProviderAfterSnapshotOperations(status, durableProv.Close) + } + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + _ = h.Close() + return 1 + } + if status != nil { + status.SetUblkStatusSource(ublkTarget) + } + _ = json.NewEncoder(os.Stdout).Encode(ublkReadyLine{ + Component: "blockvolume", + Phase: "ublk-ready", + Device: ublkPath, + }) + } + } // startFrontends + + // The one stop waiter has already returned if a stop won the race above. + if stopped == nil { + w := <-stopWait + stopped = &w + } + leaseStop, leaseDone := stopped.leaseStop, stopped.leaseDone + // The resource owner performs shutdown. The lease callback waits for this + // exact drain; it cannot ACK a merely requested or failed close. + h.FenceWorkspaceLease() + var drainErr error + drainErr = errors.Join(drainErr, stopSnapshotOperationsForShutdown(status)) + if leaseStop != nil && durableProv != nil { + drainErr = errors.Join(drainErr, durableProv.Backend(f.volumeID).StopIO(leaseStop.ctx, "workspace lease fenced")) + } + h.SetFrontendTargets(nil) + // The ublk device drains with the other frontends: its Close (STOP_DEV, + // queue join, DEL_DEV) is part of the drain the lease ACK waits for. + if ublkTarget != nil { + drainErr = errors.Join(drainErr, ublkTarget.Close()) + } + if nvmeTarget != nil { + if status != nil { + status.SetNVMeListenerReady(false) + } + drainErr = errors.Join(drainErr, nvmeTarget.Close()) + } + if iscsiTarget != nil { + drainErr = errors.Join(drainErr, iscsiTarget.Close()) + } + // Tear down replication BEFORE durable storage close (LIFO + // listener lifecycle). Listener closes its accept loop + + // in-flight handler conns; ReplicationVolume closes its outbound + // peer connections. Both borrow LogicalStorage that + // durableProv.Close will release; tearing them down first + // prevents use-after-free on the storage handle. + if replListen != nil { + replListen.Stop() + } + if replVolume != nil { + drainErr = errors.Join(drainErr, replVolume.Close()) + } + // A detached HEAD is stable until a higher grant. Read it while the + // attachment identity is still available, then ACK only after Close succeeds. + var detachedGen uint64 + if leaseStop != nil && drainErr == nil && workspaceLayoutHead != nil { + var me layout.HolderID + me, drainErr = durableProv.LayoutHolder(leaseStop.ctx, leaseStop.id.VolumeId) + if drainErr == nil { + detachedGen, drainErr = workspaceLayoutDetachedGeneration(leaseStop.ctx, workspaceLayoutHead, leaseStop.id, me) + } + } + // T3b: close DurableProvider in correct order — Provider.Close + // closes backends first (flags them closed) then storage files + // (releases fd + final fsync). + if durableProv != nil { + drainErr = errors.Join(drainErr, closeProviderAfterSnapshotOperations(status, durableProv.Close)) + } + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + if leaseStop != nil { + gen := detachedGen + if drainErr == nil && workspaceLayoutHead == nil { + drainErr = errors.New("workspace layout HEAD unavailable for detached proof") + } + leaseStop.reply <- workspaceStopResult{gen: gen, err: drainErr} + } + finishWorkspaceLease(exits, f, h, leaseDone) + if err := h.Close(); err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: close:", err) + return 1 + } + return 0 +} + +func shouldPublishNVMeFrontendTarget(transport string) bool { + return transport == "tcp" || transport == "rdma" +} + +func nvmeRDMATargetStartFailureReason(err error) string { + message := err.Error() + switch { + case strings.Contains(message, "port ID already exists"): + return "rdma_port_conflict" + case strings.Contains(message, "subsystem already exists"): + return "rdma_subsystem_conflict" + case strings.Contains(message, "cannot assign requested address"): + return "rdma_bind_address_unassigned" + case strings.Contains(message, "permission denied"), strings.Contains(message, "kernel target requires root"): + return "rdma_target_permission_denied" + default: + return "rdma_target_start_failed" + } +} + +func nvmeFrontendCapabilities(nvmeListen, selectedTransport string, listenerStarted bool) []volume.FrontendTransportCapability { + return nvmeFrontendCapabilitiesWithRDMAPreflight(nvmeListen, selectedTransport, listenerStarted, nvmeRDMAPreflightFacts(nvmeListen)) +} + +func nvmeFrontendCapabilitiesWithRDMAPreflight(nvmeListen, selectedTransport string, listenerStarted bool, rdmaFacts []volume.FrontendTransportPreflightFact) []volume.FrontendTransportCapability { + tcpStarted := listenerStarted && nvmeListen != "" && selectedTransport == "tcp" + rdmaSelected := selectedTransport == "rdma" + rdmaStarted := listenerStarted && nvmeListen != "" && rdmaSelected && nvmerdma.Implemented() + rdmaStart := nvmeRDMAListenerStartDecision(rdmaSelected, rdmaFacts) + rdmaReason := "nvme_rdma_transport_unsupported" + if rdmaStarted { + rdmaReason = "implemented" + } + return []volume.FrontendTransportCapability{ + { + Protocol: "nvme", + Transport: "tcp", + Supported: true, + ListenerImplemented: true, + ListenerStarted: tcpStarted, + StartAllowed: true, + StartReason: "implemented", + Reason: "implemented", + }, + { + Protocol: "nvme", + Transport: "rdma", + Supported: rdmaStarted, + ListenerImplemented: nvmerdma.Implemented(), + ListenerStarted: rdmaStarted, + StartAllowed: rdmaStart.allowed, + StartReason: rdmaStart.reason, + Reason: rdmaReason, + Preflight: append([]volume.FrontendTransportPreflightFact(nil), rdmaFacts...), + }, + } +} + +type nvmeRDMAListenerStart struct { + allowed bool + reason string +} + +func nvmeRDMAListenerStartDecision(enabled bool, facts []volume.FrontendTransportPreflightFact) nvmeRDMAListenerStart { + if !enabled { + return nvmeRDMAListenerStart{allowed: false, reason: "nvme_rdma_listener_disabled"} + } + for _, fact := range facts { + // nvme-rdma is an initiator module. Keep it visible as a host fact, but + // do not require it on a target that serves through nvmet-rdma. + if fact.Name == "nvme_rdma_module" { + continue + } + if !fact.Available { + return nvmeRDMAListenerStart{allowed: false, reason: fact.Reason} + } + } + if !nvmerdma.Implemented() { + return nvmeRDMAListenerStart{allowed: false, reason: "nvme_rdma_transport_unsupported"} + } + return nvmeRDMAListenerStart{allowed: true, reason: "implemented"} +} + +func nvmeRDMAPreflightFacts(nvmeListen string) []volume.FrontendTransportPreflightFact { + return []volume.FrontendTransportPreflightFact{ + nvmeRDMAModuleFact(), + kernelModuleFact("nvmet-rdma", "nvmet_rdma_module"), + kernelModuleFact("nbd", "nbd_module"), + rdmaDeviceFact(), + rdmaBindAddressFact(nvmeListen), + configFSFact(), + } +} + +func nvmeRDMAModuleFact() volume.FrontendTransportPreflightFact { + return kernelModuleFact("nvme-rdma", "nvme_rdma_module") +} + +func kernelModuleFact(module, factName string) volume.FrontendTransportPreflightFact { + sysName := strings.ReplaceAll(module, "-", "_") + if _, err := os.Stat("/sys/module/" + sysName); err == nil { + return volume.FrontendTransportPreflightFact{Name: factName, Available: true, Reason: factName + "_loaded"} + } + if data, err := os.ReadFile("/proc/modules"); err == nil && strings.Contains(string(data), sysName+" ") { + return volume.FrontendTransportPreflightFact{Name: factName, Available: true, Reason: factName + "_loaded"} + } + if err := exec.Command("modinfo", module).Run(); err == nil { + return volume.FrontendTransportPreflightFact{Name: factName, Available: true, Reason: factName + "_available"} + } + return volume.FrontendTransportPreflightFact{Name: factName, Available: false, Reason: factName + "_missing"} +} + +func configFSFact() volume.FrontendTransportPreflightFact { + if _, err := os.Stat("/sys/kernel/config"); err == nil { + return volume.FrontendTransportPreflightFact{Name: "configfs", Available: true, Reason: "configfs_available"} + } + return volume.FrontendTransportPreflightFact{Name: "configfs", Available: false, Reason: "configfs_missing"} +} + +func rdmaDeviceFact() volume.FrontendTransportPreflightFact { + entries, err := os.ReadDir("/sys/class/infiniband") + if err != nil || len(entries) == 0 { + return volume.FrontendTransportPreflightFact{Name: "rdma_device", Available: false, Reason: "rdma_device_missing"} + } + names := make([]string, 0, len(entries)) + for _, entry := range entries { + names = append(names, entry.Name()) + } + return volume.FrontendTransportPreflightFact{Name: "rdma_device", Available: true, Reason: "rdma_device_present", Detail: strings.Join(names, ",")} +} + +func rdmaBindAddressFact(listen string) volume.FrontendTransportPreflightFact { + host := listen + if h, _, err := net.SplitHostPort(listen); err == nil { + host = h + } + host = strings.Trim(host, "[]") + ip := net.ParseIP(host) + if ip == nil || ip.IsUnspecified() || ip.IsLoopback() { + return volume.FrontendTransportPreflightFact{Name: "rdma_bind_address", Available: false, Reason: "rdma_bind_address_invalid", Detail: host} + } + return volume.FrontendTransportPreflightFact{Name: "rdma_bind_address", Available: true, Reason: "rdma_bind_address_candidate", Detail: host} +} + +func waitFaultedDurableRecovery(stop <-chan struct{}, h *volume.Host, status *volume.StatusServer, durableProv *durable.DurableProvider, evidence string) int { + fmt.Fprintln(os.Stderr, "blockvolume: durable recovery faulted; status endpoint remains available and local readiness remains blocked:", evidence) + <-stop + + if durableProv != nil { + _ = closeProviderAfterSnapshotOperations(status, durableProv.Close) + } + if status != nil { + shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = status.Close(shutCtx) + shutCancel() + } + if err := h.Close(); err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: close:", err) + return 1 + } + return 0 +} + +// deriveDualLaneAddr maps "host:port" → "host:port+1". Per +// docs/recovery-wiring-plan.md §4 Option A: dual-lane traffic uses a +// separate port from the legacy data port via this fixed convention. +// Production may eventually carry a separate dual-lane field in +// AssignmentFact; until then, all daemons must agree on this offset. +func deriveDualLaneAddr(addr string) (string, error) { + host, portStr, err := net.SplitHostPort(addr) + if err != nil { + return "", fmt.Errorf("split %q: %w", addr, err) + } + port, err := strconv.Atoi(portStr) + if err != nil { + return "", fmt.Errorf("port %q not numeric: %w", portStr, err) + } + if port+1 > 65535 { + return "", fmt.Errorf("port %d+1 overflows", port) + } + return net.JoinHostPort(host, strconv.Itoa(port+1)), nil +} + +// replicaFloorPath is where the replica's epoch floor record lives (G1): +// beside the volume's durable files, or "" for non-durable memback runs. +// hostConfig is the volume host's configuration from the flags. +func hostConfig(f flags, readyCh chan<- adapter.AssignmentInfo) volume.Config { + var ident storeident.Identity + if f.durableRoot != "" { + ident = storeident.Of(f.durableRoot) + } + return volume.Config{ + MasterAddr: f.masterAddr, + AckProfile: strings.ReplaceAll(f.replicationAck, "-", "_"), + LinesNameTheirProcess: true, + ServerID: f.serverID, + VolumeID: f.volumeID, + ReplicaID: f.replicaID, + DataAddr: f.dataAddr, + CtrlAddr: f.ctrlAddr, + HeartbeatInterval: f.hbInterval, + RecoverTimeout: f.recoverTimeout, + ReadyMarker: readyCh, + EnableT1Readiness: f.enableT1Readiness, + WorkspaceLease: f.workspaceLease, + RF1Only: rf1Only(f), + StorageIdentity: ident, + } +} + +// epochTablePath is where the volume's epoch table lives, beside the floor +// record ("" for non-durable memback runs: in memory only). +func epochTablePath(f flags) string { + if f.durableRoot == "" { + return "" + } + return filepath.Join(f.durableRoot, f.volumeID+".epoch-table") +} + +func replicaFloorPath(f flags) string { + if f.durableRoot == "" { + return "" + } + return filepath.Join(f.durableRoot, f.volumeID+".replica-floor") +} diff --git a/seaweed-block/cmd/blockvolume/maintenance_status_test.go b/seaweed-block/cmd/blockvolume/maintenance_status_test.go new file mode 100644 index 0000000000..f20edbd6e6 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/maintenance_status_test.go @@ -0,0 +1,333 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" + "os" + "path" + "path/filepath" + "reflect" + "strings" + "sync/atomic" + "testing" + "time" +) + +type maintenanceDiagnosticFiler struct { + chunkstore.Filer + fail atomic.Bool + absent bool +} + +func (f *maintenanceDiagnosticFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if name == layout.HeadName && f.fail.Swap(false) { + if f.absent { + return nil, chunkstore.ErrNotFound + } + return nil, errors.New("diagnostic read unavailable") + } + return f.Filer.LookupEntry(ctx, dir, name) +} + +type maintenanceDiagnosticCleaner struct { + layoutCleaner + filer *maintenanceDiagnosticFiler +} + +func (c maintenanceDiagnosticCleaner) Clean(ctx context.Context, run func(context.Context, layout.HolderID, string) error) error { + return c.layoutCleaner.Clean(ctx, func(ctx context.Context, me layout.HolderID, s string) error { + c.filer.fail.Store(true) + return run(ctx, me, s) + }) +} + +func maintenanceJSON(t *testing.T, p *durable.DurableProvider) map[string]any { + t.Helper() + b, err := json.Marshal(p.DurableStatuses()) + if err != nil { + t.Fatal(err) + } + var v []map[string]any + if err = json.Unmarshal(b, &v); err != nil { + t.Fatal(err) + } + c := v[0]["Chunk"].(map[string]any) + m, ok := c["Maintenance"].(map[string]any) + if !ok { + t.Fatalf("maintenance loop has no status: %s", b) + } + return m +} + +func TestMaintenanceStatusRealPassAndTimeout(t *testing.T) { + for _, kind := range []string{"completed", "reachable", "metadata-only", "head-unread", "head-absent", "retention-only", "newer-pending-work", "timeout"} { + t.Run(kind, func(t *testing.T) { + timeout := kind == "timeout" + ctx := context.Background() + fixture := testutil.NewLayoutFixture(t, "v1", 256, 16) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16, ChunkMaintenanceInterval: time.Hour, ChunkMaintenanceTimeout: 100 * time.Millisecond, ChunkStagger: true} + fixture.Configure(&cfg) + var p *durable.DurableProvider + diagnosticFiler := &maintenanceDiagnosticFiler{Filer: fixture.Filer, absent: kind == "head-absent"} + maintenanceCatalog := fixture.Catalog + if kind == "head-unread" || kind == "head-absent" { + var e error + maintenanceCatalog, e = chunkstore.NewBCatalog(diagnosticFiler, fixture.Blobs, "/provider-test") + if e != nil { + t.Fatal(e) + } + } + entered, release := make(chan struct{}), make(chan struct{}) + var cleanerRequests atomic.Int32 + var orphanPaths []string + pass := newChunkMaintenance(maintenanceCatalog, fixture.Ref, func(ctx context.Context) (layoutCleaner, error) { + cleanerRequests.Add(1) + r, e := p.LayoutRemote(ctx, "v1") + if e != nil { + return nil, e + } + if kind == "head-unread" || kind == "head-absent" { + return maintenanceDiagnosticCleaner{layoutCleaner: r.(layoutCleaner), filer: diagnosticFiler}, nil + } + return r.(layoutCleaner), nil + }, kind != "retention-only", time.Now) + cfg.ChunkMaintenance = func(ctx context.Context, v string) error { + close(entered) + if timeout { + <-ctx.Done() + return ctx.Err() + } + select { + case <-release: + case <-ctx.Done(): + return ctx.Err() + } + return pass(ctx, v) + } + var err error + p, err = durable.NewDurableProvider(cfg, cleaningView{}) + if err != nil { + t.Fatal(err) + } + defer p.Close() + if _, err = p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + m := maintenanceJSON(t, p) + if m["passesOk"] != float64(0) || m["inProgress"] != false || m["currentStartNs"] != float64(0) || m["lastPass"] != nil { + t.Fatalf("initial=%v", m) + } + if !timeout { + st, e := fixture.Catalog.Store(fixture.Ref) + if e != nil { + t.Fatal(e) + } + data := bytes.Repeat([]byte{99}, 4096) + if e = fixture.Filer.CreateEntry(ctx, path.Join("/provider-test", fixture.Ref.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); e != nil { + t.Fatal(e) + } + chunk := layout.NameChunk(0, data) + if kind != "metadata-only" { + if e = layout.EnsureObject(ctx, st, chunk.Path(), data, "ended-session"); e != nil { + t.Fatal(e) + } + orphanPaths = append(orphanPaths, chunk.Path()) + } + root, segs, e := layout.Build(map[uint64]layout.Ref{0: {Owner: fixture.Ref.Name, OwnerID: fixture.Ref.ID, Chunk: chunk}}) + if e != nil { + t.Fatal(e) + } + rn, e := layout.PrepareRoot(ctx, st, root, segs, "ended-session") + if e != nil { + t.Fatal(e) + } + orphanPaths = append(orphanPaths, rn.Path()) + for sn := range segs { + orphanPaths = append(orphanPaths, sn.Path()) + } + } + if kind == "reachable" { + local, e := p.EnsureStorage("v1") + if e != nil { + t.Fatal(e) + } + if _, e = local.Write(0, bytes.Repeat([]byte{42}, 4096)); e != nil { + t.Fatal(e) + } + if _, e = local.Sync(); e != nil { + t.Fatal(e) + } + if _, e = p.CaptureVolume(ctx, "v1"); e != nil { + t.Fatal(e) + } + } + before, _, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil { + t.Fatal(err) + } + if kind == "newer-pending-work" { + // Simulate bytes persisted by a future producer, not a v1.1 producer path. + st, e := fixture.Catalog.Store(fixture.Ref) + if e != nil { + t.Fatal(e) + } + before.Version = layout.HeadVersion1 + before.Lists = []layout.ListCursor{{Ref: layout.ListRef{Hash: layout.Sum([]byte("future pending page")).String(), Pages: 1}, Kind: layout.ListUploadIntent, Producer: "future", Generation: 1}} + if e = st.UpdateHead(ctx, before.Gen, before, layout.CauseCommit); e != nil { + t.Fatal(e) + } + before, _, err = fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil { + t.Fatal(err) + } + } + if !p.KickMaintenance("v1") { + t.Fatal("kick refused") + } + select { + case <-entered: + case <-time.After(time.Second): + t.Fatal("not entered") + } + m = maintenanceJSON(t, p) + if m["inProgress"] != true || m["currentStartNs"].(float64) <= 0 { + t.Fatalf("running=%v", m) + } + if !timeout { + close(release) + } + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + m = maintenanceJSON(t, p) + if m["lastPass"] != nil { + break + } + time.Sleep(time.Millisecond) + } + last, ok := m["lastPass"].(map[string]any) + if !ok { + t.Fatalf("no completion: %v", m) + } + if m["inProgress"] != false || m["currentStartNs"] != float64(0) || last["atNs"].(float64) <= 0 { + t.Fatalf("ended=%v", m) + } + if timeout { + if m["passesOk"] != float64(0) || last["error"] == "" { + t.Fatalf("timeout=%v", m) + } + return + } + after, _, err := fixture.Catalog.ReadHead(ctx, fixture.Ref) + if err != nil { + t.Fatal(err) + } + if kind == "retention-only" { + if cleanerRequests.Load() != 0 || !reflect.DeepEqual(before, after) || m["passesOk"] != float64(1) || last["headGen"] != float64(0) || last["error"] != "" { + t.Fatalf("retention reported a clean: requests=%d status=%v", cleanerRequests.Load(), m) + } + st, e := fixture.Catalog.Store(fixture.Ref) + if e != nil { + t.Fatal(e) + } + for _, name := range orphanPaths { + _, found, e := st.Stat(ctx, name) + if e != nil || !found { + t.Fatalf("retention-only removed %s: found=%t err=%v", name, found, e) + } + } + // The shared fixture is produced by the real callback/status projection; + // normalize only its already-checked wall-clock end timestamp. + last["atNs"] = float64(1) + raw, e := os.ReadFile(filepath.Join("testdata", "maintenance-retention-only.json")) + if e != nil { + t.Fatal(e) + } + var want map[string]any + if e = json.Unmarshal(raw, &want); e != nil { + t.Fatal(e) + } + if !reflect.DeepEqual(m, want) { + t.Fatalf("retention-only contract changed: got=%v want=%v", m, want) + } + return + } + if kind == "newer-pending-work" { + if last["skipReason"] != "newer_pending_work" || !reflect.DeepEqual(before.Lists, after.Lists) { + t.Fatalf("reserved work silently skipped or consumed: status=%v lists=%v", last, after.Lists) + } + } else if _, present := last["skipReason"]; present { + t.Fatalf("unexpected skip reason: %v", last) + } + expectedGen := before.Gen + 1 + if kind == "head-unread" || kind == "head-absent" { + expectedGen = 0 + if last["error"] != "" || !strings.Contains(last["headGenError"].(string), "HEAD generation not read") { + t.Fatalf("missing diagnostic: %v", last) + } + if kind == "head-absent" && last["headGenError"] != "HEAD generation not read: HEAD absent" { + t.Fatalf("missing absent-HEAD diagnostic: %v", last) + } + } else if last["error"] != "" || last["headGenError"] != "" { + t.Fatalf("unexpected error: %v", last) + } + if after.Gen != before.Gen+2 || m["passesOk"] != float64(1) || last["headGen"].(float64) != float64(expectedGen) { + t.Fatalf("before=%d after=%d status=%v", before.Gen, after.Gen, m) + } + total, chunks := float64(3), float64(1) + if kind == "metadata-only" { + total, chunks = 2, 0 + } + plannedTotal, plannedChunks, plannedRoots, plannedSegments := total, chunks, float64(1), float64(1) + if kind == "reachable" { + plannedTotal, plannedChunks, plannedRoots, plannedSegments = 6, 2, 2, 2 + } + if last["plannedChunks"] != plannedChunks || last["plannedRoots"] != plannedRoots || last["plannedSegments"] != plannedSegments || last["planned"] != plannedTotal || last["removed"] != total || last["removedChunks"] != chunks || last["removedRoots"] != float64(1) || last["removedSegments"] != float64(1) { + t.Fatalf("object counts=%v", last) + } + if _, ok := last["planned"]; !ok { + t.Fatal("planned absent") + } + if _, ok := last["removed"]; !ok { + t.Fatal("removed absent") + } + }) + } +} + +func TestMaintenanceStatusAbsentWithoutLoop(t *testing.T) { + fixture := testutil.NewLayoutFixture(t, "v1", 256, 16) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16} + fixture.Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, cleaningView{}) + if err != nil { + t.Fatal(err) + } + defer p.Close() + if _, err = p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + b, err := json.Marshal(p.DurableStatuses()) + if err != nil { + t.Fatal(err) + } + var v []map[string]any + if err = json.Unmarshal(b, &v); err != nil { + t.Fatal(err) + } + if _, exists := v[0]["Chunk"].(map[string]any)["Maintenance"]; exists { + t.Fatalf("disabled loop exposed Maintenance") + } +} diff --git a/seaweed-block/cmd/blockvolume/master_crash_integration_test.go b/seaweed-block/cmd/blockvolume/master_crash_integration_test.go new file mode 100644 index 0000000000..85c71745b9 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/master_crash_integration_test.go @@ -0,0 +1,98 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "errors" + "os/exec" + "strings" + "syscall" + "testing" + "time" +) + +// This kills the master after the move answer, before the target starts. +// It tests an issued move's recovery, not a kill inside a persistence syscall. +func TestProcedureMasterKilledAfterMoveBeforeTargetStarts(t *testing.T) { + env := startHandoffEnv(t, 3) + must, mustU := fatalOn(t) + old := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, old, "s1") + block := pattern("master-move-test") + env.writeBlock(t, "s1", 0, block) + g := env.seal(t, "s1", e) + l := env.sealedLSN(t, e, g) + env.revoke(t, e, g) + must(old.wait(30 * time.Second)) + env.waitAck(t, e, g) + + args := env.moveClean(e, "s2", "move-v1-1") + out, _ := env.h.command(t, args...) + e2 := mustU(movedEpochTo(out, e, g, l, "s2")) + restartKilledMaster(t, env) + // The same request must recover the issued epoch, not issue another one. + out, _ = env.h.command(t, args...) + if replay := mustU(movedEpochTo(out, e, g, l, "s2")); replay != e2 { + t.Fatalf("replayed move issued epoch %d; original was %d", replay, e2) + } + for _, conflict := range []struct{ target, request string }{ + {"s2", "different-request"}, {"s3", "different-target"}, + } { + out, stderr, code := env.h.run(t, env.moveClean(e, conflict.target, conflict.request)...) + if code != 1 || out != "" || strings.TrimSpace(stderr) != "workspace move: clean move: workspace move: missing or changed authority/lease" { + t.Fatalf("competing move to %s: exit=%d stdout=%q stderr=%q; want the definite-refusal exit and changed-authority answer", conflict.target, code, out, stderr) + } + } + out, _ = env.h.command(t, env.chunkShow()...) + if got := mustU(sealedLayoutHeadPosition(out, e, g)); got != l { + t.Fatalf("sealed HEAD LSN %d; want %d", got, l) + } + nw := env.start(t, "blockvolume-s2", "s2") + if got := env.adopt(t, nw, "s2"); got != e2 { + t.Fatalf("target adopted epoch %d; want recovered epoch %d", got, e2) + } + // Planned hand-over step 8 observes the completed layout claim in HEAD: + // its identity advanced while the sealed image and position were kept. + out, _ = env.h.command(t, env.chunkShow()...) + must(checkLayoutHeadReopenedBy(out, e2, g, l, "s2")) + if !bytes.Equal(env.readBlock(t, "s2", 0), block) { + t.Fatal("acknowledged source block changed after master crash and move recovery") + } + if !bytes.Equal(env.readBlock(t, "s2", 8), make([]byte, 4096)) { + t.Fatal("unwritten target block is not zero") + } + // A returning source must not adopt or serve the issued target's line. + returning := env.start(t, "blockvolume-s1-returning", "s1") + poll(t, 45*time.Second, "returning old holder did not exit", func() bool { + if returning.has("adopted as PRIMARY") || env.servingNow("s1") { + t.Fatal("returning old holder adopted or served after the issued move") + } + select { + case <-returning.done: + return true + default: + return false + } + }) + code := exitCode(returning.err) + if (code != 75 && code != 78) || !returning.has("blockvolume: exiting status=") { + t.Fatalf("returning old holder exit=%v without the documented retry/no-retry exit line", returning.err) + } + +} + +func restartKilledMaster(t *testing.T, env *handoffEnv) { + t.Helper() + env.masterProcess.kill(t) + var exit *exec.ExitError + if !errors.As(env.masterProcess.err, &exit) { + t.Fatalf("master exit %v; want SIGKILL", env.masterProcess.err) + } + if ws, ok := exit.Sys().(syscall.WaitStatus); !ok || !ws.Signaled() || ws.Signal() != syscall.SIGKILL { + t.Fatalf("master status %v; want SIGKILL", exit.Sys()) + } + t.Log("blockmaster confirmed dead by SIGKILL before restart") + env.masterProcess = env.h.start(t, "blockmaster-restarted", env.h.master, env.masterArgs...) + env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") +} diff --git a/seaweed-block/cmd/blockvolume/master_loss_integration_test.go b/seaweed-block/cmd/blockvolume/master_loss_integration_test.go new file mode 100644 index 0000000000..7fded6b97d --- /dev/null +++ b/seaweed-block/cmd/blockvolume/master_loss_integration_test.go @@ -0,0 +1,227 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "fmt" + "io" + "net" + "os" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// Coverage cells A2.24, A2.27 and A2.35: the holder loses its master while it +// is alive, two ways: its connections are closed (renewals fail at once), or +// they stay open and every byte is dropped (each renewal hangs until its own +// 2 s timeout: the guard's stalled-renewal path). Either way the holder exits +// 75 for lease_expired before a forced move is admitted, and the target then +// serves the cut block. Administrative calls still reach the real master. +func TestProcedureMasterUnreachableFencesBeforeForcedMove(t *testing.T) { + t.Run("connections closed", func(t *testing.T) { masterLoss(t, false) }) + t.Run("silent drop", func(t *testing.T) { masterLoss(t, true) }) +} + +func masterLoss(t *testing.T, silent bool) { + env := startHandoffEnv(t, 2) + proxy, disconnect, drop := holderMasterProxy(t, env.h.masterAddr) + args := env.volArgs("s1") + for i := range args { + if args[i] == "--master" { + args[i+1] = proxy + } + } + old := env.h.start(t, "blockvolume-s1-partition", env.h.volume, args...) + e := env.adopt(t, old, "s1") + block := pattern("master-loss-kept") + env.writeBlock(t, "s1", 0, block) + // Install a known remote point before losing the master, so the target's + // read proves data preservation without promising unpublished WAL data. + env.h.command(t, "ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status, "--timeout", "120s") + env.requireHeadHolder(t, e, "s1") + if silent { + drop() + } else { + disconnect() + } + b := env.hosts["s2"] + move := []string{"ops", "workspace", "force-move", "--master", env.h.masterAddr, "--volume", "v1", + "--target-host", b.id, "--target-data", b.data, "--target-ctrl", b.ctrl, "--request-id", "master-loss-move", + "--confirm-forced", fmt.Sprintf("v1@%d", e)} + refusedWhileAlive := false + poll(t, 90*time.Second, "forced move never admitted after holder lost master", func() bool { + exitedBeforePreview := false + select { + case <-old.done: + exitedBeforePreview = true + default: + } + out, _ := env.h.command(t, append(append([]string{}, move...), "--dry-run")...) + if previewAdmitted(out) { + if !exitedBeforePreview { + t.Fatal("forced move admitted before the live holder's exit was observed") + } + return true + } + if !exitedBeforePreview { + refusedWhileAlive = true + } + return false + }) + if !refusedWhileAlive { + t.Fatal("no forced-move refusal observed while the disconnected holder was alive") + } + if err := old.wait(time.Second); exitCode(err) != 75 { + t.Fatalf("master-lost holder exited %v; want75", err) + } + if !old.has("reason=lease_expired") { + t.Fatal("holder exit lacks affirmative lease_expired reason") + } + if silent { + // The stalled-renewal path: a renewal ran to its own timeout, then the + // guard fenced, then the process exited for the expired lease. + requireLogOrder(t, old, "the call reached the 2s renewal timeout", "workspace lease: fenced", "reason=lease_expired") + } + if listening(env.hosts["s1"].nvme) { + t.Fatal("exited holder still has a frontend listener") + } + out, _ := env.h.command(t, move...) + _, mustU := fatalOn(t) + e2 := mustU(forcedEpoch(out, e, "s1", "s2")) + nw := env.start(t, "blockvolume-s2-after-partition", "s2") + if got := env.adopt(t, nw, "s2"); got != e2 { + t.Fatalf("target epoch%d; want%d", got, e2) + } + if !bytes.Equal(env.readBlock(t, "s2", 0), block) { + t.Fatal("target lost the confirmed-cut block") + } +} + +// requireLogOrder requires each of lines to appear in d's log, each after the +// one before it. +func requireLogOrder(t *testing.T, d *daemon, lines ...string) { + t.Helper() + data, _ := os.ReadFile(d.log) + at := 0 + for _, l := range lines { + i := strings.Index(string(data)[at:], l) + if i < 0 { + t.Fatalf("%s: %q missing, or not after the lines before it (%q)", d.name, l, lines) + } + at += i + len(l) + } +} + +// holderMasterProxy forwards real TCP bytes until disconnect closes every +// accepted connection and the listener, or until drop makes it a silent +// black hole: every connection, open or new, stays open and its bytes are +// read and discarded in both directions, so a call sent through it gets no +// answer until its own timeout. Closing a port or dropping bytes is the +// injected failure, never the evidence used to pass the lease/exit +// assertion. +func holderMasterProxy(t *testing.T, target string) (string, func(), func()) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + var mu sync.Mutex + var wg sync.WaitGroup + var once sync.Once + closed := false + var dropping atomic.Bool + conns := map[net.Conn]bool{} + // forward copies src to dst until src ends, discarding the bytes while + // dropping. + forward := func(dst, src net.Conn) { + buf := make([]byte, 32<<10) + for { + n, err := src.Read(buf) + if n > 0 && !dropping.Load() { + if _, werr := dst.Write(buf[:n]); werr != nil { + return + } + } + if err != nil { + return + } + } + } + acceptDone := make(chan struct{}) + stop := func() { + once.Do(func() { + mu.Lock() + closed = true + _ = ln.Close() + for c := range conns { + _ = c.Close() + } + mu.Unlock() + }) + } + t.Cleanup(func() { + stop() + select { + case <-acceptDone: + case <-time.After(5 * time.Second): + t.Error("proxy accept did not end") + } + joined := make(chan struct{}) + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("proxy connections did not end") + } + }) + go func() { + defer close(acceptDone) + for { + client, err := ln.Accept() + if err != nil { + return + } + mu.Lock() + if closed { + mu.Unlock() + _ = client.Close() + continue + } + conns[client] = true + wg.Add(1) + mu.Unlock() + go func() { + defer wg.Done() + defer func() { mu.Lock(); delete(conns, client); mu.Unlock(); _ = client.Close() }() + if dropping.Load() { // a new connection into the black hole: held open, never answered + _, _ = io.Copy(io.Discard, client) + return + } + server, err := net.DialTimeout("tcp", target, 2*time.Second) + if err != nil { + return + } + mu.Lock() + if closed { + mu.Unlock() + _ = server.Close() + return + } + conns[server] = true + mu.Unlock() + defer func() { mu.Lock(); delete(conns, server); mu.Unlock(); _ = server.Close() }() + copied := make(chan struct{}) + go func() { forward(server, client); _ = server.Close(); close(copied) }() + forward(client, server) + _ = client.Close() + _ = server.Close() + <-copied + }() + } + }() + return ln.Addr().String(), stop, func() { dropping.Store(true) } +} diff --git a/seaweed-block/cmd/blockvolume/master_tls.go b/seaweed-block/cmd/blockvolume/master_tls.go new file mode 100644 index 0000000000..780b4914ce --- /dev/null +++ b/seaweed-block/cmd/blockvolume/master_tls.go @@ -0,0 +1,48 @@ +package main + +import ( + "crypto/tls" + "crypto/x509" + "fmt" + + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc" +) + +// checkMasterTLS checks the master link's mutual-TLS flags at start (phase +// 0): all three files load; the node certificate's CN equals --server-id +// (one node certificate per server id; the master enforces the same rule +// through the role file); and an authenticated volume never listens off +// loopback. +func checkMasterTLS(f flags) error { + if !f.masterTLS.Enabled() { + return nil + } + if err := f.masterTLS.Check(); err != nil { + return fmt.Errorf("--master-tls-cert/--master-tls-key/--master-ca: %w", err) + } + pair, err := tls.LoadX509KeyPair(f.masterTLS.Cert, f.masterTLS.Key) + if err != nil { + return err + } + leaf, err := x509.ParseCertificate(pair.Certificate[0]) + if err != nil { + return fmt.Errorf("--master-tls-cert %s: %w", f.masterTLS.Cert, err) + } + if leaf.Subject.CommonName != f.serverID { + return fmt.Errorf("--master-tls-cert %s has CN=%q but --server-id is %q: a node certificate names its server id; issue one with CN=%s", f.masterTLS.Cert, leaf.Subject.CommonName, f.serverID, f.serverID) + } + if f.allowExternalStatusBind { + return fmt.Errorf("--allow-external-status-bind cannot be combined with --master-tls-cert: an authenticated volume's status listener stays on loopback") + } + return nil +} + +// masterDialTLS is the master link's dial option: mutual TLS when the flags +// name the files, nil (development-mode plaintext) otherwise. +func masterDialTLS(f flags) (grpc.DialOption, error) { + if !f.masterTLS.Enabled() { + return nil, nil + } + return link.ClientCredentials(f.masterTLS, "") +} diff --git a/seaweed-block/cmd/blockvolume/master_tls_test.go b/seaweed-block/cmd/blockvolume/master_tls_test.go new file mode 100644 index 0000000000..7ec156fda9 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/master_tls_test.go @@ -0,0 +1,44 @@ +package main + +import ( + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth/authtest" +) + +// Phase 0: the volume's master-link TLS flags are checked at start: a node +// certificate whose CN differs from --server-id, a partial set, or TLS with +// --allow-external-status-bind refuses the start with a cure line. +func TestMasterTLSFlags(t *testing.T) { + ca := authtest.NewCA(t, "ca") + dir := t.TempDir() + caPath := ca.WriteCA(t, dir) + good, goodKey := ca.Issue(t, "node-b", time.Now().Add(time.Hour)).WriteFiles(t, dir, "node-b") + other, otherKey := ca.Issue(t, "s9", time.Now().Add(time.Hour)).WriteFiles(t, dir, "s9") + base := append(phase150RequiredBlockvolumeArgs(), "--server-id=node-b") // the last --server-id wins + for _, c := range []struct { + name string + args []string + want string // "" = accepted + }{ + {"no TLS (development mode)", nil, ""}, + {"CN equals --server-id", []string{"--master-tls-cert", good, "--master-tls-key", goodKey, "--master-ca", caPath}, ""}, + {"CN differs from --server-id", []string{"--master-tls-cert", other, "--master-tls-key", otherKey, "--master-ca", caPath}, `CN="s9" but --server-id is "node-b"`}, + {"no CA", []string{"--master-tls-cert", good, "--master-tls-key", goodKey}, "a certificate, its key and a CA"}, + {"with --allow-external-status-bind", []string{"--master-tls-cert", good, "--master-tls-key", goodKey, "--master-ca", caPath, "--allow-external-status-bind"}, "cannot be combined"}, + } { + f, err := parseFlags(append(append([]string{}, base...), c.args...)) + switch { + case c.want == "" && err != nil: + t.Errorf("%s: %v; want accepted", c.name, err) + case c.want != "" && (err == nil || !strings.Contains(err.Error(), c.want)): + t.Errorf("%s: %v; want an error naming %q", c.name, err, c.want) + case c.want == "" && c.args != nil: + if d, err := masterDialTLS(f); err != nil || d == nil { + t.Errorf("%s: dial option %v %v; want mutual TLS", c.name, d, err) + } + } + } +} diff --git a/seaweed-block/cmd/blockvolume/master_wait_integration_test.go b/seaweed-block/cmd/blockvolume/master_wait_integration_test.go new file mode 100644 index 0000000000..884906e800 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/master_wait_integration_test.go @@ -0,0 +1,549 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "slices" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "os" + "sync" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +type masterWaitView struct { + Reason string + Since time.Time + Until time.Time +} + +// masterWaitOf reads /status MasterWait for v1 (ok false when absent). +func masterWaitOf(statusAddr string) (masterWaitView, bool) { return masterWaitOfVolume(statusAddr, "v1") } + +// masterWaitOfVolume reads /status MasterWait for vol. +func masterWaitOfVolume(statusAddr, vol string) (masterWaitView, bool) { + c := &http.Client{Timeout: 2 * time.Second} + resp, err := c.Get("http://" + statusAddr + "/status?volume=" + vol) + if err != nil { + return masterWaitView{}, false + } + defer resp.Body.Close() + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + var st struct { + MasterWait *struct { + Reason string + SinceMs, UntilMs int64 + } + } + if json.Unmarshal(raw, &st) != nil || st.MasterWait == nil { + return masterWaitView{}, false + } + v := masterWaitView{Reason: st.MasterWait.Reason, Since: time.UnixMilli(st.MasterWait.SinceMs)} + if st.MasterWait.UntilMs != 0 { + v.Until = time.UnixMilli(st.MasterWait.UntilMs) + } + return v, true +} + +func stillRunning(t *testing.T, d *daemon, what string) { + t.Helper() + select { + case <-d.done: + t.Fatalf("%s: %s exited (%v); it must wait", what, d.name, d.err) + default: + } +} + +// waitForBarrier starts a waiting process with the master down, restarts the +// master and returns the process and the barrier time /status shows. +func waitForBarrier(t *testing.T, env *handoffEnv, name string) (*daemon, time.Time) { + t.Helper() + b := env.hosts["s1"] + first := env.start(t, name+"-holder", "s1") + env.adopt(t, first, "s1") + env.masterProcess.kill(t) + if code := exitCode(first.wait(90 * time.Second)); code != 75 { + t.Fatalf("the holder exited %v with the master down; want one fence exit 75", first.err) + } + waiting := env.start(t, name, "s1") + time.Sleep(45 * time.Second) // past the old fixed 30 s wait + stillRunning(t, waiting, "45 s with the master unreachable") + mw, ok := masterWaitOf(b.status) + if !ok || mw.Reason != "unreachable" || !mw.Until.IsZero() || time.Since(mw.Since) < 40*time.Second { + t.Fatalf("/status MasterWait %+v (present %v); want unreachable for 40 s or more, no bound", mw, ok) + } + env.masterProcess = env.h.start(t, name+"-master-back", env.h.master, env.masterArgs...) + env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + var until time.Time + poll(t, 30*time.Second, "/status never showed the master's barrier", func() bool { + mw, ok := masterWaitOf(b.status) + if ok && mw.Reason == "barrier" && !mw.Until.IsZero() { + until = mw.Until + return true + } + return false + }) + waiting.waitLog(t, 10*time.Second, "re-grant refused until") + return waiting, until +} + +// A start that finds blockmaster unreachable waits inside the process with +// no bound (no exit 75 every ~38 s), shows why on /status, and when the +// master returns shows the master's barrier time and serves within 2 s of +// it, without a restart. +func TestMasterRestartShowsBarrierUntil(t *testing.T) { + env := startHandoffEnv(t, 1) + b := env.hosts["s1"] + waiting, until := waitForBarrier(t, env, "bv-wait") + t.Logf("barrier until %s (%v from now)", until.UTC().Format(time.RFC3339Nano), time.Until(until).Round(time.Millisecond)) + deadline := until.Add(2 * time.Second) + for !volumeFrontendReady(b.status, "v1") { + if time.Now().After(deadline.Add(30 * time.Second)) { + t.Fatal("the waiting process never served after the barrier") + } + stillRunning(t, waiting, "after the barrier") + time.Sleep(100 * time.Millisecond) + } + late := time.Since(until) + t.Logf("served %v after the barrier time", late.Round(time.Millisecond)) + if late > 2*time.Second { + t.Fatalf("served %v after the master's barrier time; want <= 2 s", late.Round(time.Millisecond)) + } + if _, ok := masterWaitOf(b.status); ok { + t.Fatal("/status still shows MasterWait while serving") + } +} + +// SIGTERM (systemctl stop) during either wait ends the process with status 0 +// within 10 s: while the master is unreachable, and at the barrier. +func TestStopDuringMasterWaitReturnsPromptly(t *testing.T) { + env := startHandoffEnv(t, 1) + stopIn := func(d *daemon, what string) { + t.Helper() + at := time.Now() + d.term(t, 10*time.Second) + if d.err != nil { + t.Fatalf("%s: exit %v after SIGTERM; want status 0", what, d.err) + } + t.Logf("%s: stopped in %v", what, time.Since(at).Round(time.Millisecond)) + } + waiting, _ := waitForBarrier(t, env, "bv-stop") + stopIn(waiting, "at the barrier") + + env.masterProcess.kill(t) + unreachable := env.start(t, "bv-stop-unreachable", "s1") + poll(t, 30*time.Second, "/status never showed unreachable", func() bool { + mw, ok := masterWaitOf(env.hosts["s1"].status) + return ok && mw.Reason == "unreachable" + }) + stopIn(unreachable, "unreachable") +} + +// A process waiting at the barrier with its cached assignment at e, frozen +// while a forced move gives the line to s2 at e+1, then resumed: the +// master's typed MOVED refusal ends it with exit 78 moved at once. It never +// served. +func TestWaitingVolumeMovedDuringOutageExits78(t *testing.T) { + env := startHandoffEnv(t, 2) + b := env.hosts["s1"] + holder := env.start(t, "bv-moved-holder", "s1") + e := env.adopt(t, holder, "s1") + holder.kill(t) + time.Sleep(35 * time.Second) // the lease has lapsed; the barrier has not + waiting := env.start(t, "bv-moved-waiting", "s1") + poll(t, 30*time.Second, "/status never showed the barrier", func() bool { + mw, ok := masterWaitOf(b.status) + return ok && mw.Reason == "barrier" + }) + if err := waiting.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatal(err) + } + env.forceMove(t, e, "s2", "force-moved-during-wait") + if err := waiting.proc.Signal(syscall.SIGCONT); err != nil { + t.Fatal(err) + } + err := waiting.wait(60 * time.Second) + if code := exitCode(err); code != 78 || !waiting.has("blockvolume: exiting status=78 reason=moved") { + t.Fatalf("the waiting process exit %v; want 78 reason=moved", err) + } + if waiting.has("adopted as PRIMARY") && volumeFrontendReady(b.status, "v1") { + t.Fatal("the moved process served") + } +} + +// A unit for a volume the master does not assign to this host stops: with +// the master answering, the wait is bounded (30 s from contact) and exits +// 75 assignment_timeout, so the unit still reaches its start limit. +func TestObsoleteUnitStopsWithReachableMaster(t *testing.T) { + env := startHandoffEnv(t, 1) + b := env.hosts["s1"] + b.volume, b.root = "v-unknown", t.TempDir() + at := time.Now() + d := env.h.start(t, "bv-obsolete", env.h.volume, env.volArgsFor(b)...) + err := d.wait(2 * time.Minute) + took := time.Since(at) + t.Logf("obsolete unit exited %v after %v", err, took.Round(time.Millisecond)) + if exitCode(err) != 75 || !d.has("reason=assignment_timeout") || took < 25*time.Second { + t.Fatalf("obsolete unit exit %v after %v; want 75 assignment_timeout after the 30 s bound", err, took) + } +} + +// revokeAndExit seals v1 on s1, revokes it at e and waits for the holder's +// clean exit and recorded ACK: the volume is then admissible for delete. +func revokeAndExit(t *testing.T, env *handoffEnv, hostID string, holder *daemon, e uint64) { + t.Helper() + b := env.hosts[hostID] + out, _ := env.h.command(t, "ops", "chunk", "detach", "--plain", "--volume", "v1", "--status-addr", b.status, "--timeout", "120s") + var a struct { + HeadGen uint64 `json:"headGen"` + } + if err := json.Unmarshal([]byte(out), &a); err != nil || a.HeadGen == 0 { + t.Fatalf("plain detach: %v %q", err, out) + } + env.h.command(t, "ops", "workspace", "revoke", "--master", env.h.masterAddr, "--volume", "v1", "--replica", "r1", + "--epoch", fmt.Sprint(e), "--sealed-gen", fmt.Sprint(a.HeadGen)) + if err := holder.wait(30 * time.Second); err != nil { + t.Fatalf("holder after the revocation: %v; want a clean exit", err) + } + poll(t, 30*time.Second, "the ACK was never recorded", func() bool { + out, _ := env.h.command(t, "ops", "workspace", "show", "--master", env.h.masterAddr, "--volume", "v1") + return showsAck(out, e, a.HeadGen) + }) +} + +// A process waiting on its cached assignment while the volume's delete is +// committed exits 78 deleted at once (the master's typed DELETED refusal); +// while the delete is only admitted (abortable) it keeps the bounded wait and +// exits 75 assignment_timeout, never 78. +func TestWaitingVolumeDeletedDuringOutageExits78(t *testing.T) { + t.Run("committed", func(t *testing.T) { + // The waiting s1 process reaches the master through a proxy the test + // cuts: while it cannot reach the master (no bound), the line moves to + // s2, s2 is revoked with an ACK and the delete commits. When the + // proxy returns, the renewal at its cached epoch meets the committed + // deletion. + env := startHandoffEnv(t, 2) + holder := env.start(t, "bv-del-holder", "s1") + e := env.adopt(t, holder, "s1") + holder.kill(t) + px := startMasterProxy(t, env.h.masterAddr) + args := env.volArgs("s1") + for i := range args { + if args[i] == "--master" { + args[i+1] = px.addr + } + } + time.Sleep(35 * time.Second) // the lease lapsed; the barrier has not passed + waiting := env.h.start(t, "bv-del-waiting", env.h.volume, args...) + poll(t, 30*time.Second, "/status never showed the barrier", func() bool { + mw, ok := masterWaitOf(env.hosts["s1"].status) + return ok && mw.Reason == "barrier" + }) + px.cut() + env.forceMove(t, e, "s2", "force-before-delete") + s2 := env.start(t, "bv-del-s2", "s2") + e2 := env.adopt(t, s2, "s2") + revokeAndExit(t, env, "s2", s2, e2) + out, errOut, code := env.h.run(t, "ops", "chunk", "volume-delete", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, + "--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-while-waiting") + var del struct{ Completed bool } + if code != 0 || json.Unmarshal([]byte(out), &del) != nil || !del.Completed { + t.Fatalf("volume-delete while a process waits: exit %d %s %s; want completed", code, out, errOut) + } + stillRunning(t, waiting, "while the master was unreachable") + px.restore() + err := waiting.wait(60 * time.Second) + if exitCode(err) != 78 || !waiting.has("blockvolume: exiting status=78 reason=deleted") { + t.Fatalf("waiting process after the committed delete: %v; want 78 reason=deleted", err) + } + }) + t.Run("admitted", func(t *testing.T) { + env := startHandoffEnv(t, 1) + holder := env.start(t, "bv-adm-holder", "s1") + e := env.adopt(t, holder, "s1") + revokeAndExit(t, env, "s1", holder, e) + conn, err := grpc.NewClient(env.h.masterAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := control.NewLifecycleServiceClient(conn).MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v1", Token: "admit-only"}); err != nil { + t.Fatal("admit the delete:", err) + } + at := time.Now() + waiting := env.start(t, "bv-adm-waiting", "s1") + err = waiting.wait(2 * time.Minute) + if exitCode(err) != 75 || !waiting.has("reason=assignment_timeout") || time.Since(at) < 25*time.Second { + t.Fatalf("waiting process under an admitted delete: %v after %v; want the bounded 75 assignment_timeout", err, time.Since(at)) + } + }) +} + +// After a master restart every lapsed volume gets the same barrier time; with +// 20 volume processes (one per volume) waiting, each must serve within 2 s of +// its barrier: the guards' jittered wake and the publisher's busy refusals +// must not keep them in step. Twenty processes: run only when +// SWB_MANY_VOLUMES=1 (not in every CI pass). +func TestManyVolumesServeTogetherAfterMasterRestart(t *testing.T) { + if os.Getenv("SWB_MANY_VOLUMES") != "1" { + t.Skip("20 volume processes: set SWB_MANY_VOLUMES=1") + } + const n = 20 + var targets []string + for i := 2; i <= n; i++ { + targets = append(targets, fmt.Sprintf("v%d", i)) + } + env := startHandoffEnvVolumes(t, 1, targets) + hosts := []bvHost{env.hosts["s1"]} + hosts[0].volume = "v1" + for _, v := range targets { + hosts = append(hosts, env.hosts["n-"+v]) + } + start := func(round string) []*daemon { + ds := make([]*daemon, len(hosts)) + for i, b := range hosts { + ds[i] = env.h.start(t, fmt.Sprintf("bv-%s-%s", round, b.volume), env.h.volume, env.volArgsFor(b)...) + } + return ds + } + first := start("first") + for _, b := range hosts { + poll(t, 3*time.Minute, b.volume+" never served", func() bool { return volumeFrontendReady(b.status, b.volume) }) + } + env.masterProcess.kill(t) + for i, d := range first { + if code := exitCode(d.wait(90 * time.Second)); code != 75 { + t.Fatalf("%s holder exited %v with the master down; want 75", hosts[i].volume, d.err) + } + } + waiting := start("waiting") + wBefore := storeWriteP99(t, env.h.dir) + time.Sleep(10 * time.Second) + env.masterProcess = env.h.start(t, "blockmaster-back", env.h.master, env.masterArgs...) + env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + + // One watcher per volume, every 50 ms: its barrier time from /status, + // then the moment it serves. + until := make([]time.Time, len(hosts)) + served := make([]time.Time, len(hosts)) + seen := make([]map[string]bool, len(hosts)) // the MasterWait reasons each watcher saw + var wg sync.WaitGroup + deadline := time.Now().Add(3 * time.Minute) + for i, b := range hosts { + wg.Add(1) + go func() { + defer wg.Done() + seen[i] = map[string]bool{} + for time.Now().Before(deadline) { + if mw, ok := masterWaitOfVolume(b.status, b.volume); ok { + seen[i][mw.Reason] = true + if until[i].IsZero() && mw.Reason == "barrier" { + until[i] = mw.Until + } + } + if volumeFrontendReady(b.status, b.volume) { + served[i] = time.Now() + return + } + time.Sleep(50 * time.Millisecond) + } + }() + } + wg.Wait() + for i, b := range hosts { + if served[i].IsZero() { + t.Fatalf("%s never served after the master returned", b.volume) + } + } + // After a master restart every lapsed volume's barrier is the master's + // reload plus TTL plus skew: the same T. A volume whose watcher missed it + // on /status is measured against the latest T the others showed. + var common time.Time + captured := 0 + for _, u := range until { + if !u.IsZero() { + captured++ + if u.After(common) { + common = u + } + } + } + if captured < len(hosts)/2 { + t.Fatalf("only %d of %d volumes showed the barrier on /status", captured, len(hosts)) + } + var worst time.Duration + for i, b := range hosts { + stillRunning(t, waiting[i], b.volume) + ref, how := until[i], "its barrier" + if ref.IsZero() { + ref, how = common, "the common barrier (reasons seen: "+fmt.Sprint(seen[i])+")" + } + late := served[i].Sub(ref) + t.Logf("%s served %v after %s", b.volume, late.Round(time.Millisecond), how) + worst = max(worst, late) + } + w := storeWriteP99(t, env.h.dir) + t.Logf("%d volumes: worst %v after the barrier; master store device W p99 %v (measured around the restart: %v)", + len(hosts), worst.Round(time.Millisecond), w.Round(time.Microsecond), []time.Duration{wBefore.Round(time.Microsecond), w.Round(time.Microsecond)}) + w = max(w, wBefore) + // The bound is T + 0.1 s + N x W for the store device; "within 2 s of + // the barrier" is a claim about a device that does not stall. Assert it + // only where this run measured such a device; otherwise report. + if w > storeWriteP99Limit { + t.Logf("2 s bar not asserted: the store device stalled in this run (W p99 %v > %v)", w.Round(time.Millisecond), storeWriteP99Limit) + return + } + if worst > 2*time.Second { + t.Fatalf("a volume served %v after its barrier with W p99 %v; want every one within 2 s", worst.Round(time.Millisecond), w.Round(time.Microsecond)) + } +} + +// storeWriteP99Limit is the store write p99 below which the 20-volume bar is +// asserted (a quiet NVMe store measured 2.3 ms). +const storeWriteP99Limit = 20 * time.Millisecond + +// storeWriteP99 measures the p99 of 100 authority store writes (the grant's +// durable write) in a directory beside the master's store. +func storeWriteP99(t *testing.T, dir string) time.Duration { + t.Helper() + d, err := os.MkdirTemp(dir, "w-probe-") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(d) + s, err := authority.NewFileAuthorityStore(d) + if err != nil { + t.Fatal(err) + } + defer s.Close() + var ws []time.Duration + for i := 0; i < 100; i++ { + r := authority.DurableRecord{VolumeID: fmt.Sprintf("w%03d", i), ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, + DataAddr: "127.0.0.1:1", CtrlAddr: "127.0.0.1:2", WriteSeq: 1, + Workspace: &authority.WorkspaceState{Lease: &authority.WorkspaceLease{ReplicaID: "r1", Epoch: 1, ExpiresAtNS: time.Now().UnixNano()}}} + start := time.Now() + if err := s.Put(r); err != nil { + t.Fatal(err) + } + ws = append(ws, time.Since(start)) + } + slices.Sort(ws) + return ws[98] +} + +// masterProxy forwards TCP connections to the master; cut closes its +// listener and every open connection (the master is unreachable through it), +// restore listens again on the same address. +type masterProxy struct { + t *testing.T + addr string + target string + mu sync.Mutex + ln net.Listener + conns []net.Conn +} + +func startMasterProxy(t *testing.T, target string) *masterProxy { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + p := &masterProxy{t: t, addr: ln.Addr().String(), target: target} + p.serve(ln) + t.Cleanup(p.cut) + return p +} + +func (p *masterProxy) serve(ln net.Listener) { + p.mu.Lock() + p.ln = ln + p.mu.Unlock() + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + up, err := net.Dial("tcp", p.target) + if err != nil { + _ = c.Close() + continue + } + p.mu.Lock() + p.conns = append(p.conns, c, up) + p.mu.Unlock() + go func() { _, _ = io.Copy(up, c); _ = up.Close() }() + go func() { _, _ = io.Copy(c, up); _ = c.Close() }() + } + }() +} + +func (p *masterProxy) cut() { + p.mu.Lock() + defer p.mu.Unlock() + if p.ln != nil { + _ = p.ln.Close() + p.ln = nil + } + for _, c := range p.conns { + _ = c.Close() + } + p.conns = nil +} + +func (p *masterProxy) restore() { + p.t.Helper() + ln, err := net.Listen("tcp", p.addr) + if err != nil { + p.t.Fatalf("proxy relisten %s: %v", p.addr, err) + } + p.serve(ln) +} + +// A volume process whose server id is not registered (a misconfigured unit, +// or a clone) never serves and never exits 75: the master refuses it with the +// typed IDENTITY detail, and it waits visibly, /status MasterWait reason +// "identity refused: unregistered", until its registration is fixed. A +// restart cannot fix a registration, so a 75 loop would only burn the start +// limit. SIGTERM still ends it at once. +func TestUnregisteredServerWaitsVisibly(t *testing.T) { + env := startHandoffEnv(t, 1) + b := env.hosts["s1"] + args := env.volArgs("s1") + for i := range args { + if args[i] == "--server-id" { + args[i+1] = "s-unregistered" + } + } + d := env.h.start(t, "bv-unregistered", env.h.volume, args...) + poll(t, 30*time.Second, "/status never showed the identity refusal", func() bool { + mw, ok := masterWaitOf(b.status) + return ok && mw.Reason == "identity refused: unregistered" && mw.Until.IsZero() + }) + time.Sleep(45 * time.Second) // past the 30 s bound a reachable master would give + stillRunning(t, d, "45 s refused as unregistered") + if volumeFrontendReady(b.status, "v1") { + t.Fatal("an unregistered server served") + } + if mw, ok := masterWaitOf(b.status); !ok || mw.Reason != "identity refused: unregistered" || time.Since(mw.Since) < 40*time.Second { + t.Fatalf("/status MasterWait %+v (present %v); want identity refused for 40 s or more", mw, ok) + } + d.term(t, 10*time.Second) + if d.err != nil { + t.Fatalf("exit %v after SIGTERM; want status 0", d.err) + } +} diff --git a/seaweed-block/cmd/blockvolume/memory_cgroup.go b/seaweed-block/cmd/blockvolume/memory_cgroup.go new file mode 100644 index 0000000000..ca6854f88d --- /dev/null +++ b/seaweed-block/cmd/blockvolume/memory_cgroup.go @@ -0,0 +1,128 @@ +package main + +import ( + "errors" + "fmt" + "os" + "path" + "strconv" + "strings" +) + +// cgroupMemoryLimitMiB reads the current unified cgroup and its ancestors: +// a parent's finite limit also constrains this holder. Zero means no v2 limit. +// Use slash paths even in fixture tests on non-Linux hosts. +func cgroupMemoryLimitMiB(readFile func(string) ([]byte, error)) (int64, error) { + data, err := readFile("/proc/self/cgroup") + if errors.Is(err, os.ErrNotExist) { + return 0, nil + } + if err != nil { + return 0, err + } + group := "" + for _, line := range strings.Split(string(data), "\n") { + if strings.HasPrefix(line, "0::") { + group = strings.TrimPrefix(line, "0::") + break + } + } + if group == "" { + return 0, nil + } + if !strings.HasPrefix(group, "/") { + return 0, fmt.Errorf("invalid unified cgroup path %q", group) + } + for _, part := range strings.Split(group, "/") { + if part == ".." { + return 0, fmt.Errorf("unified cgroup path escapes its mount: %q", group) + } + } + leaf, mount, err := cgroupMemoryDirectory(path.Clean(group), readFile) + if err != nil { + return 0, err + } + var limit int64 + for dir := leaf; ; dir = path.Dir(dir) { + name := path.Join(dir, "memory.max") + value, err := readFile(name) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return 0, fmt.Errorf("%s: %w", name, err) + } + if err == nil && strings.TrimSpace(string(value)) != "max" { + n, err := strconv.ParseInt(strings.TrimSpace(string(value)), 10, 64) + if err != nil || n <= 0 { + return 0, fmt.Errorf("invalid %s value %q", name, value) + } + if limit == 0 || n < limit { + limit = n + } + } + if dir == mount { + break + } + } + if limit == 0 { + return 0, nil + } + // Divide before multiplying to avoid overflow near MaxInt64. + mib := (limit/10*9 + limit%10*9/10) >> 20 + if mib == 0 { + return 0, fmt.Errorf("cgroup memory limit %d is too small for a MiB soft limit", limit) + } + return mib, nil +} + +// mountinfo names both the filesystem subtree root and its visible mountpoint. +// A membership path must resolve inside that view; an unresolved v2 hierarchy +// is an error here, not evidence of unlimited memory: the caller keeps the +// default limit and warns why. +func cgroupMemoryDirectory(group string, readFile func(string) ([]byte, error)) (string, string, error) { + data, err := readFile("/proc/self/mountinfo") + if err != nil { + return "", "", fmt.Errorf("read cgroup mounts: %w", err) + } + unescape := strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`) + var leaf, mount, bestRoot string + for _, line := range strings.Split(string(data), "\n") { + left, right, ok := strings.Cut(line, " - ") + if !ok { + continue + } + fs := strings.Fields(right) + if len(fs) == 0 || fs[0] != "cgroup2" { + continue + } + fields := strings.Fields(left) + if len(fields) < 6 { + return "", "", fmt.Errorf("malformed cgroup2 mountinfo") + } + root, point := unescape.Replace(fields[3]), unescape.Replace(fields[4]) + if !path.IsAbs(root) || !path.IsAbs(point) { + return "", "", fmt.Errorf("invalid cgroup2 mount paths") + } + unresolved := false + for _, part := range strings.Split(root+"/"+point, "/") { + if part == ".." { + unresolved = true + break + } + } + if unresolved { + continue + } // do not clean an out-of-namespace root into a different view + root, point = path.Clean(root), path.Clean(point) + if group != root && root != "/" && !strings.HasPrefix(group, root+"/") { + continue + } + // Prefer the widest visible ancestry when the hierarchy is mounted + // more than once, so a subtree bind mount does not hide a parent cap. + if mount == "" || len(root) < len(bestRoot) { + leaf, mount, bestRoot = path.Join(point, strings.TrimPrefix(group, root)), point, root + } + } + if mount == "" { + return "", "", fmt.Errorf("no cgroup2 mount resolves membership %q", group) + } + return leaf, mount, nil +} diff --git a/seaweed-block/cmd/blockvolume/memory_cgroup_test.go b/seaweed-block/cmd/blockvolume/memory_cgroup_test.go new file mode 100644 index 0000000000..3532ddbec3 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/memory_cgroup_test.go @@ -0,0 +1,120 @@ +package main + +import ( + "errors" + "os" + "testing" +) + +func TestMemoryLimitUsesCgroupUnlessExplicit(t *testing.T) { + base := []string{"--master", "127.0.0.1:1", "--server-id", "h1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:2", "--ctrl-addr", "127.0.0.1:3"} + t.Setenv("GOMEMLIMIT", "") + files := map[string]string{ + "/proc/self/mountinfo": "29 23 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup rw\n", + "/proc/self/cgroup": "0::/system.slice/volume.service\n", + "/sys/fs/cgroup/system.slice/volume.service/memory.max": "2147483648\n", + "/sys/fs/cgroup/system.slice/memory.max": "max\n", + "/sys/fs/cgroup/memory.max": "max\n", + } + read := func(name string) ([]byte, error) { + if s, ok := files[name]; ok { + return []byte(s), nil + } + return nil, os.ErrNotExist + } + f, err := parseFlagsWithCgroup(base, read) + if err != nil || f.memoryLimitMiB != 1843 { + t.Fatalf("2 GiB cgroup: limit=%d err=%v, want 1843 MiB", f.memoryLimitMiB, err) + } + for _, value := range []string{"192", "0"} { + f, err = parseFlagsWithCgroup(append(append([]string{}, base...), "--memory-limit-mib", value), func(string) ([]byte, error) { t.Fatal("explicit flag read cgroup"); return nil, os.ErrNotExist }) + want := int64(192) + if value == "0" { + want = 0 + } + if err != nil || f.memoryLimitMiB != want { + t.Fatalf("explicit %s: %d %v", value, f.memoryLimitMiB, err) + } + } +} + +func TestCgroupMemoryLimitHierarchyAndFallback(t *testing.T) { + for _, tc := range []struct { + name, membership, leaf, parent string + want int64 + wantErr bool + }{ + {"parent bounds child", "0::/parent/child\n", "2147483648", "1073741824", 921, false}, + {"unlimited", "0::/parent/child\n", "max", "max", 0, false}, + {"legacy hierarchy", "1:memory:/parent/child\n", "2147483648", "max", 0, false}, + {"malformed", "0::/parent/child\n", "garbage", "max", 0, true}, + {"overflow safe", "0::/parent/child\n", "9223372036854775807", "max", 7916483719987, false}, + {"escape refused", "0::/../child\n", "max", "max", 0, true}, + } { + t.Run(tc.name, func(t *testing.T) { + files := map[string]string{"/proc/self/mountinfo": "29 23 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup rw\n", "/proc/self/cgroup": tc.membership, "/sys/fs/cgroup/parent/child/memory.max": tc.leaf, "/sys/fs/cgroup/parent/memory.max": tc.parent, "/sys/fs/cgroup/memory.max": "max"} + got, err := cgroupMemoryLimitMiB(func(name string) ([]byte, error) { + if s, ok := files[name]; ok { + return []byte(s), nil + } + return nil, os.ErrNotExist + }) + if (err != nil) != tc.wantErr || got != tc.want { + t.Fatalf("got %d,%v want %d error=%v", got, err, tc.want, tc.wantErr) + } + }) + } + if n, err := cgroupMemoryLimitMiB(func(string) ([]byte, error) { return nil, os.ErrNotExist }); n != 0 || err != nil { + t.Fatalf("no proc cgroup: %d %v", n, err) + } + denied := errors.New("permission denied") + if _, err := cgroupMemoryLimitMiB(func(string) ([]byte, error) { return nil, denied }); !errors.Is(err, denied) { + t.Fatalf("read error hidden: %v", err) + } +} + +func TestCgroupMemoryLimitMountViews(t *testing.T) { + for _, tc := range []struct { + name, group, mountinfo string + files map[string]string + want int64 + wantErr bool + }{ + {"alternate mount", "/slice/holder", "29 23 0:26 / /cg rw - cgroup2 cgroup rw", map[string]string{"/cg/slice/holder/memory.max": "2147483648", "/cg/slice/memory.max": "max", "/cg/memory.max": "max"}, 1843, false}, + {"subtree mount", "/slice/holder", "29 23 0:26 /slice /cg rw - cgroup2 cgroup rw", map[string]string{"/cg/holder/memory.max": "2147483648", "/cg/memory.max": "1073741824", "/memory.max": "1048576"}, 921, false}, + {"namespace root", "/", "29 23 0:26 / /cg rw - cgroup2 cgroup rw", map[string]string{"/cg/memory.max": "1073741824"}, 921, false}, + {"escaped mount", "/holder", `29 23 0:26 / /cg\040memory rw - cgroup2 cgroup rw`, map[string]string{"/cg memory/holder/memory.max": "2147483648", "/cg memory/memory.max": "max"}, 1843, false}, + {"memory controller absent", "/holder", "29 23 0:26 / /cg rw - cgroup2 cgroup rw", nil, 0, false}, + {"wider ancestry", "/slice/holder", "29 23 0:26 / /cg rw - cgroup2 cgroup rw\n30 23 0:26 /slice /nested rw - cgroup2 cgroup rw", map[string]string{"/cg/slice/holder/memory.max": "2147483648", "/cg/slice/memory.max": "1073741824", "/cg/memory.max": "max", "/nested/holder/memory.max": "2147483648", "/nested/memory.max": "max"}, 921, false}, + {"unresolved view", "/holder", "29 23 0:26 /other /cg rw - cgroup2 cgroup rw", nil, 0, true}, + {"parent-relative mount root", "/holder", "29 23 0:26 /.. /cg rw - cgroup2 cgroup rw", nil, 0, true}, + {"valid alternative to parent-relative root", "/holder", "29 23 0:26 /.. /hidden rw - cgroup2 cgroup rw\n30 23 0:26 / /cg rw - cgroup2 cgroup rw", map[string]string{"/cg/holder/memory.max": "2147483648", "/cg/memory.max": "max"}, 1843, false}, + } { + t.Run(tc.name, func(t *testing.T) { + read := func(name string) ([]byte, error) { + switch name { + case "/proc/self/cgroup": + return []byte("0::" + tc.group + "\n"), nil + case "/proc/self/mountinfo": + return []byte(tc.mountinfo + "\n"), nil + } + if s, ok := tc.files[name]; ok { + return []byte(s), nil + } + return nil, os.ErrNotExist + } + got, err := cgroupMemoryLimitMiB(read) + if (err != nil) != tc.wantErr || got != tc.want { + t.Fatalf("got %d,%v want %d", got, err, tc.want) + } + }) + } +} + +func TestVersionDoesNotReadCgroup(t *testing.T) { + t.Setenv("GOMEMLIMIT", "") + f, err := parseFlagsWithCgroup([]string{"--version"}, func(string) ([]byte, error) { t.Error("version read cgroup"); return nil, errors.New("unreadable") }) + if err != nil || !f.version { + t.Fatalf("version: %v %+v", err, f) + } +} diff --git a/seaweed-block/cmd/blockvolume/memory_fallback_test.go b/seaweed-block/cmd/blockvolume/memory_fallback_test.go new file mode 100644 index 0000000000..7d9c924460 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/memory_fallback_test.go @@ -0,0 +1,110 @@ +package main + +import ( + "fmt" + "os" + "runtime/debug" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/host/volume" +) + +var fallbackBase = []string{"--master", "127.0.0.1:1", "--server-id", "h1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:2", "--ctrl-addr", "127.0.0.1:3"} + +// cgroupFiles serves fixture /proc and cgroup files; anything else is absent. +func cgroupFiles(files map[string]string) func(string) ([]byte, error) { + return func(name string) ([]byte, error) { + if s, ok := files[name]; ok { + return []byte(s), nil + } + return nil, os.ErrNotExist + } +} + +// A holder whose cgroup v2 limit cannot be derived, with neither +// --memory-limit-mib nor GOMEMLIMIT given, starts on the 256 MiB default and +// says why: it is the no-limit case, never a refusal. The first case is a +// mount namespace whose cgroup2 mount does not cover the process's +// membership (what the process sees in /proc/self/mountinfo and cgroup). +func TestMemoryLimitFallsBackWhenTheCgroupLimitCannotBeDerived(t *testing.T) { + t.Setenv("GOMEMLIMIT", "") + for _, tc := range []struct { + name, reason string + files map[string]string + }{ + {"membership outside the namespace's cgroup2 mount", `no cgroup2 mount resolves membership "/user.slice/user-1000.slice/session-7.scope"`, map[string]string{ + "/proc/self/mountinfo": "29 23 0:26 /system.slice/runner.service /sys/fs/cgroup rw - cgroup2 cgroup rw\n", + "/proc/self/cgroup": "0::/user.slice/user-1000.slice/session-7.scope\n", + }}, + {"unreadable memory.max", "invalid /sys/fs/cgroup/holder/memory.max value", map[string]string{ + "/proc/self/mountinfo": "29 23 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup rw\n", + "/proc/self/cgroup": "0::/holder\n", + "/sys/fs/cgroup/holder/memory.max": "garbage\n", + }}, + } { + t.Run(tc.name, func(t *testing.T) { + f, err := parseFlagsWithCgroup(fallbackBase, cgroupFiles(tc.files)) + if err != nil { + t.Fatalf("refused to start: %v", err) + } + if f.memoryLimitMiB != 256 { + t.Fatalf("limit %d MiB, want the 256 MiB default", f.memoryLimitMiB) + } + if !strings.Contains(f.memoryLimitFallback, tc.reason) { + t.Fatalf("fallback reason %q does not name %q", f.memoryLimitFallback, tc.reason) + } + }) + } + // An explicit but invalid limit still refuses. + if _, err := parseFlagsWithCgroup(append(append([]string{}, fallbackBase...), "--memory-limit-mib", "-1"), cgroupFiles(nil)); err == nil { + t.Fatal("an invalid --memory-limit-mib was accepted") + } +} + +// Applying a fallback limit logs exactly one WARN naming why and the two ways +// to choose a limit, and status reports the reason; a derived limit logs +// nothing and reports no reason. +func TestMemoryLimitFallbackWarnsOnceAndShowsInStatus(t *testing.T) { + t.Setenv("GOMEMLIMIT", "") + old := debug.SetMemoryLimit(-1) + t.Cleanup(func() { debug.SetMemoryLimit(old); volume.SetSoftLimitFallback("") }) + f, err := parseFlagsWithCgroup(fallbackBase, cgroupFiles(map[string]string{ + "/proc/self/mountinfo": "29 23 0:26 /system.slice/runner.service /sys/fs/cgroup rw - cgroup2 cgroup rw\n", + "/proc/self/cgroup": "0::/user.slice/user-1000.slice/session-7.scope\n", + })) + if err != nil { + t.Fatalf("refused to start: %v", err) + } + var lines []string + logf := func(format string, args ...any) { lines = append(lines, fmt.Sprintf(format, args...)) } + applyMemoryLimit(f, logf) + if len(lines) != 1 { + t.Fatalf("%d log lines, want exactly one WARN: %q", len(lines), lines) + } + for _, want := range []string{"level=WARN", "no cgroup2 mount resolves membership", "256 MiB", "--memory-limit-mib", "GOMEMLIMIT"} { + if !strings.Contains(lines[0], want) { + t.Fatalf("the WARN does not name %q: %s", want, lines[0]) + } + } + if got := debug.SetMemoryLimit(-1); got != 256<<20 { + t.Fatalf("soft limit in force %d, want 256 MiB", got) + } + if got := volume.SoftLimitFallback(); !strings.Contains(got, "no cgroup2 mount resolves membership") { + t.Fatalf("status reports the fallback as %q", got) + } + + lines = nil + f, err = parseFlagsWithCgroup(fallbackBase, cgroupFiles(map[string]string{ + "/proc/self/mountinfo": "29 23 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup rw\n", + "/proc/self/cgroup": "0::/system.slice/volume.service\n", + "/sys/fs/cgroup/system.slice/volume.service/memory.max": "2147483648\n", + })) + if err != nil { + t.Fatal(err) + } + applyMemoryLimit(f, logf) + if len(lines) != 0 || volume.SoftLimitFallback() != "" { + t.Fatalf("a derived limit logged %q and reports fallback %q", lines, volume.SoftLimitFallback()) + } +} diff --git a/seaweed-block/cmd/blockvolume/memory_flags_test.go b/seaweed-block/cmd/blockvolume/memory_flags_test.go new file mode 100644 index 0000000000..d5e9f92697 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/memory_flags_test.go @@ -0,0 +1,30 @@ +package main + +import ( + "os" + "testing" +) + +func TestMemoryLimitFlagAndEnvironment(t *testing.T) { + base := []string{"--master", "127.0.0.1:1", "--server-id", "h1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:2", "--ctrl-addr", "127.0.0.1:3"} + t.Setenv("GOMEMLIMIT", "") + noCgroup := func(string) ([]byte, error) { return nil, os.ErrNotExist } + f, err := parseFlagsWithCgroup(base, noCgroup) + if err != nil || f.memoryLimitMiB != 256 { + t.Fatalf("default memory limit: %d %v", f.memoryLimitMiB, err) + } + t.Setenv("GOMEMLIMIT", "128MiB") + f, err = parseFlagsWithCgroup(base, noCgroup) + if err != nil || f.memoryLimitMiB != 0 { + t.Fatalf("explicit runtime limit overridden: %d %v", f.memoryLimitMiB, err) + } + f, err = parseFlags(append(append([]string{}, base...), "--memory-limit-mib", "192")) + if err != nil || f.memoryLimitMiB != 192 { + t.Fatalf("explicit flag: %d %v", f.memoryLimitMiB, err) + } + for _, value := range []string{"-1", "9223372036854775807"} { + if _, err = parseFlags(append(append([]string{}, base...), "--memory-limit-mib", value)); err == nil { + t.Fatalf("invalid limit %s accepted", value) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/memory_limit.go b/seaweed-block/cmd/blockvolume/memory_limit.go new file mode 100644 index 0000000000..c4f2d17c99 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/memory_limit.go @@ -0,0 +1,21 @@ +package main + +import ( + "runtime/debug" + + "github.com/seaweedfs/seaweed-block/core/host/volume" +) + +// applyMemoryLimit sets the process's Go soft memory limit from the parsed +// flags. When the default is in force because the cgroup v2 limit could not +// be derived, it logs one WARN naming why and how to choose a limit, and +// status reports the reason (Memory.SoftLimitFallback). +func applyMemoryLimit(f flags, logf func(string, ...any)) { + if f.memoryLimitMiB > 0 { + debug.SetMemoryLimit(f.memoryLimitMiB << 20) + } + volume.SetSoftLimitFallback(f.memoryLimitFallback) + if f.memoryLimitFallback != "" { + logf("blockvolume: level=WARN memory limit: the cgroup v2 limit could not be derived (%s); running with the %d MiB default soft limit; set --memory-limit-mib or GOMEMLIMIT to choose a limit", f.memoryLimitFallback, f.memoryLimitMiB) + } +} diff --git a/seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go b/seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go new file mode 100644 index 0000000000..c5f4194c11 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/neverstarted_delete_integration_test.go @@ -0,0 +1,459 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" +) + +// INV-WS-DELETE-NO-LIVE-HOLDER-001, the guard half: a restore target created but never +// attached (no blockvolume ever started for it) is deletable already on 1.0. +// volume-delete completes without a revoke, its HEAD becomes a deleted +// tombstone, and the source volume and its snapshot are untouched. The 1.0.1 +// red half is a target whose blockvolume started, was assigned and exited +// before it claimed HEAD (the TestNeverStartedLine... tests below). +func TestNeverAttachedRestoreTargetIsDeletable(t *testing.T) { + env := startHandoffEnvWith(t, 1, []string{"v2"}) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + holder := env.start(t, "blockvolume-v1", "s1") + env.adopt(t, holder, "s1") + env.writeBlock(t, "s1", 0, cutCrashBlock('N', 0)) + env.snapshot(t, "s1", "v1", "s1") + + // The target exists in the catalog; its blockvolume never starts. + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + + out, errOut, code := env.h.run(t, "ops", "chunk", "volume-delete", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC, + "--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-v2-never-started") + if code != 0 || !handoffDeleteCompleted(out) { + t.Fatalf("volume-delete of a never-attached target must complete; exit %d:\n%s\n%s", code, out, errOut) + } + shown := env.headOf(t, "v2") + if !strings.Contains(shown, `"state":"deleted"`) { + t.Fatalf("the deleted target's HEAD is not a deleted tombstone:\n%s", shown) + } + // The source and its snapshot are untouched. + if got := env.readBlock(t, "s1", 0); string(got) != string(cutCrashBlock('N', 0)) { + t.Fatalf("the source's block changed") + } + if snaps := env.snapshots(t, "v1", ""); len(snaps) != 1 { + t.Fatalf("the source has %d snapshots after the target's delete; want 1", len(snaps)) + } +} + +// 1.0.1 (INV-WS-DELETE-NO-LIVE-HOLDER-001; the fence of NeverStarted -> Deleting): once a +// never-attached target's delete is admitted, a late start of its blockvolume +// must not claim it: the process exits without serving and the catalog still +// says deleted. Recorded on 1.0 to see where it stands. +func TestNeverStartedDeleteFencesALateStart(t *testing.T) { + env := startHandoffEnvWith(t, 1, []string{"v2"}) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + holder := env.start(t, "blockvolume-v1", "s1") + env.adopt(t, holder, "s1") + env.writeBlock(t, "s1", 0, cutCrashBlock('L', 0)) + env.snapshot(t, "s1", "v1", "s1") + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + out, errOut, code := env.h.run(t, "ops", "chunk", "volume-delete", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC, + "--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-v2-late") + if code != 0 { + t.Fatalf("volume-delete of a never-attached target: exit %d:\n%s\n%s", code, out, errOut) + } + b := env.hosts["n-v2"] + late := env.h.start(t, "blockvolume-v2-late", env.h.volume, env.volArgsFor(b)...) + err := late.wait(60 * time.Second) + served := late.has("durable: HEAD claim for volume=v2 done") || volumeFrontendReady(b.status, "v2") + shown := env.headOf(t, "v2") + t.Logf("late start after the delete: exit %v, served %v, HEAD %s", err, served, firstLine(shown)) + if served || err == nil || strings.Contains(fmt.Sprint(err), "still running") || !strings.Contains(shown, `"state":"deleted"`) { + t.Fatalf("1.0.1: a start after the delete must exit without claiming or serving and leave the volume deleted; exit %v, served %v, HEAD:\n%s", err, served, shown) + } +} + +// 1.0.1 (INV-WS-DELETE-NO-LIVE-HOLDER-001; the race): a start of a never-attached target and its +// volume-delete run at the same time, five times. Exactly one wins each time: +// either the volume is deleted and the process never served, or the process +// claimed and served and the delete is refused as for a live holder. +func TestNeverStartedDeleteRacesAStart(t *testing.T) { + targets := []string{"v2", "v3", "v4", "v5", "v6"} + env := startHandoffEnvWith(t, 1, targets) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + holder := env.start(t, "blockvolume-v1", "s1") + env.adopt(t, holder, "s1") + env.writeBlock(t, "s1", 0, cutCrashBlock('R', 0)) + env.snapshot(t, "s1", "v1", "s1") + for _, v := range targets { + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", v, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + b := env.hosts["n-"+v] + type delResult struct { + out string + code int + } + deleted := make(chan delResult, 1) + d := env.h.start(t, "blockvolume-"+v+"-race", env.h.volume, env.volArgsFor(b)...) + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) + defer cancel() + out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "volume-delete", "--volume", v, "--chunk-filer", env.cluster.filerGRPC, + "--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-"+v+"-race") + if err != nil { + code = -1 + } + deleted <- delResult{out + errOut, code} + }() + r := <-deleted + _ = d.wait(30 * time.Second) + // Served means the process claimed HEAD (no I/O is admitted before the + // claim) or its frontend became ready; adopting the assignment comes + // before the claim and is not serving. + served := d.has("durable: HEAD claim for volume="+v+" done") || volumeFrontendReady(b.status, v) + shown := env.headOf(t, v) + isDeleted := strings.Contains(shown, `"state":"deleted"`) + t.Logf("%s: delete exit %d, served %v, HEAD deleted %v: %s", v, r.code, served, isDeleted, firstLine(r.out)) + switch { + case r.code == 0 && isDeleted && !served: + case r.code != 0 && served && !isDeleted: + default: + t.Errorf("1.0.1: %s: not exactly one winner: delete exit %d, served %v, HEAD deleted %v", v, r.code, served, isDeleted) + } + d.kill(t) + } +} + +func (env *handoffEnv) workspaceShow(t *testing.T, v string) string { + out, errOut, _ := env.h.run(t, "ops", "workspace", "show", "--master", env.h.masterAddr, "--volume", v) + return out + errOut +} + +func (env *handoffEnv) deleteNoRevoke(ctx context.Context, v, request string) (string, int) { + out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "volume-delete", "--volume", v, "--chunk-filer", env.cluster.filerGRPC, + "--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", request) + if err != nil { + code = -1 + } + // runCLI records both streams. Only stdout is the typed success answer; + // stderr may contain acknowledged HEAD-write diagnostics on success too. + if code == 0 { + return out, code + } + return out + errOut, code +} + +// deleteAfterTheHorizon is v1's delete of a line HEAD never reached: the +// delete may be refused only while the stranded line's lease can still be +// live ("lease expiry plus clock-skew margin has not elapsed"); nobody +// renews it, so the same delete (same request id, which resumes it) run +// past the horizon it names completes. Any other refusal is returned as it +// is. The immediate delete of a never-started line, without waiting, is the +// 1.0.1 fix. +func (env *handoffEnv) deleteAfterTheHorizon(t *testing.T, v, request string) (string, int) { + t.Helper() + out, code := env.deleteNoRevoke(context.Background(), v, request) + if code == 0 || !strings.Contains(out, "has not elapsed") { + return out, code + } + wait := 75 * time.Second + if i := strings.Index(out, "live until "); i >= 0 { + if f := strings.Fields(out[i+len("live until "):]); len(f) > 0 { + if until, err := time.Parse(time.RFC3339Nano, strings.TrimRight(f[0], ":")); err == nil { + wait = time.Until(until) + 5*time.Second + } + } + } + if wait < 0 || wait > 90*time.Second { + t.Fatalf("the refusal names a horizon %v away (want within 90 s):\n%s", wait, out) + } + t.Logf("%s: refused until its lease horizon; retrying in %v:\n%s", v, wait.Round(time.Second), firstLine(out)) + time.Sleep(wait) + return env.deleteNoRevoke(context.Background(), v, request) +} + +// lineOf returns the master's durable authority record for v (the line: +// replica, epoch, and any workspace lease), as stored in --authority-store. +func (env *handoffEnv) lineOf(t *testing.T, v string) string { + t.Helper() + dir := "" + for i, a := range env.masterArgs { + if a == "--authority-store" && i+1 < len(env.masterArgs) { + dir = env.masterArgs[i+1] + } + } + data, err := os.ReadFile(filepath.Join(dir, v+".v3auth.json")) + if os.IsNotExist(err) { + return "(no line)" + } + if err != nil { + t.Fatal(err) + } + return strings.Join(strings.Fields(string(data)), " ") +} + +// requireNeverStarted checks the state by its facts: the master's line for +// v is at epoch e (with or without a lease, as lease says) and HEAD is below +// it (epoch headEpoch). +func (env *handoffEnv) requireNeverStarted(t *testing.T, v string, e, headEpoch uint64, lease bool) { + t.Helper() + line, head := env.lineOf(t, v), env.headOf(t, v) + ok := strings.Contains(line, fmt.Sprintf(`"Epoch":%d,`, e)) && strings.Contains(head, fmt.Sprintf(`"epoch":%d,`, headEpoch)) && + strings.Contains(line, `"Lease":`) == lease + if !ok { + t.Fatalf("setup: %s is not a line at epoch %d (lease %v) over HEAD at epoch %d:\nline: %s\nHEAD: %s", v, e, lease, headEpoch, line, head) + } + t.Logf("%s: line %s\nHEAD %s", v, line, head) +} + +// strandStoreDown (S1): v's first start runs with the store (filer) down. +// The process heartbeats and the master writes the line at epoch 1; local +// readiness blocks before the assignment is applied, no lease is granted, +// and the process exits. The filer comes back. Line at 1, no lease, HEAD 0. +func (env *handoffEnv) strandStoreDown(t *testing.T, v string) { + t.Helper() + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", v, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + env.cluster.stopProc(t, "filer") + d := env.h.start(t, "blockvolume-"+v+"-store-down", env.h.volume, env.volArgsFor(env.hosts["n-"+v])...) + err := d.wait(120 * time.Second) + env.cluster.restartProc(t, "filer") + w4WaitTCP(t, env.cluster.filerGRPC, 30*time.Second) + if err == nil || d.has("adopted as PRIMARY") { + t.Fatalf("setup: %s's start with the store down exited %v, adopted %v", v, err, d.has("adopted as PRIMARY")) + } + env.requireNeverStarted(t, v, 1, 0, false) +} + +// strandAtGrant (S2): v's first start with the right flags is stopped +// (SIGSTOP) the moment the master shows its lease granted, after the +// adoption and before the HEAD claim, then killed. Line at 1 with a granted +// lease, HEAD 0. When the claim wins the race the next candidate is tried; +// it returns the stranded volume. +func (env *handoffEnv) strandAtGrant(t *testing.T, candidates ...string) string { + t.Helper() + for _, v := range candidates { + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", v, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + d := env.h.start(t, "blockvolume-"+v+"-stopped-at-grant", env.h.volume, env.volArgsFor(env.hosts["n-"+v])...) + deadline := time.Now().Add(60 * time.Second) + for !d.has("adopted as PRIMARY") && time.Now().Before(deadline) { + time.Sleep(time.Millisecond) + } + for time.Now().Before(deadline) { + out, _, _, _ := runCLI(context.Background(), env.h, "ops", "workspace", "show", "--master", env.h.masterAddr, "--volume", v) + if strings.Contains(out, "lease state: granted") { + break + } + } + if err := d.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatalf("setup: stop %s: %v", v, err) + } + claimed := !strings.Contains(env.headOf(t, v), `"epoch":0,"holder":""`) + _ = d.proc.Signal(syscall.SIGKILL) + _ = d.wait(10 * time.Second) + if claimed { + t.Logf("%s: the claim won the race; trying the next candidate", v) + continue + } + env.requireNeverStarted(t, v, 1, 0, true) + return v + } + t.Fatalf("setup: the claim won the race for every candidate %v", candidates) + return "" +} + +// INV-WS-DELETE-NO-LIVE-HOLDER-001 (on v1 past the stranded line's lease +// horizon: deleteAfterTheHorizon; at once is 1.0.1): a line whose epoch HEAD never +// reached has acknowledged nothing, so volume-delete completes WITHOUT a +// revoke; HEAD becomes a deleted tombstone, the source is untouched, and no +// granted lease stays on the deleted volume. Routes, each without root: +// - S1: a first start with the store down (line, no lease); +// - S2: a first start stopped at the lease grant (line and lease), deleted +// at once and again after the lease lapsed (65 s); +// - clean move: the volume moved clean to a target that never starts (a +// line and a lease at the new epoch, HEAD at the old one, detached). +// +// On 1.0 every delete is refused as volume_in_use (live authority needs a +// revocation ACK that no process can give). +func TestNeverStartedLineIsDeletableWithoutARevoke(t *testing.T) { + deleted := func(t *testing.T, env *handoffEnv, v, request string) { + t.Helper() + before := env.workspaceShow(t, v) + out, code := env.deleteAfterTheHorizon(t, v, request) + completed := code == 0 && handoffDeleteCompleted(out) + head, after := env.headOf(t, v), env.workspaceShow(t, v) + t.Logf("delete exit %d, completed %v, HEAD %s\nworkspace show before:\n%s\nafter:\n%s\ndelete output:\n%s", code, completed, head, before, after, out) + if !completed { + t.Fatalf("volume-delete of %s (line above HEAD) must complete without a revoke, past the lease horizon; exit %d", v, code) + } + if !strings.Contains(head, `"state":"deleted"`) || strings.Contains(after, "lease state: granted") { + t.Fatalf("a completed delete must leave a deleted HEAD and no granted lease") + } + } + t.Run("S1-store-down", func(t *testing.T) { + env := startSourceWithSnapshot(t, "v2") + env.strandStoreDown(t, "v2") + deleted(t, env, "v2", "del-v2-s1") + requireSourceUntouched(t, env) + }) + t.Run("S2-stopped-at-grant", func(t *testing.T) { + env := startSourceWithSnapshot(t, "v3", "v3b", "v3c") + v := env.strandAtGrant(t, "v3", "v3b", "v3c") + deleted(t, env, v, "del-"+v+"-s2") + requireSourceUntouched(t, env) + }) + t.Run("S2-lease-lapsed", func(t *testing.T) { + env := startSourceWithSnapshot(t, "v4", "v4b", "v4c") + v := env.strandAtGrant(t, "v4", "v4b", "v4c") + time.Sleep(65 * time.Second) + deleted(t, env, v, "del-"+v+"-s2-lapsed") + }) + t.Run("clean-move-target-never-started", func(t *testing.T) { + env := startHandoffEnv(t, 2) + must, mustU := fatalOn(t) + old := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, old, "s1") + env.writeBlock(t, "s1", 0, pattern("never-start-move")) + g := env.seal(t, "s1", e) + l := env.sealedLSN(t, e, g) + env.revoke(t, e, g) + must(old.wait(30 * time.Second)) + env.waitAck(t, e, g) + out, _ := env.h.command(t, env.moveClean(e, "s2", "move-v1-1")...) + e2 := mustU(movedEpochTo(out, e, g, l, "s2")) + env.requireNeverStarted(t, "v1", e2, e, true) + deleted(t, env, "v1", "del-v1-moved") + }) +} + +func requireSourceUntouched(t *testing.T, env *handoffEnv) { + t.Helper() + if got := env.readBlock(t, "s1", 0); string(got) != string(cutCrashBlock('A', 0)) { + t.Fatalf("the source's block changed") + } + if snaps := env.snapshots(t, "v1", ""); len(snaps) != 1 { + t.Fatalf("the source has %d snapshots after the target's delete; want 1", len(snaps)) + } +} + +// After that delete (on v1 past the lease horizon), a start of the target with the store up +// must not claim it: it exits without serving and the HEAD stays deleted. +// S1 and S2. +func TestNeverStartedLineDeleteFencesALateStart(t *testing.T) { + for _, c := range []struct { + name string + targets []string + }{ + {"S1-store-down", []string{"v2"}}, + {"S2-stopped-at-grant", []string{"v3", "v3b", "v3c"}}, + } { + t.Run(c.name, func(t *testing.T) { + env := startSourceWithSnapshot(t, c.targets...) + v := c.targets[0] + if c.name == "S1-store-down" { + env.strandStoreDown(t, v) + } else { + v = env.strandAtGrant(t, c.targets...) + } + if out, code := env.deleteAfterTheHorizon(t, v, "del-"+v+"-late"); code != 0 { + t.Fatalf("volume-delete of %s (line above HEAD), past the lease horizon: exit %d:\n%s", v, code, out) + } + b := env.hosts["n-"+v] + late := env.h.start(t, "blockvolume-"+v+"-late", env.h.volume, env.volArgsFor(b)...) + err := late.wait(90 * time.Second) + served := volumeFrontendReady(b.status, v) + head := env.headOf(t, v) + if served || err == nil || strings.Contains(fmt.Sprint(err), "still running") || !strings.Contains(head, `"state":"deleted"`) { + t.Fatalf("1.0.1: a start after the delete must exit without claiming or serving; exit %v, served %v, HEAD %s", err, served, head) + } + }) + } +} + +// 1.0.1 red: a start (store up) of an S1 target and its volume-delete race, +// with the start delayed by 0 s to 3 s. Each time exactly one wins: the +// volume is deleted and never served, or it served and the delete was +// refused. With a 3 s lead the delete must win. +func TestNeverStartedLineDeleteRacesAStart(t *testing.T) { + targets := []string{"v2", "v3", "v4", "v5", "v6"} + delays := []time.Duration{0, 0, 200 * time.Millisecond, time.Second, 3 * time.Second} + env := startSourceWithSnapshot(t, targets...) + for i, v := range targets { + env.strandStoreDown(t, v) + b := env.hosts["n-"+v] + type delResult struct { + out string + code int + } + deleted := make(chan delResult, 1) + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) + defer cancel() + out, code := env.deleteNoRevoke(ctx, v, "del-"+v+"-race") + deleted <- delResult{out, code} + }() + time.Sleep(delays[i]) + d := env.h.start(t, "blockvolume-"+v+"-race", env.h.volume, env.volArgsFor(b)...) + r := <-deleted + _ = d.wait(60 * time.Second) + served := volumeFrontendReady(b.status, v) + isDeleted := strings.Contains(env.headOf(t, v), `"state":"deleted"`) + t.Logf("%s (start +%v): delete exit %d, served %v, HEAD deleted %v: %s", v, delays[i], r.code, served, isDeleted, firstLine(r.out)) + switch { + case r.code == 0 && isDeleted && !served: + case r.code != 0 && served && !isDeleted && delays[i] < 3*time.Second: + default: + t.Errorf("1.0.1: %s: want exactly one winner (the delete with a 3 s lead): delete exit %d, served %v, HEAD deleted %v", v, r.code, served, isDeleted) + } + d.kill(t) + } +} + +// Master restart, one direction (on v1 past the lease horizon): the master is SIGKILLed and +// restarted between the stranding and the delete; the delete still completes +// without a revoke, from what the master and the HEAD keep durably. S1 and S2. +func TestNeverStartedDeleteAfterAMasterRestart(t *testing.T) { + for _, s2 := range []bool{false, true} { + name := map[bool]string{false: "S1-store-down", true: "S2-stopped-at-grant"}[s2] + t.Run(name, func(t *testing.T) { + env := startSourceWithSnapshot(t, "v2", "v2b", "v2c") + v := "v2" + if s2 { + v = env.strandAtGrant(t, "v2", "v2b", "v2c") + } else { + env.strandStoreDown(t, v) + } + restartKilledMaster(t, env) + out, code := env.deleteAfterTheHorizon(t, v, "del-"+v+"-after-restart") + if head := env.headOf(t, v); code != 0 || !strings.Contains(head, `"state":"deleted"`) { + t.Fatalf("after a master restart, volume-delete of %s must complete (past the lease horizon); exit %d, HEAD %s:\n%s", v, code, head, out) + } + }) + } +} + +// Guard, green on 1.0 (master restart, the other direction): a target whose +// holder DID claim its HEAD, was SIGKILLed, and whose lease the restarted +// master no longer holds in memory, is not never-started: volume-delete +// without a revoke and an ACK is refused and the HEAD is not tombstoned. +func TestClaimedTargetAfterAMasterRestartIsNotNeverStarted(t *testing.T) { + env := startSourceWithSnapshot(t, "v2") + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + d := env.startTarget(t, "v2", "blockvolume-v2") + if head := env.headOf(t, "v2"); strings.Contains(head, `"holder":""`) { + t.Fatalf("setup: v2 serves but its HEAD is not claimed: %s", head) + } + d.kill(t) + restartKilledMaster(t, env) + out, code := env.deleteNoRevoke(context.Background(), "v2", "del-v2-claimed") + if head := env.headOf(t, "v2"); code == 0 || strings.Contains(head, `"state":"deleted"`) { + t.Fatalf("a claimed target was deleted without a revoke after a master restart; exit %d, HEAD %s:\n%s", code, head, out) + } +} diff --git a/seaweed-block/cmd/blockvolume/new_cluster_format_level_integration_test.go b/seaweed-block/cmd/blockvolume/new_cluster_format_level_integration_test.go new file mode 100644 index 0000000000..566d9a355c --- /dev/null +++ b/seaweed-block/cmd/blockvolume/new_cluster_format_level_integration_test.go @@ -0,0 +1,26 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "strings" + "testing" +) + +// TestANewClustersRealHolderReportsLevel1AndIsGranted: on a new cluster +// (an empty master store starts at format level 1) the REAL blockvolume +// binary is granted its line: the grant needs the holder process's own +// report at level 1, so the adoption proves its first heartbeat reported +// reads_level 1; and its first snapshot runs at once (a fresh store has +// nothing for the upgrade compare pass, which would answer in_progress). +func TestANewClustersRealHolderReportsLevel1AndIsGranted(t *testing.T) { + env := startHandoffEnvWith(t, 1, nil) + out, _ := env.h.command(t, "cluster", "format-level", "--master", env.h.masterAddr) + if strings.TrimSpace(out) != "format level 1" { + t.Fatalf("a new cluster's format level: %q, want 1", out) + } + holder := env.start(t, "blockvolume-s1", "s1") + env.adopt(t, holder, "s1") // the grant: only after the holder process's own level-1 report + env.writeBlock(t, "s1", 0, pattern("new-cluster-lv1!")) + env.snapshot(t, "s1", "v1", "first") +} diff --git a/seaweed-block/cmd/blockvolume/newer_format_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/newer_format_systemd_integration_test.go new file mode 100644 index 0000000000..6cf93b7932 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/newer_format_systemd_integration_test.go @@ -0,0 +1,232 @@ +//go:build linux && subprocess && chunkstore_integration && systemd_integration + +package main_test + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "fmt" + "hash/crc32" + "os" + "os/exec" + "path" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc" +) + +// Under the shipped unit's restart policy (Restart=on-failure, +// RestartPreventExitStatus=78 79), a holder that meets a local store or a +// HEAD written by a newer format exits 78 with its reason and systemd does +// not start it again: zero restarts after the restart interval, and the +// store's bytes and HEAD's record unchanged. The control: a process of the +// same unit policy that exits 1 is restarted. +func TestSystemdNewerFormatExits78WithoutRestart(t *testing.T) { + if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" { + t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof") + } + if os.Geteuid() != 0 { + t.Fatal("systemd qualification needs root") + } + if os.Getenv("CHUNKSTORE_WEED") == "" { + t.Fatal("real CHUNKSTORE_WEED binary required") + } + if err := os.MkdirAll(durable.HostVolumeLockDir, 0o700); err != nil { + t.Fatalf("host volume lock directory: %v", err) + } + fixture := newGAP1Fixture(t) + root := fixture.root + bin := filepath.Join(root, "bin") + if err := os.Mkdir(bin, 0755); err != nil { + t.Fatal(err) + } + for _, name := range []string{"blockvolume", "blockmaster"} { + if pre := os.Getenv("SWB_PREBUILT_BIN"); pre != "" { // a host without a Go toolchain: binaries of the same commit + raw, err := os.ReadFile(filepath.Join(pre, name)) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(bin, name), raw, 0o755); err != nil { + t.Fatal(err) + } + continue + } + buildCtx, buildCancel := context.WithTimeout(context.Background(), 2*time.Minute) + cmd := exec.CommandContext(buildCtx, "go", "build", "-p", "4", "-o", filepath.Join(bin, name), "../"+name) + cmd.WaitDelay = time.Second + out, err := cmd.CombinedOutput() + buildCancel() + if err != nil { + t.Fatalf("real binary build: %v %s", err, out) + } + } + shipped := gap1ShippedPolicy(t) + stem := fmt.Sprintf("newerfmt-%d", time.Now().UnixNano()) + + // Control: the same unit policy restarts a process that exits 1. + control1 := stem + "-exit1" + fixture.start(t, control1, true, "/bin/sh", "-c", "exit 1") + waitGAP1(t, "control: an exit 1 was not restarted under the shipped policy", 30*time.Second, func() bool { + return gap1Unit(t, control1)["NRestarts"] != "0" + }) + restarts := gap1Unit(t, control1)["NRestarts"] // read before the stop, which resets it + gap1Systemctl(t, "stop", control1) + t.Logf("control: exit 1 restarted (NRestarts=%s) under Restart=%s RestartPreventExitStatus=%s", restarts, shipped["Restart"], shipped["RestartPreventExitStatus"]) + + cluster := startWorkspaceWeedAt(t, filepath.Join(root, "weed")) + gap1PreserveFailure(t, root, cluster.dir) + volume := stem + base := "/" + stem + masterAddr := leaseBinaryAddress(t) + target, masterListen := gap1TargetAddresses(t, masterAddr) + dataAddr, ctrlAddr, statusAddr, nvmeAddr := leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t) + cfg := fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\n - server_id: s2\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n - id: %s\n size_bytes: 262144\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: r1\n source: existing_replica\n", dataAddr, ctrlAddr, target.dataAddr, target.ctrlAddr, volume) + spec := filepath.Join(root, "cluster.yaml") + if err := os.WriteFile(spec, []byte(cfg), 0600); err != nil { + t.Fatal(err) + } + tlsDir := gap1WriteTLS(t, root, target) + fixture.start(t, stem+"-master", false, filepath.Join(bin, "blockmaster"), + "--listen", masterListen, "--tls-cert", filepath.Join(tlsDir, "master.crt"), "--tls-key", filepath.Join(tlsDir, "master.key"), + "--tls-client-ca", filepath.Join(tlsDir, "ca.crt"), "--role-file", filepath.Join(tlsDir, "roles"), "--audit-log", filepath.Join(tlsDir, "audit.log"), "--authority-store", filepath.Join(root, "auth"), "--lifecycle-store", filepath.Join(root, "life"), + "--cluster-spec", spec, "--lifecycle-product-loop-interval", "200ms", "--expected-slots-per-volume", "1", + "--workspace-rpc", "--chunk-filer", cluster.filerGRPC, "--chunk-path", base) + w4WaitTCP(t, masterAddr, 20*time.Second) + admin, err := link.ClientCredentials(link.TLSFiles{Cert: filepath.Join(tlsDir, "admin.crt"), Key: filepath.Join(tlsDir, "admin.key"), CA: filepath.Join(tlsDir, "ca.crt")}, "") + if err != nil { + t.Fatal(err) + } + conn, err := grpc.NewClient(masterAddr, admin) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + var layoutID layout.VolumeID + waitGAP1(t, "master never resolved the volume's layout identity", 20*time.Second, func() bool { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + id, e := lifecycleclient.ResolveVolume(ctx, control.NewLifecycleServiceClient(conn), volume) + layoutID = id + return e == nil + }) + store := filepath.Join(root, "store") + args := []string{"--master", masterAddr, "--server-id", "s1", + "--master-tls-cert", filepath.Join(tlsDir, "s1.crt"), "--master-tls-key", filepath.Join(tlsDir, "s1.key"), "--master-ca", filepath.Join(tlsDir, "ca.crt"), + "--volume-id", volume, "--replica-id", "r1", "--layout-id", layoutID.String(), + "--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--heartbeat-interval", "200ms", "--t1-readiness", "--status-addr", statusAddr, + "--durable-root", store, "--durable-impl", "walstore-chunk", "--durable-blocks", "64", + "--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease", + "--nvme-listen", nvmeAddr, "--nvme-subsysnqn", "nqn.2026-11.test:" + stem} + bootstrap := stem + "-bootstrap" + fixture.start(t, bootstrap, false, filepath.Join(bin, "blockvolume"), args...) + waitGAP1(t, "bootstrap did not attach under a real lease", 60*time.Second, func() bool { return gap1Operational(t, statusAddr, volume) }) + gap1Systemctl(t, "stop", bootstrap) + waitGAP1(t, "bootstrap still running", 30*time.Second, func() bool { return gap1Unit(t, bootstrap)["MainPID"] == "0" }) + + // refusedOnce starts a restarting unit and requires it to exit 78 with + // reason, then stay down past the restart interval with zero restarts. + refusedOnce := func(unit, reason string) { + t.Helper() + fixture.start(t, unit, true, filepath.Join(bin, "blockvolume"), args...) + waitGAP1(t, unit+": never exited 78", 120*time.Second, func() bool { + u := gap1Unit(t, unit) + return u["MainPID"] == "0" && u["ExecMainStatus"] == "78" + }) + time.Sleep(12 * time.Second) // past RestartSec (shipped 5s), twice + u := gap1Unit(t, unit) + if u["NRestarts"] != "0" || u["ExecMainStatus"] != "78" || u["MainPID"] != "0" { + t.Fatalf("%s: restarted or running after its 78: %+v", unit, u) + } + out, _ := exec.Command("journalctl", "-u", unit, "--no-pager", "-o", "cat").CombinedOutput() + if want := "exiting status=78 reason=" + reason; !strings.Contains(string(out), want) { + t.Fatalf("%s: journal lacks %q:\n%s", unit, want, out) + } + t.Logf("%s: exit 78 %s, NRestarts=0 after %s", unit, reason, shipped["RestartSec"]) + gap1Systemctl(t, "reset-failed", unit) + } + + // 1. The local store written by a newer format: both descriptor slots + // carry the chunk-state marker above what this binary reads. + var storeFile string // the one file under the durable root that starts with the store's superblock magic + if err := filepath.Walk(store, func(p string, fi os.FileInfo, err error) error { + if err != nil || !fi.Mode().IsRegular() || fi.Size() < 8192 { + return err + } + head := make([]byte, 4) + if f, err := os.Open(p); err == nil { + _, _ = f.Read(head) + _ = f.Close() + } + if string(head) == "SWBK" { + if storeFile != "" { + t.Fatalf("two stores under %s: %s, %s", store, storeFile, p) + } + storeFile = p + } + return nil + }); err != nil { + t.Fatal(err) + } + if storeFile == "" { + t.Fatalf("no store under %s", store) + } + original, err := os.ReadFile(storeFile) + if err != nil { + t.Fatal(err) + } + marked := append([]byte(nil), original...) + for _, off := range []int{0, 4096} { // descriptor slots A and B, 4096 bytes each, CRC32C in the last 4 + slot := marked[off : off+4096] + binary.LittleEndian.PutUint16(slot[306:], 9) // a chunk-state format newer than any this binary reads + binary.LittleEndian.PutUint64(slot[312:], 1) + binary.LittleEndian.PutUint32(slot[4092:], crc32.Checksum(slot[:4092], crc32.MakeTable(crc32.Castagnoli))) + } + if err := os.WriteFile(storeFile, marked, 0o644); err != nil { + t.Fatal(err) + } + refusedOnce(stem+"-store", "store_format_newer") + if after, err := os.ReadFile(storeFile); err != nil || !bytes.Equal(after, marked) { + t.Fatalf("the refused open changed the store (%v)", err) + } + if err := os.WriteFile(storeFile, original, 0o644); err != nil { + t.Fatal(err) + } + + // 2. A HEAD written by a newer version. + ref := chunkstore.VolumeRef{Name: volume, ID: layoutID} + cl := cluster.client(t, "") + dir := path.Join(base, ref.Dir()) + ctx := context.Background() + entry, err := cl.LookupEntry(ctx, dir, "HEAD") + if err != nil { + t.Fatal(err) + } + var head map[string]any + if err := json.Unmarshal(entry.Content, &head); err != nil { + t.Fatalf("HEAD record: %v", err) + } + head["version"] = 9 + newer, err := json.Marshal(head) + if err != nil { + t.Fatal(err) + } + entry.Content = newer + if err := cl.UpdateEntry(ctx, dir, entry, nil); err != nil { + t.Fatal(err) + } + refusedOnce(stem+"-head", "head_newer_version") + if after, err := cl.LookupEntry(ctx, dir, "HEAD"); err != nil || !bytes.Equal(after.Content, newer) { + t.Fatalf("the refused start changed HEAD (%v)", err) + } +} diff --git a/seaweed-block/cmd/blockvolume/newer_version_exit_test.go b/seaweed-block/cmd/blockvolume/newer_version_exit_test.go new file mode 100644 index 0000000000..c4273a3768 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/newer_version_exit_test.go @@ -0,0 +1,93 @@ +package main + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// exitNewerVersion is a startup outcome that ended on a HEAD written by a +// newer version. +type exitNewerVersion struct{ exitStartupOutcome } + +func (exitNewerVersion) ChunkStartupNewerVersion(string, uint64) bool { return true } + +// A startup ended on a HEAD written by a newer version exits 78 +// head_newer_version (no restart: a restart reads the same HEAD), where the +// same ended startup otherwise exits the restartable 75. +func TestANewerHeadVersionExits78NotRestartable(t *testing.T) { + h, _ := exitAuthorityHost(t) + e := newProcessExit(context.Background()) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, &exitNewerVersion{exitStartupOutcome{expired: true}}) { + t.Fatal("the newer-version startup did not end the process") + } + if out := <-e.decision; out.code != 78 || out.reason != "head_newer_version" { + t.Fatalf("newer-version startup exit = %+v, want 78 head_newer_version", out) + } + h2, _ := exitAuthorityHost(t) + e2 := newProcessExit(context.Background()) + chooseChunkStartupExit(e2, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h2, &exitStartupOutcome{expired: true}) + if out := <-e2.decision; out.code != 75 { + t.Fatalf("control: an ended startup without the refusal exits %+v, want 75", out) + } +} + +// A fatal durable open of a store written by a newer format exits 78 +// store_format_newer; any other fatal open exits 1 as before. +func TestAStoreOfANewerFormatExits78(t *testing.T) { + if code, reason := durableOpenFatalExit(fmt.Errorf("durable: OpenWALStore x: %w", storage.ErrStoreFormatNewer)); code != 78 || reason != "store_format_newer" { + t.Fatalf("newer-format store exit = %d %q, want 78 store_format_newer", code, reason) + } + if code, reason := durableOpenFatalExit(errors.New("durable: OpenWALStore x: invalid superblock")); code != 1 || reason != "" { + t.Fatalf("other fatal open exit = %d %q, want 1", code, reason) + } +} + +// A master's final refusal keeps its exit when the same startup also ended +// on a newer HEAD version: MOVED stays 78 moved, FINAL stays 79 revoked. +func TestAMasterFinalExitWinsOverANewerHeadVersion(t *testing.T) { + for _, tc := range []struct { + kind control.WorkspaceLeaseRefusal_Kind + final string + code int + reason string + }{ + {control.WorkspaceLeaseRefusal_MOVED, "moved", 78, "moved"}, + {control.WorkspaceLeaseRefusal_FINAL, "revoked", 79, "revoked"}, + } { + t.Run(tc.final, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + refusal, err := status.New(codes.FailedPrecondition, "final refusal").WithDetails(&control.WorkspaceLeaseRefusal{Kind: tc.kind}) + if err != nil { + t.Fatal(err) + } + h, _ := exitAuthorityHost(t, func(s *exitAssignmentStream) { s.streamRefuse = refusal.Err() }) + for { + if _, final := h.MasterWaitState(); final == tc.final { + break + } + select { + case <-ctx.Done(): + t.Fatalf("the master's %s refusal never reached the host", tc.final) + case <-time.After(time.Millisecond): + } + } + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, &exitNewerVersion{exitStartupOutcome{expired: true}}) { + t.Fatal("no startup decision") + } + if out := <-e.decision; out.code != tc.code || out.reason != tc.reason { + t.Fatalf("final %s with a newer HEAD version chose %+v; want %d %s", tc.final, out, tc.code, tc.reason) + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/nvme_ana_provider.go b/seaweed-block/cmd/blockvolume/nvme_ana_provider.go new file mode 100644 index 0000000000..e4e132829e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/nvme_ana_provider.go @@ -0,0 +1,82 @@ +package main + +import ( + "encoding/binary" + "hash/fnv" + + "github.com/seaweedfs/seaweed-block/core/engine" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/host/volume" +) + +type projectionANAProvider struct { + view *volume.AdapterProjectionView + volumeID string + replicaID string +} + +var _ nvme.ANAProvider = (*projectionANAProvider)(nil) + +func newProjectionANAProvider(view *volume.AdapterProjectionView, volumeID, replicaID string, _ ...string) *projectionANAProvider { + return &projectionANAProvider{ + view: view, + volumeID: volumeID, + replicaID: replicaID, + } +} + +func (p *projectionANAProvider) ANAState() nvme.ANAState { + if p == nil || p.view == nil { + return nvme.ANAInaccessible + } + fp := p.view.Projection() + if fp.VolumeID != p.volumeID || fp.ReplicaID != p.replicaID { + return nvme.ANAInaccessible + } + ep := p.view.EngineProjection() + if fp.Healthy { + return nvme.ANAOptimized + } + switch ep.Mode { + case engine.ModeRecovering: + return nvme.ANAChange + case engine.ModeHealthy, engine.ModeIdle: + return nvme.ANANonOptimized + case engine.ModeDegraded: + return nvme.ANAInaccessible + default: + return nvme.ANAChange + } +} + +func (p *projectionANAProvider) ANAChangeCount() uint64 { + if p == nil || p.view == nil { + return 1 + } + ep := p.view.EngineProjection() + const maxUint32 = uint64(^uint32(0)) + if ep.Epoch <= maxUint32 && ep.EndpointVersion <= maxUint32 { + count := uint64(uint32(ep.Epoch))<<32 | uint64(uint32(ep.EndpointVersion)) + if count == 0 { + return 1 + } + return count + } + var buf [16]byte + binary.LittleEndian.PutUint64(buf[0:8], ep.Epoch) + binary.LittleEndian.PutUint64(buf[8:16], ep.EndpointVersion) + h := fnv.New64a() + _, _ = h.Write(buf[:]) + count := h.Sum64() + if count == 0 { + return 1 + } + return count +} + +func (p *projectionANAProvider) ANAGroupID() uint32 { + // Linux validates ANA group descriptors against Identify Controller's + // ANAGRPMAX/NANAGRPID. The current target exposes one namespace and one ANA + // group, so the only valid advertised group id is the dense group 1. + return 1 +} diff --git a/seaweed-block/cmd/blockvolume/nvme_ana_provider_test.go b/seaweed-block/cmd/blockvolume/nvme_ana_provider_test.go new file mode 100644 index 0000000000..fbe99b3f13 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/nvme_ana_provider_test.go @@ -0,0 +1,98 @@ +package main + +import ( + "os" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/engine" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/host/volume" +) + +func TestProjectionANAProvider_StateMapping(t *testing.T) { + tests := []struct { + name string + mode engine.Mode + superseded bool + want nvme.ANAState + }{ + {name: "healthy", mode: engine.ModeHealthy, want: nvme.ANAOptimized}, + {name: "superseded healthy", mode: engine.ModeHealthy, superseded: true, want: nvme.ANANonOptimized}, + {name: "recovering", mode: engine.ModeRecovering, want: nvme.ANAChange}, + {name: "degraded", mode: engine.ModeDegraded, want: nvme.ANAInaccessible}, + {name: "idle", mode: engine.ModeIdle, want: nvme.ANANonOptimized}, + } + 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: 2}}, + "v1", + "r1", + aluaSupersedeProbe{yes: tt.superseded}, + ) + prov := newProjectionANAProvider(view, "v1", "r1") + if got := prov.ANAState(); got != tt.want { + t.Fatalf("ANAState()=%#x want %#x", got, tt.want) + } + }) + } +} + +func TestProjectionANAProvider_GroupIDIsDenseAndWithinAdvertisedRange(t *testing.T) { + view1 := volume.NewAdapterProjectionView( + aluaProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy}}, + "v1", + "r1", + nil, + ) + r1a := newProjectionANAProvider(view1, "v1", "r1", "nqn.2026-05.io.seaweedfs:v1") + r1b := newProjectionANAProvider(view1, "v1", "r1", "nqn.2026-05.io.seaweedfs:v1") + + if got := r1a.ANAGroupID(); got != 1 { + t.Fatalf("ANAGroupID()=%d want 1 for single-group ANA", got) + } + if r1a.ANAGroupID() != r1b.ANAGroupID() { + t.Fatalf("same replica produced unstable ANA group: %d vs %d", r1a.ANAGroupID(), r1b.ANAGroupID()) + } +} + +func TestProjectionANAProvider_ChangeCountTracksLineage(t *testing.T) { + view := volume.NewAdapterProjectionView( + aluaProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 3, EndpointVersion: 7}}, + "v1", + "r1", + nil, + ) + prov := newProjectionANAProvider(view, "v1", "r1") + + want := uint64(3)<<32 | 7 + if got := prov.ANAChangeCount(); got != want { + t.Fatalf("ANAChangeCount()=%d want %d", got, want) + } +} + +func TestProjectionANAProvider_FailsClosedOnIdentityMismatch(t *testing.T) { + view := volume.NewAdapterProjectionView( + aluaProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy}}, + "v1", + "r1", + nil, + ) + prov := newProjectionANAProvider(view, "v1", "r2") + if got := prov.ANAState(); got != nvme.ANAInaccessible { + t.Fatalf("identity mismatch ANAState()=%#x want %#x", got, nvme.ANAInaccessible) + } +} + +func TestProjectionANAProvider_DoesNotImportControlTruthDomains(t *testing.T) { + body, err := os.ReadFile("nvme_ana_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 ANA provider must not import %s", forbidden) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/nvme_controller_id.go b/seaweed-block/cmd/blockvolume/nvme_controller_id.go new file mode 100644 index 0000000000..2efe7bf44c --- /dev/null +++ b/seaweed-block/cmd/blockvolume/nvme_controller_id.go @@ -0,0 +1,41 @@ +package main + +import ( + "hash/fnv" + "strconv" +) + +const maxNVMeControllerID uint32 = 0xffef + +func nvmeControllerIDFromReplicaID(replicaID string) uint16 { + if n, ok := trailingDecimal(replicaID); ok { + if n == 0 { + return 1 + } + if n > uint64(maxNVMeControllerID) { + n = uint64(maxNVMeControllerID) + } + return uint16(n) + } + h := fnv.New32a() + _, _ = h.Write([]byte(replicaID)) + return uint16(h.Sum32()%maxNVMeControllerID + 1) +} + +func trailingDecimal(s string) (uint64, bool) { + if s == "" { + return 0, false + } + start := len(s) + for start > 0 && s[start-1] >= '0' && s[start-1] <= '9' { + start-- + } + if start == len(s) { + return 0, false + } + n, err := strconv.ParseUint(s[start:], 10, 64) + if err != nil { + return 0, false + } + return n, true +} diff --git a/seaweed-block/cmd/blockvolume/nvme_controller_id_test.go b/seaweed-block/cmd/blockvolume/nvme_controller_id_test.go new file mode 100644 index 0000000000..b98c54180b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/nvme_controller_id_test.go @@ -0,0 +1,31 @@ +package main + +import "testing" + +func TestNVMeControllerIDFromReplicaID_DenseReplicaSuffixes(t *testing.T) { + tests := map[string]uint16{ + "r1": 1, + "r2": 2, + "replica3": 3, + "r0": 1, + "r65519": uint16(maxNVMeControllerID), + "r65520": uint16(maxNVMeControllerID), + "r999999999999": uint16(maxNVMeControllerID), + } + for replicaID, want := range tests { + if got := nvmeControllerIDFromReplicaID(replicaID); got != want { + t.Fatalf("nvmeControllerIDFromReplicaID(%q)=%d want %d", replicaID, got, want) + } + } +} + +func TestNVMeControllerIDFromReplicaID_HashFallbackIsStableAndNonReserved(t *testing.T) { + a := nvmeControllerIDFromReplicaID("east-primary") + b := nvmeControllerIDFromReplicaID("east-primary") + if a != b { + t.Fatalf("hash fallback unstable: %d vs %d", a, b) + } + if a == 0 || a == 0xffff { + t.Fatalf("hash fallback returned reserved CNTLID %d", a) + } +} diff --git a/seaweed-block/cmd/blockvolume/nvme_host_retry_integration_test.go b/seaweed-block/cmd/blockvolume/nvme_host_retry_integration_test.go new file mode 100644 index 0000000000..13392f161b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/nvme_host_retry_integration_test.go @@ -0,0 +1,57 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "fmt" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" +) + +func TestInitiatorFlushRetriesTransientCompletion(t *testing.T) { + client, server := net.Pipe() + defer client.Close() + defer server.Close() + _ = server.SetDeadline(time.Now().Add(5 * time.Second)) + c := &nvmeInitiator{io: client, r: nvme.NewReader(client), w: nvme.NewWriter(client)} + done := make(chan error, 1) + go func() { + r, w := nvme.NewReader(server), nvme.NewWriter(server) + for i := 0; i < 6; i++ { + h, err := r.Dequeue() + if err != nil { + done <- err + return + } + if h.Type != 4 { + done <- fmt.Errorf("command type %d", h.Type) + return + } + var cmd nvme.CapsuleCommand + if err = r.Receive(&cmd); err != nil { + done <- err + return + } + if cmd.OpCode != 0 || cmd.CID != uint16(i+1) { + done <- fmt.Errorf("retry command %+v", cmd) + return + } + resp := nvme.CapsuleResponse{CID: cmd.CID} + if i < 5 { + resp.Status = 0x0104 + } + if err = w.SendHeaderOnly(5, &resp, 16); err != nil { + done <- err + return + } + } + done <- nil + }() + c.flush(t) + if err := <-done; err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/cmd/blockvolume/nvme_retry_test.go b/seaweed-block/cmd/blockvolume/nvme_retry_test.go new file mode 100644 index 0000000000..eaaf8b4717 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/nvme_retry_test.go @@ -0,0 +1,122 @@ +package main_test + +import ( + "errors" + "fmt" + "strings" + "testing" + "time" +) + +// nvmeHostMaxRetries is the Linux NVMe host's default retry count for a +// command whose status has Do Not Retry clear (nvme_core max_retries). +const nvmeHostMaxRetries = 5 + +// nvmeStatusError is a completion with a non-zero status. Bit 15 of the +// status field is Do Not Retry. +type nvmeStatusError struct { + op string + status uint16 +} + +func (e *nvmeStatusError) Error() string { return fmt.Sprintf("nvme %s status 0x%04x", e.op, e.status) } + +func (e *nvmeStatusError) retryable() bool { return e.status&0x8000 == 0 } + +// retryLikeHost runs op as the Linux NVMe host runs a command: a completion +// whose status has Do Not Retry clear is retried, at most max times; it +// returns the number of such refusals. When max retries are used up the +// error is returned, as the host returns EIO then. A status with Do Not +// Retry set, or any other error (transport, lost or unexpected bytes), is +// returned at once. +func retryLikeHost(max int, op func() error) (refused int, err error) { + return retryLikeHostReporting(max, op, nil) +} + +func retryLikeHostReporting(max int, op func() error, report func(int, uint16)) (refused int, err error) { + started := time.Now() + for { + err = op() + var se *nvmeStatusError + if err == nil || !errors.As(err, &se) || !se.retryable() { + return refused, err + } + refused++ + if report != nil { + report(refused, se.status) + } + if refused > max { + return refused, fmt.Errorf("%w: refused %d times, %d retries used up, elapsed=%s", err, refused, max, time.Since(started)) + } + } +} + +func TestRetryLikeHostRetriesOnlyDNRClearStatusFiveTimes(t *testing.T) { + busy := &nvmeStatusError{op: "Write", status: 0x0104} // namespace not ready, DNR clear + permanent := &nvmeStatusError{op: "Write", status: 0x8004} // DNR set + script := func(errs ...error) (func() error, *int) { + calls := 0 + return func() error { + calls++ + if calls <= len(errs) { + return errs[calls-1] + } + return nil + }, &calls + } + repeat := func(e error, n int) []error { + out := make([]error, n) + for i := range out { + out[i] = e + } + return out + } + for _, tc := range []struct { + name string + max int + errs []error + refused int + calls int + fails bool + }{ + {"five refusals then success", nvmeHostMaxRetries, repeat(busy, 5), 5, 6, false}, + {"six refusals use up the retries", nvmeHostMaxRetries, repeat(busy, 6), 6, 6, true}, + {"retries off fails on the first refusal", 0, repeat(busy, 1), 1, 1, true}, + {"do not retry set fails at once", nvmeHostMaxRetries, []error{permanent}, 0, 1, true}, + {"a transport error fails at once", nvmeHostMaxRetries, []error{errors.New("nvme Write: want R2T: EOF")}, 0, 1, true}, + {"success", nvmeHostMaxRetries, nil, 0, 1, false}, + } { + t.Run(tc.name, func(t *testing.T) { + op, calls := script(tc.errs...) + refused, err := retryLikeHost(tc.max, op) + if refused != tc.refused || *calls != tc.calls || (err != nil) != tc.fails { + t.Fatalf("refused %d calls %d err %v; want refused %d calls %d fails %v", refused, *calls, err, tc.refused, tc.calls, tc.fails) + } + }) + } +} + +func TestRetryLikeHostReportsExhaustedDuration(t *testing.T) { + _, err := retryLikeHost(nvmeHostMaxRetries, func() error { return &nvmeStatusError{op: "Write", status: 0x0104} }) + if err == nil || !strings.Contains(err.Error(), "elapsed=") { + t.Fatalf("missing exhaustion duration: %v", err) + } +} + +func TestRetryLikeHostReportsEveryRetryableStatus(t *testing.T) { + var statuses []uint16 + _, err := retryLikeHostReporting(5, func() error { return &nvmeStatusError{op: "Write", status: 0x0104} }, func(attempt int, status uint16) { + if attempt != len(statuses)+1 { + t.Fatalf("attempt %d", attempt) + } + statuses = append(statuses, status) + }) + if err == nil || len(statuses) != 6 { + t.Fatalf("statuses=%v err=%v", statuses, err) + } + for _, status := range statuses { + if status != 0x0104 { + t.Fatalf("status 0x%04x", status) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/nvme_witness_integration_test.go b/seaweed-block/cmd/blockvolume/nvme_witness_integration_test.go new file mode 100644 index 0000000000..fc06c7ab9e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/nvme_witness_integration_test.go @@ -0,0 +1,160 @@ +//go:build linux && subprocess && chunkstore_integration + +// The NVMe/TCP witness client of the real-binary tests: connect, write with +// a flush, read back exactly. +package main_test + +import ( + "bytes" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" +) + +// This small initiator uses the same exported wire types and admin/IO queue +// handshake as core/frontend/nvme/client_support_test.go. It talks only to the +// real blockvolume in this harness; no kernel device or unrelated NQN is used. +type gap1NVMe struct { + admin, io net.Conn + r *nvme.Reader + w *nvme.Writer + cid uint16 +} + +func gap1ConnectNVMe(t *testing.T, addr, nqn string) *gap1NVMe { + t.Helper() + c := &gap1NVMe{} + t.Cleanup(c.close) + var controller uint16 = 0xffff + for q := uint16(0); q < 2; q++ { + conn, err := net.DialTimeout("tcp", addr, 5*time.Second) + if err != nil { + t.Fatal(err) + } + if q == 0 { + c.admin = conn + } else { + c.io = conn + } + _ = conn.SetDeadline(time.Now().Add(10 * time.Second)) + r, w := nvme.NewReader(conn), nvme.NewWriter(conn) + if err := w.SendHeaderOnly(0, &nvme.ICRequest{PDUFormatVersion: 0, PDUMaxR2T: 1}, 120); err != nil { + t.Fatal(err) + } + h, err := r.Dequeue() + if err != nil || h.Type != 1 { + t.Fatalf("NVMe IC response: %+v %v", h, err) + } + var ic nvme.ICResponse + if err := r.Receive(&ic); err != nil { + t.Fatal(err) + } + c.cid++ + cmd := nvme.CapsuleCommand{OpCode: 0x7f, FCType: 1, CID: c.cid, D10: uint32(q) << 16} + data := make([]byte, 1024) + (&nvme.ConnectData{HostID: [16]byte{1, 2, 3, 4}, CNTLID: controller, SubNQN: nqn, HostNQN: "nqn.2026-11.test:gap1-host"}).Marshal(data) + if err := w.SendWithData(4, 0, &cmd, 64, data); err != nil { + t.Fatal(err) + } + reply := gap1NVMeReply(t, r, c.cid) + if q == 0 { + controller = uint16(reply.DW0) + if controller == 0 { + t.Fatal("no controller assigned") + } + } + if q == 1 { + c.r, c.w = r, w + } + } + return c +} + +func (c *gap1NVMe) close() { + if c.io != nil { + _ = c.io.Close() + } + if c.admin != nil { + _ = c.admin.Close() + } +} + +func gap1NVMeReply(t *testing.T, r *nvme.Reader, cid uint16) nvme.CapsuleResponse { + t.Helper() + h, err := r.Dequeue() + if err != nil || h.Type != 5 { + t.Fatalf("NVMe capsule header: %+v %v", h, err) + } + var reply nvme.CapsuleResponse + if err := r.Receive(&reply); err != nil { + t.Fatal(err) + } + if reply.CID != cid || reply.Status != 0 { + t.Fatalf("NVMe CID %d: %+v", cid, reply) + } + return reply +} + +func (c *gap1NVMe) writeFlush(t *testing.T, lba uint64, payload []byte) { + t.Helper() + if len(payload) != 4096 { + t.Fatal("harness writes exactly one block") + } + c.cid++ + cmd := nvme.CapsuleCommand{OpCode: 1, CID: c.cid, NSID: 1, D10: uint32(lba), D11: uint32(lba >> 32)} + if err := c.w.SendHeaderOnly(4, &cmd, 64); err != nil { + t.Fatal(err) + } + h, err := c.r.Dequeue() + if err != nil || h.Type != 9 { + t.Fatalf("NVMe R2T: %+v %v", h, err) + } + var r2t nvme.R2THeader + if err := c.r.Receive(&r2t); err != nil { + t.Fatal(err) + } + if r2t.CCCID != c.cid || r2t.DATAO != 0 || r2t.DATAL != uint32(len(payload)) { + t.Fatalf("wrong R2T %+v", r2t) + } + data := nvme.H2CDataHeader{CCCID: c.cid, TAG: r2t.TAG, DATAO: 0, DATAL: uint32(len(payload))} + if err := c.w.SendWithData(6, 0, &data, 16, payload); err != nil { + t.Fatal(err) + } + gap1NVMeReply(t, c.r, c.cid) + c.cid++ + flush := nvme.CapsuleCommand{OpCode: 0, CID: c.cid, NSID: 1} + if err := c.w.SendHeaderOnly(4, &flush, 64); err != nil { + t.Fatal(err) + } + gap1NVMeReply(t, c.r, c.cid) // only this completed Flush makes the record durable +} + +func (c *gap1NVMe) readExact(t *testing.T, lba uint64, want []byte) { + t.Helper() + c.cid++ + cmd := nvme.CapsuleCommand{OpCode: 2, CID: c.cid, NSID: 1, D10: uint32(lba), D11: uint32(lba >> 32)} + if err := c.w.SendHeaderOnly(4, &cmd, 64); err != nil { + t.Fatal(err) + } + h, err := c.r.Dequeue() + if err != nil || h.Type != 7 { + t.Fatalf("NVMe read data: %+v %v", h, err) + } + var header nvme.C2HDataHeader + if err := c.r.Receive(&header); err != nil { + t.Fatal(err) + } + if header.CCCID != c.cid || header.DATAO != 0 || header.DATAL != uint32(len(want)) || c.r.Length() != uint32(len(want)) { + t.Fatalf("wrong read frame %+v length%d", header, c.r.Length()) + } + got := make([]byte, c.r.Length()) + if err := c.r.ReceiveData(got); err != nil { + t.Fatal(err) + } + gap1NVMeReply(t, c.r, c.cid) + if !bytes.Equal(got, want) { + t.Fatal("fsync-acknowledged NVMe record changed after supervised restart") + } +} diff --git a/seaweed-block/cmd/blockvolume/owner_endpoints_helper_test.go b/seaweed-block/cmd/blockvolume/owner_endpoints_helper_test.go new file mode 100644 index 0000000000..16aa06ee6b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/owner_endpoints_helper_test.go @@ -0,0 +1,53 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// The procedure gate needs positive evidence from every recipient: an owner's +// delivery or the documented MOVED refusal before any assignment is delivered. +// A refusal never excuses wrong endpoints in a delivery that did occur. +func TestWrongOwnerEndpointsNeedsPositiveEvidenceFromEachRecipient(t *testing.T) { + owner := bvHost{id: "s2", data: "127.0.0.1:2001", ctrl: "127.0.0.1:2002"} + dir := t.TempDir() + good := `blockvolume: assignment stream delivery process="X" server="s2" volume="v1" replica="r1" epoch=2 ev=1 data="127.0.0.1:2001" ctrl="127.0.0.1:2002"` + wrong := `blockvolume: assignment stream delivery process="X" server="s2" volume="v1" replica="r1" epoch=2 ev=2 data="127.0.0.1:1001" ctrl="127.0.0.1:1002"` + other := `blockvolume: assignment stream delivery process="X" server="s1" volume="v1" replica="r1" epoch=1 ev=1 data="127.0.0.1:1001" ctrl="127.0.0.1:1002"` + moved := `blockvolume: exiting status=78 reason=moved` + logOf := func(name string, lines ...string) *daemon { + p := filepath.Join(dir, name+".log") + if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil { + t.Fatal(err) + } + return &daemon{name: name, log: p} + } + missing := &daemon{name: "gone", log: filepath.Join(dir, "does-not-exist.log")} + for _, c := range []struct { + name string + ds []*daemon + reject string // "" = must pass + }{ + {"both positive", []*daemon{logOf("a1", good), logOf("b1", other, good)}, ""}, + {"second unreadable", []*daemon{logOf("a2", good), missing}, "log unreadable"}, + {"first has no epoch delivery", []*daemon{logOf("a3", other), logOf("b3", good)}, "no epoch delivery logged"}, + {"second carries another host's endpoints", []*daemon{logOf("a4", good), logOf("b4", good, wrong)}, "127.0.0.1:1001"}, + {"first empty log", []*daemon{logOf("a5"), logOf("b5", good)}, "no epoch delivery logged"}, + {"source refused before delivery", []*daemon{logOf("a6", good), logOf("b6", moved)}, ""}, + {"refusal does not excuse wrong endpoints", []*daemon{logOf("a7", good), logOf("b7", wrong, moved)}, "127.0.0.1:1001"}, + {"unclassified exit is not a moved refusal", []*daemon{logOf("a8", good), logOf("b8", "blockvolume: exiting status=78")}, "no epoch delivery logged"}, + {"retry exit is not a moved refusal", []*daemon{logOf("a9", good), logOf("b9", "blockvolume: exiting status=75 reason=assignment_timeout")}, "no epoch delivery logged"}, + } { + bad := wrongOwnerEndpoints(2, owner, c.ds...) + switch { + case c.reject == "" && len(bad) != 0: + t.Errorf("%s: rejected %v, want pass", c.name, bad) + case c.reject != "" && !strings.Contains(strings.Join(bad, "\n"), c.reject): + t.Errorf("%s: got %v, want a rejection naming %q", c.name, bad, c.reject) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/phase0_master_baseline_integration_test.go b/seaweed-block/cmd/blockvolume/phase0_master_baseline_integration_test.go new file mode 100644 index 0000000000..bc5bebc54e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/phase0_master_baseline_integration_test.go @@ -0,0 +1,232 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "fmt" + "sync" + "testing" + "time" +) + +// Phase 0 baseline: what blockmaster's loss costs the guests today, measured +// with real binaries and an in-test NVMe/TCP initiator, so that phase 0 +// (mTLS on the master/holder link) can be gated against it. One write of 4 +// KiB every 10 ms per volume, each with a 30 s command deadline. +// +// (a) blockmaster SIGKILLed and restarted 5 s later under guest writes: +// guest write errors (expected 0) and the write latency; +// (b) blockmaster down 60 s: the time until each volume fences, then, +// with the master back, until it serves again. The harness restarts +// an exited blockvolume after the shipped RestartSec (5 s), as the unit +// does, and counts the starts against the shipped start limit (10 in +// 600 s); +// (c) as (b) with 3 volumes. +// +// The numbers are logged as PHASE0 lines; only (a)'s zero write errors and +// (b)/(c)'s serving again are asserted. + +const ( + baselineEvery = 10 * time.Millisecond + baselineDeadline = 30 * time.Second + unitRestartSec = 5 * time.Second + unitStartLimit = 10 + unitStartLimitSpan = 600 * time.Second +) + +type baselineWriter struct { + mu sync.Mutex + samples []f1Sample + errAt time.Time + err error + stopped chan struct{} + stopOnce sync.Once + done chan struct{} +} + +// startBaselineWriter writes to vol's frontend until stopped or until the +// first failed write (the fence, when the master is gone). +func startBaselineWriter(t *testing.T, env *handoffEnv, key string) *baselineWriter { + t.Helper() + b := env.hosts[key] + c := dialNVMe(t, b.nvme, plannedHandoffNQN) + w := &baselineWriter{stopped: make(chan struct{}), done: make(chan struct{})} + go func() { + defer close(w.done) + defer c.close() + for n := uint64(0); ; n++ { + select { + case <-w.stopped: + return + case <-time.After(baselineEvery): + } + lba := n % 1024 + s := time.Now() + _ = c.io.SetDeadline(s.Add(baselineDeadline)) + err := c.tryWrite(lba, f1Block(b.volume, 0, "phase0", lba)) + w.mu.Lock() + w.samples = append(w.samples, f1Sample{start: s, d: time.Since(s)}) + if err != nil { + w.err, w.errAt = err, time.Now() + } + w.mu.Unlock() + if err != nil { + return + } + } + }() + return w +} + +func (w *baselineWriter) stop() { + w.stopOnce.Do(func() { close(w.stopped) }) + <-w.done +} + +// maxLatency is the longest write that started in [from, to]. +func (w *baselineWriter) maxLatency(from, to time.Time) (time.Duration, int) { + w.mu.Lock() + defer w.mu.Unlock() + var max time.Duration + n := 0 + for _, s := range w.samples { + if !s.start.Before(from) && !s.start.After(to) { + n++ + if s.d > max { + max = s.d + } + } + } + return max, n +} + +func TestPhase0BaselineMasterKilledAndRestartedUnderWrites(t *testing.T) { + env, _ := f1StartEnv(t, f1Config{Volumes: 1}) + vols := f1StartSources(t, env, 1) + w := startBaselineWriter(t, env, vols[0].id) + time.Sleep(10 * time.Second) + killAt := time.Now() + env.masterProcess.kill(t) + time.Sleep(5 * time.Second) + env.masterProcess = env.h.start(t, "blockmaster-restarted", env.h.master, env.masterArgs...) + env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + backAt := time.Now() + time.Sleep(30 * time.Second) + w.stop() + all, n := w.maxLatency(time.Time{}, time.Now()) + around, m := w.maxLatency(killAt, backAt.Add(5*time.Second)) + t.Logf("PHASE0 (a) master SIGKILL + restart after 5 s: writes %d, write errors %d (%v), max write latency %v, max in the kill window (%d writes) %v, master back after %v", + n, map[bool]int{true: 1, false: 0}[w.err != nil], w.err, all.Round(time.Microsecond), m, around.Round(time.Microsecond), backAt.Sub(killAt).Round(time.Millisecond)) + if w.err != nil { + t.Fatalf("phase 0 baseline (a): a guest write failed while the master was down 5 s: %v", w.err) + } +} + +// unitEmulator restarts an exited blockvolume after unitRestartSec, as the +// shipped unit does, and records every exit. +type unitEmulator struct { + mu sync.Mutex + d *daemon + starts []time.Time + exits []string + stop chan struct{} + done chan struct{} +} + +func emulateUnit(t *testing.T, env *handoffEnv, key string, d *daemon) *unitEmulator { + u := &unitEmulator{d: d, starts: []time.Time{time.Now()}, stop: make(chan struct{}), done: make(chan struct{})} + go func() { + defer close(u.done) + for { + u.mu.Lock() + cur := u.d + u.mu.Unlock() + select { + case <-u.stop: + return + case <-cur.done: + } + u.mu.Lock() + u.exits = append(u.exits, fmt.Sprintf("%s exit %d", time.Now().Format("15:04:05.000"), exitCode(cur.err))) + u.mu.Unlock() + select { + case <-u.stop: + return + case <-time.After(unitRestartSec): + } + next := env.h.start(t, fmt.Sprintf("blockvolume-%s-unit-%d", key, len(u.starts)), env.h.volume, env.volArgsFor(env.hosts[key])...) + u.mu.Lock() + u.d, u.starts = next, append(u.starts, time.Now()) + u.mu.Unlock() + } + }() + return u +} + +// startLimitHit reports whether the unit's starts would have exceeded the +// shipped limit (more than unitStartLimit starts within unitStartLimitSpan). +func (u *unitEmulator) startLimitHit() bool { + u.mu.Lock() + defer u.mu.Unlock() + for i := range u.starts { + n := 0 + for _, s := range u.starts[i:] { + if s.Sub(u.starts[i]) <= unitStartLimitSpan { + n++ + } + } + if n > unitStartLimit { + return true + } + } + return false +} + +func phase0MasterDown60s(t *testing.T, n int) { + env, _ := f1StartEnv(t, f1Config{Volumes: n}) + vols := f1StartSources(t, env, n) + writers := make([]*baselineWriter, n) + units := make([]*unitEmulator, n) + for i, v := range vols { + writers[i] = startBaselineWriter(t, env, v.id) + units[i] = emulateUnit(t, env, v.id, v.d) + } + time.Sleep(10 * time.Second) + killAt := time.Now() + env.masterProcess.kill(t) + time.Sleep(60 * time.Second) + env.masterProcess = env.h.start(t, "blockmaster-back", env.h.master, env.masterArgs...) + env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + backAt := time.Now() + for i, v := range vols { + b := env.hosts[v.id] + poll(t, 5*time.Minute, v.id+" never served again after the master came back", func() bool { return volumeFrontendReady(b.status, b.volume) }) + servedAt := time.Now() + probe := startBaselineWriter(t, env, v.id) + time.Sleep(time.Second) + probe.stop() + if probe.err != nil { + t.Fatalf("%s serves again but a write failed: %v", v.id, probe.err) + } + writers[i].stop() + close(units[i].stop) + <-units[i].done + w, u := writers[i], units[i] + u.mu.Lock() + starts, exits := len(u.starts), append([]string(nil), u.exits...) + u.mu.Unlock() + fence := "none" + if w.err != nil { + fence = w.errAt.Sub(killAt).Round(time.Millisecond).String() + } + firstExit := "none" + if len(exits) > 0 { + firstExit = exits[0] + } + t.Logf("PHASE0 (%s) master down 60 s, volume %s: first failed write after %s (%v); exits %v (first %s); starts %d, start limit (%d in %v) hit %v; serving again %v after the master came back", + map[int]string{1: "b", 3: "c"}[n], v.id, fence, w.err, exits, firstExit, starts, unitStartLimit, unitStartLimitSpan, u.startLimitHit(), servedAt.Sub(backAt).Round(time.Millisecond)) + } +} + +func TestPhase0BaselineMasterDown60sOneVolume(t *testing.T) { phase0MasterDown60s(t, 1) } +func TestPhase0BaselineMasterDown60sThreeVolumes(t *testing.T) { phase0MasterDown60s(t, 3) } diff --git a/seaweed-block/cmd/blockvolume/plain_detach_capability_test.go b/seaweed-block/cmd/blockvolume/plain_detach_capability_test.go new file mode 100644 index 0000000000..e49fb06fb7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/plain_detach_capability_test.go @@ -0,0 +1,23 @@ +package main + +import ( + "reflect" + "testing" +) + +func TestPlainDetachCapabilityFlagIsNoop(t *testing.T) { + base := []string{"--master", "127.0.0.1:1", "--server-id", "h1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:2", "--ctrl-addr", "127.0.0.1:3"} + want, err := parseFlags(base) + if err != nil { + t.Fatal(err) + } + for _, arg := range []string{"--chunk-detach-plain-supported", "--chunk-detach-plain-supported=true", "--chunk-detach-plain-supported=false"} { + got, err := parseFlags(append(append([]string{}, base...), arg)) + if err != nil { + t.Fatalf("capability flag unavailable: %s: %v", arg, err) + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("capability flag changed runtime configuration: %s", arg) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go new file mode 100644 index 0000000000..59cdaafe6e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/planned_handoff_checks_test.go @@ -0,0 +1,431 @@ +package main_test + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "testing" +) + +// The checks below read the product's own output for each step of the +// planned hand-over (docs/volume-lifecycle.md). The binary test applies +// them to live output; TestPlannedHandoffChecksReadCapturedProductOutput +// applies them to output captured from the real binaries +// (testdata/planned-handoff), so they run in every default test run. + +func checkShowBeforeStart(out string) error { + return wantLines(out, "volume: v1 (query snapshot, not authority to serve)", "replica: none", "recorded ACK: none") +} + +func checkShowGranted(out string, e uint64) error { + return wantLines(out, "replica: r1", fmt.Sprintf("epoch: %d", e), "lease state: granted", + fmt.Sprintf("holder: r1@%d (logical replica)", e), "recorded ACK: none") +} + +// adoptedEpoch reads E from blockvolume's adoption line. +func adoptedEpoch(line string) (uint64, error) { return adoptedEpochOf("v1", line) } + +// adoptedEpochOf reads E from blockvolume's adoption line for volume vol. +func adoptedEpochOf(vol, line string) (uint64, error) { + e, err := matchUint(regexp.MustCompile(`blockvolume: volume `+regexp.QuoteMeta(vol)+` adopted as PRIMARY at r1@(\d+) `), line) + if err == nil && e == 0 { + err = fmt.Errorf("adopted at epoch 0: %q", line) + } + return e, err +} + +// sealedGen reads G from a plain detach: one JSON object on stdout and +// exactly the sealed-generation line on stderr. +func sealedGen(stdout, stderr string, e uint64) (uint64, error) { + return sealedGenOf(stdout, stderr, "v1", e) +} + +// sealedGenOf reads G from a plain detach of volume vol at epoch e. +func sealedGenOf(stdout, stderr, vol string, e uint64) (uint64, error) { + var a struct { + VolumeID string `json:"volumeID"` + HeadGen uint64 `json:"headGen"` + HeadEpoch uint64 `json:"headEpoch"` + CutLSN uint64 `json:"cutLSN"` + LastWrittenLSN uint64 `json:"lastWrittenLSN"` + } + if err := json.Unmarshal([]byte(stdout), &a); err != nil { + return 0, fmt.Errorf("plain detach stdout is not the JSON answer: %v: %q", err, stdout) + } + if a.VolumeID != vol || a.HeadGen == 0 || a.HeadEpoch != e || a.CutLSN == 0 || a.LastWrittenLSN == 0 { + return 0, fmt.Errorf("plain detach answer %+v; want %s, a generation, epoch %d and both LSNs after a write", a, vol, e) + } + if strings.TrimSpace(stderr) != fmt.Sprintf("sealed HEAD generation: %d", a.HeadGen) { + return 0, fmt.Errorf("plain detach stderr %q; want exactly the sealed generation line", stderr) + } + return a.HeadGen, nil +} + +type detachedBy struct { + Holder string `json:"holder"` + Epoch uint64 `json:"epoch"` + Gen uint64 `json:"gen"` +} + +type headRecord struct { + Gen uint64 `json:"gen"` + Epoch uint64 `json:"epoch"` + Holder string `json:"holder"` + State string `json:"state"` + RemoteLSN uint64 `json:"remoteLSN"` + DetachedBy *detachedBy `json:"detachedBy"` +} + +func parseHead(out string) (headRecord, error) { + var shown struct { + Head *headRecord `json:"head"` + } + if err := json.Unmarshal([]byte(out), &shown); err != nil || shown.Head == nil { + return headRecord{}, fmt.Errorf("chunk show stdout has no head: %v: %q", err, out) + } + return *shown.Head, nil +} + +// sealedHeadLSN checks HEAD after the seal and returns its remote LSN (L). +func sealedHeadLSN(out string, e, g uint64) (uint64, error) { + h, err := parseHead(out) + if err != nil { + return 0, err + } + if h.Gen != g || h.Epoch != e || h.Holder != "s1/r1" || h.State != "detached" || + h.DetachedBy == nil || *h.DetachedBy != (detachedBy{Holder: "s1/r1", Epoch: e, Gen: g}) { + return 0, fmt.Errorf("HEAD after the seal %+v; want gen %d epoch %d holder s1/r1 detached by itself", h, g, e) + } + return h.RemoteLSN, nil +} + +// The layout HEAD exposes the committed position and the master-minted +// holder identity. The old storage HEAD's DetachedBy proof is not a field of +// this format; a detached layout HEAD itself is the committed stop image. +type layoutHeadRecord struct { + Gen uint64 `json:"gen"` + Epoch uint64 `json:"epoch"` + Holder string `json:"holder"` + ClaimID string `json:"claimID"` + Position uint64 `json:"position"` + State string `json:"state"` + Current json.RawMessage `json:"current"` +} + +func parseLayoutHead(out string) (layoutHeadRecord, error) { + var shown struct { + Head *layoutHeadRecord `json:"head"` + } + if err := json.Unmarshal([]byte(out), &shown); err != nil || shown.Head == nil { + return layoutHeadRecord{}, fmt.Errorf("layout show stdout has no head: %v: %q", err, out) + } + return *shown.Head, nil +} + +func sealedLayoutHeadPosition(out string, epoch, gen uint64) (uint64, error) { + h, err := parseLayoutHead(out) + if err != nil { + return 0, err + } + if h.Gen != gen || h.Epoch != epoch || h.Holder != "s1/r1" || h.ClaimID == "" || h.State != "detached" || len(h.Current) == 0 || string(h.Current) == "null" { + return 0, fmt.Errorf("layout HEAD after seal %+v; want committed detached image at gen %d epoch %d holder s1/r1", h, gen, epoch) + } + return h.Position, nil +} + +func checkLayoutHeadReopened(out string, epoch, sealedGen, position uint64) error { + return checkLayoutHeadReopenedBy(out, epoch, sealedGen, position, "s1") +} + +func checkLayoutHeadReopenedBy(out string, epoch, sealedGen, position uint64, host string) error { + h, err := parseLayoutHead(out) + if err != nil { + return err + } + if h.Gen <= sealedGen || h.Epoch != epoch || h.Holder != host+"/r1" || h.ClaimID == "" || h.State != "" || h.Position != position || len(h.Current) == 0 || string(h.Current) == "null" { + return fmt.Errorf("layout HEAD after claim %+v; want live image above gen %d at epoch %d position %d holder %s/r1", h, sealedGen, epoch, position, host) + } + return nil +} + +func checkRevoke(out string, e, g uint64) error { + if !strings.HasPrefix(out, fmt.Sprintf("revocation requested: volume v1 holder r1@%d expiry_ns ", e)) { + return fmt.Errorf("revoke stdout %q", out) + } + return wantLines(out, fmt.Sprintf("operator-stated sealed HEAD generation: %d (not verified); workspace show must report ACK at this generation before move --clean", g)) +} + +func showsAck(out string, e, g uint64) bool { + return hasLine(out, fmt.Sprintf("recorded ACK: r1@%d HEAD generation %d", e, g)) +} + +// movedEpoch reads E2 from the clean move's answer to s1. +func movedEpoch(out string, e, g, l uint64) (uint64, error) { return movedEpochTo(out, e, g, l, "s1") } + +// movedEpochTo reads E2 from the clean move's answer to the target host. +func movedEpochTo(out string, e, g, l uint64, target string) (uint64, error) { + issued := regexp.MustCompile(fmt.Sprintf(`^clean move issued: volume v1 request move-v1-1: r1@%d -> r1@(\d+) on %s \(sealed HEAD gen %d, remote LSN %d\)$`, e, regexp.QuoteMeta(target), g, l)) + first, _, _ := strings.Cut(out, "\n") + e2, err := matchUint(issued, strings.TrimRight(first, "\r")) + if err != nil { + return 0, err + } + if e2 <= e { + return 0, fmt.Errorf("clean move issued epoch %d; want above %d", e2, e) + } + return e2, wantLines(out, fmt.Sprintf("next: start volume v1 on %s (this command moved authority only)", target)) +} + +func checkClaimDone(line string, e2 uint64) error { return checkClaimDoneBy(line, e2, "s1") } + +func checkClaimDoneBy(line string, e2 uint64, host string) error { + if !strings.Contains(line, "durable: HEAD claim for volume=v1 done in") || !strings.Contains(line, fmt.Sprintf(`epoch=%d holder="%s/r1"`, e2, host)) { + return fmt.Errorf("HEAD claim %q; want done at epoch %d holder %s/r1", line, e2, host) + } + return nil +} + +func checkShowMoved(out string, e, e2, g, l uint64) error { + return wantLines(out, fmt.Sprintf("epoch: %d", e2), "lease state: granted", + fmt.Sprintf("holder: r1@%d (logical replica)", e2), "recorded ACK: none", + fmt.Sprintf("move: request=move-v1-1 kind=clean issued=true s1/r1@%d -> s1/r1@%d HEAD generation %d remote LSN %d", e, e2, g, l)) +} + +func checkHeadReopened(out string, e2, g, l uint64) error { + return checkHeadReopenedBy(out, e2, g, l, "s1") +} + +func checkHeadReopenedBy(out string, e2, g, l uint64, host string) error { + h, err := parseHead(out) + if err != nil { + return err + } + if h.State != "active" || h.Epoch != e2 || h.Holder != host+"/r1" || h.Gen <= g || h.RemoteLSN != l || h.DetachedBy != nil { + return fmt.Errorf("HEAD after the reopen %+v; want active, epoch %d, holder %s/r1, gen above %d, remote LSN %d, not detached", h, e2, host, g, l) + } + return nil +} + +// forcedEpoch reads E2 from a forced move's answer (`forced move issued: +// ... r1@E on FROM -> r1@E2 on TO (kept HEAD gen N, remote LSN L)`). +func forcedEpoch(out string, e uint64, from, to string) (uint64, error) { + return forcedEpochOf(out, "v1", e, from, to) +} + +// forcedEpochOf reads E2 from a forced move of volume vol from host from to +// host to. +func forcedEpochOf(out, vol string, e uint64, from, to string) (uint64, error) { + re := regexp.MustCompile(fmt.Sprintf(`(?m)^forced move issued: volume %s request \S+: r1@%d on %s -> r1@(\d+) on %s \(kept HEAD gen \d+, remote LSN \d+\)$`, regexp.QuoteMeta(vol), e, regexp.QuoteMeta(from), regexp.QuoteMeta(to))) + e2, err := matchUint(re, out) + if err == nil && e2 <= e { + err = fmt.Errorf("forced move issued epoch %d; want above %d", e2, e) + } + return e2, err +} + +// forcedKeptLSN reads the remote LSN a forced move kept. +func forcedKeptLSN(out string) (uint64, error) { + return matchUint(regexp.MustCompile(`(?m)^forced move issued: .*\(kept HEAD gen \d+, remote LSN (\d+)\)$`), out) +} + +// previewAdmitted reports whether a force-move --dry-run says admitted. +func previewAdmitted(out string) bool { + return regexp.MustCompile(`(?m)^forced move admitted(: .*)?$`).MatchString(out) +} + +// frontendReady reports whether a /status?volume=v1 body says the frontend +// is ready to serve as primary. +func frontendReady(body []byte) bool { + var st struct{ FrontendPrimaryReady bool } + return json.Unmarshal(body, &st) == nil && st.FrontendPrimaryReady +} + +// checkCleanMoveRefused checks a clean move refused for a missing ACK: exit +// 1 (a failed precondition), nothing on stdout, the documented error. +func checkCleanMoveRefused(stdout, stderr string, code int) error { + if code != 1 || stdout != "" || !strings.Contains(stderr, "workspace clean move needs detached HEAD and matching revocation ACK") { + return fmt.Errorf("clean move without the ACK: exit %d, stdout %q, stderr %q; want exit 1 and the documented refusal", code, stdout, stderr) + } + return nil +} + +// statusPrimary reports whether a /status?volume=v1 body shows a healthy +// primary at epoch. +func statusPrimary(body []byte, epoch uint64) bool { + var st struct { + Epoch uint64 + Healthy bool + AuthorityRole string + } + return json.Unmarshal(body, &st) == nil && st.Epoch == epoch && st.Healthy && st.AuthorityRole == "primary" +} + +func hasLine(out, want string) bool { + for _, l := range strings.Split(out, "\n") { + if strings.TrimRight(l, "\r") == want { + return true + } + } + return false +} + +func wantLines(out string, want ...string) error { + for _, w := range want { + if !hasLine(out, w) { + return fmt.Errorf("no line %q in:\n%s", w, out) + } + } + return nil +} + +func matchUint(re *regexp.Regexp, s string) (uint64, error) { + m := re.FindStringSubmatch(s) + if m == nil { + return 0, fmt.Errorf("%q does not match %s", s, re) + } + return strconv.ParseUint(m[1], 10, 64) +} + +// TestPlannedHandoffChecksReadCapturedProductOutput runs every check on the +// output the real binaries printed in one passing hand-over (E=1, G=3, L=1, +// E2=2), in the refused clean move without an ACK (move-refused, +// show-revoked), and in the procedure gate's move to s2 and forced move +// (move-clean-s2, head-reopened-s2, force-move*, lost-range), and each check +// on an output of another step, which it must refuse. +func TestPlannedHandoffChecksReadCapturedProductOutput(t *testing.T) { + read := func(name string) string { + b, err := os.ReadFile(filepath.Join("testdata", "planned-handoff", name)) + if err != nil { + t.Fatal(err) + } + return strings.ReplaceAll(string(b), "\r\n", "\n") + } + logLine := func(s string) string { + for _, l := range strings.Split(read("logs.txt"), "\n") { + if strings.Contains(l, s) { + return l + } + } + t.Fatalf("logs.txt has no line with %q", s) + return "" + } + ok := func(what string, err error) { + t.Helper() + if err != nil { + t.Errorf("%s: %v", what, err) + } + } + refused := func(what string, err error) { + t.Helper() + if err == nil { + t.Errorf("%s: accepted the output of another step", what) + } + } + const e, g, l, e2 = 1, 3, 1, 2 + + ok("show before start", checkShowBeforeStart(read("show-before-start.stdout"))) + refused("show before start", checkShowBeforeStart(read("show-granted.stdout"))) + if got, err := adoptedEpoch(logLine("adopted as PRIMARY at r1@1 ")); err != nil || got != e { + t.Errorf("adopted epoch %d, %v; want %d", got, err, e) + } + ok("show granted", checkShowGranted(read("show-granted.stdout"), e)) + refused("show granted", checkShowGranted(read("show-acked.stdout"), e)) + if got, err := sealedGen(read("detach-plain.stdout"), read("detach-plain.stderr"), e); err != nil || got != g { + t.Errorf("sealed gen %d, %v; want %d", got, err, g) + } + _, err := sealedGen(read("detach-plain.stdout"), "", e) + refused("sealed gen without its stderr line", err) + if got, err := sealedHeadLSN(read("head-sealed.stdout"), e, g); err != nil || got != l { + t.Errorf("sealed HEAD LSN %d, %v; want %d", got, err, l) + } + _, err = sealedHeadLSN(read("head-reopened.stdout"), e, g) + refused("sealed HEAD", err) + ok("revoke", checkRevoke(read("revoke.stdout"), e, g)) + refused("revoke", checkRevoke(read("move-clean.stdout"), e, g)) + if !showsAck(read("show-acked.stdout"), e, g) || showsAck(read("show-granted.stdout"), e, g) { + t.Error("the ACK line is not told apart from a show without it") + } + if got, err := movedEpoch(read("move-clean.stdout"), e, g, l); err != nil || got != e2 { + t.Errorf("moved epoch %d, %v; want %d", got, err, e2) + } + _, err = movedEpoch(read("move-clean.stdout"), e, g+1, l) + refused("clean move at another generation", err) + ok("claim done", checkClaimDone(logLine(`gen=4 epoch=2 holder="s1/r1"`), e2)) + refused("claim done", checkClaimDone(logLine(`gen=2 epoch=1 holder="s1/r1"`), e2)) + ok("show moved", checkShowMoved(read("show-moved.stdout"), e, e2, g, l)) + refused("show moved", checkShowMoved(read("show-granted.stdout"), e, e2, g, l)) + ok("HEAD reopened", checkHeadReopened(read("head-reopened.stdout"), e2, g, l)) + refused("HEAD reopened", checkHeadReopened(read("head-sealed.stdout"), e2, g, l)) + ok("clean move refused", checkCleanMoveRefused("", read("move-refused.stderr"), 1)) + refused("clean move refused", checkCleanMoveRefused("", read("move-refused.stderr"), 0)) + refused("clean move refused", checkCleanMoveRefused(read("move-clean.stdout"), "", 0)) + if r := read("show-revoked.stdout"); showsAck(r, e, g) || !hasLine(r, "recorded ACK: none") { + t.Error("the revoked show without an ACK is read as acknowledged") + } + // The procedure gate's two-host outputs (a planned move to s2, a forced + // move s1 -> s2 at E=1 -> E2=2 keeping gen 3, LSN 1). + if got, err := movedEpochTo(read("move-clean-s2.stdout"), e, g, l, "s2"); err != nil || got != e2 { + t.Errorf("moved epoch to s2 %d, %v; want %d", got, err, e2) + } + _, err = movedEpochTo(read("move-clean-s2.stdout"), e, g, l, "s1") + refused("clean move to s2 read as a move to s1", err) + ok("HEAD reopened by s2", checkHeadReopenedBy(read("head-reopened-s2.stdout"), e2, g, l, "s2")) + refused("HEAD reopened by s2 read as s1's", checkHeadReopenedBy(read("head-reopened-s2.stdout"), e2, g, l, "s1")) + if got, err := forcedEpoch(read("force-move.stdout"), e, "s1", "s2"); err != nil || got != e2 { + t.Errorf("forced epoch %d, %v; want %d", got, err, e2) + } + _, err = forcedEpoch(read("force-move.stdout"), e, "s2", "s1") + refused("forced move read the other way round", err) + _, err = forcedEpoch(read("move-clean-s2.stdout"), e, "s1", "s2") + refused("forced epoch", err) + if got, err := forcedKeptLSN(read("force-move.stdout")); err != nil || got != l { + t.Errorf("forced kept LSN %d, %v; want %d", got, err, l) + } + if !previewAdmitted(read("force-move-dry-run-admitted.stdout")) || previewAdmitted(read("force-move-dry-run-refused.stdout")) { + t.Error("the dry-run preview is not told admitted from not admitted") + } + if !strings.Contains(read("force-move-dry-run-refused.stdout"), "admissible at ") { + t.Error("the refused preview has no admissible time") + } + if !strings.Contains(read("lost-range.stdout"), "range 1 of 1: request force-v1-1, r1@") { + t.Error("lost-range does not show the forced move") + } + if !frontendReady([]byte(read("status-primary.json"))) || frontendReady([]byte(`{"FrontendPrimaryReady":false,"Healthy":true}`)) { + t.Error("the frontend-ready check does not read FrontendPrimaryReady") + } + if !statusPrimary([]byte(read("status-primary.json")), e2) || statusPrimary([]byte(read("status-primary.json")), e) { + t.Error("status check does not read the epoch of a healthy primary") + } +} + +// lastCutUploadedChunks reads Chunk.Stats.LastCut.UploadedChunks of vol from a +// /status/durable body. +func lastCutUploadedChunks(body []byte, vol string) (int, error) { + var st struct { + Volumes []struct { + VolumeID string + Chunk *struct { + Stats struct { + LastCut *struct{ UploadedChunks int } + } + } + } + } + if err := json.Unmarshal(body, &st); err != nil { + return 0, fmt.Errorf("durable status is not JSON: %v", err) + } + for _, v := range st.Volumes { + if v.VolumeID != vol { + continue + } + if v.Chunk == nil || v.Chunk.Stats.LastCut == nil { + return 0, fmt.Errorf("durable status of %s has no last cut", vol) + } + return v.Chunk.Stats.LastCut.UploadedChunks, nil + } + return 0, fmt.Errorf("durable status has no volume %s", vol) +} diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go new file mode 100644 index 0000000000..ddb6196c17 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -0,0 +1,958 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "fmt" + "io" + "math/rand" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// TestStandalonePlannedHandoffToTheSameHost runs the planned hand-over back +// to the same host with the commands of docs/volume-lifecycle.md, in its +// order and form, against real blockmaster, blockvolume, sw-block and +// SeaweedFS processes on loopback: cluster spec, start, write, plain detach, +// revoke with the sealed generation, the old process acknowledges and exits +// by itself, show the ACK, clean move to the same host, start again, and the +// written block reads back unchanged. +func TestStandalonePlannedHandoffToTheSameHost(t *testing.T) { + h, cluster, chunkPath, show, volArgs := startPlannedHandoff(t) + must, mustU := fatalOn(t) + const nqn = plannedHandoffNQN + + // 4. blockvolume adopts the volume. + vol1 := h.start(t, "blockvolume-1", h.volume, volArgs...) + e := mustU(adoptedEpoch(vol1.waitLog(t, 60*time.Second, "blockvolume: volume v1 adopted as PRIMARY at r1@"))) + h.waitPrimary(t, e) + + // 5. The lease. + out, _ := h.command(t, show...) + must(checkShowGranted(out, e)) + + // 6, 7. Write a known block and flush it, then disconnect the writer. + block := bytes.Repeat([]byte("planned-handoff!"), 4096/16) + want := sha256.Sum256(block) + c := dialNVMe(t, h.nvmeAddr, nqn) + c.write(t, 0, block) + c.flush(t) + c.close() + + // 8. Seal with a plain detach. + out, errOut := h.command(t, "ops", "chunk", "detach", "--plain", "--volume", "v1", "--status-addr", h.statusAddr, "--timeout", "120s") + g := mustU(sealedGen(out, errOut, e)) + + // 9. The seal is in the object store. + chunkShow := []string{"ops", "chunk", "show", "--master", h.masterAddr, "--volume", "v1", "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath} + out, _ = h.command(t, chunkShow...) + l := mustU(sealedLayoutHeadPosition(out, e, g)) + + // 10. Revoke with the sealed generation. + out, _ = h.command(t, "ops", "workspace", "revoke", "--master", h.masterAddr, "--volume", "v1", "--replica", "r1", + "--epoch", fmt.Sprint(e), "--sealed-gen", fmt.Sprint(g)) + must(checkRevoke(out, e, g)) + + // 11. The old blockvolume acknowledges and exits by itself (a signal + // would suppress the ACK), within the 30 s lease. + if err := vol1.wait(30 * time.Second); err != nil { + t.Fatalf("blockvolume after the revocation: %v; want a clean exit by itself", err) + } + if !vol1.has(fmt.Sprintf("workspace lease: fenced volume=v1 replica=r1 epoch=%d: revoked by the master", e)) || + !vol1.has("blockvolume: stopping: the workspace lease guard fenced and requested the drain") { + t.Fatal("blockvolume log does not show the revocation fence and drain") + } + if vol1.has("blockvolume: workspace lease closeout:") { + t.Fatal("blockvolume reported a closeout error") + } + + // 12. The master recorded the ACK at the sealed generation. + poll(t, 30*time.Second, fmt.Sprintf("workspace show never reported the ACK of r1@%d at generation %d", e, g), func() bool { + out, _ := h.command(t, show...) + return showsAck(out, e, g) + }) + + // 13. Clean move to the same host; a rerun replays the issued move. + move := []string{"ops", "workspace", "move", "--clean", "--master", h.masterAddr, "--volume", "v1", "--replica", "r1", + "--epoch", fmt.Sprint(e), "--target-host", "s1", "--target-data", h.dataAddr, "--target-ctrl", h.ctrlAddr, + "--request-id", "move-v1-1"} + moved, _ := h.command(t, move...) + e2 := mustU(movedEpoch(moved, e, g, l)) + if again, _ := h.command(t, move...); again != moved { + t.Fatalf("clean move rerun answered %q; want the issued move again %q", again, moved) + } + + // 14. Start again with the same root, within the new lease (30 s). + vol2 := h.start(t, "blockvolume-2", h.volume, volArgs...) + vol2.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume v1 adopted as PRIMARY at r1@%d", e2)) + for _, bad := range []string{"refusing to attach volume=v1", "assignment unavailable, not serving"} { + if vol2.has(bad) { + t.Fatalf("the restarted blockvolume logged %q", bad) + } + } + h.waitPrimary(t, e2) + + // 15. The new lease and the move record. + out, _ = h.command(t, show...) + must(checkShowMoved(out, e, e2, g, l)) + + // 16. The new epoch claimed HEAD. + out, _ = h.command(t, chunkShow...) + must(checkLayoutHeadReopened(out, e2, g, l)) + + // 17. The block written before the hand-over reads back unchanged. + c = dialNVMe(t, h.nvmeAddr, nqn) + defer c.close() + if got := sha256.Sum256(c.read(t, 0, 4096)); got != want { + t.Fatalf("block 0 after the hand-over has sha256 %x; want %x", got, want) + } +} + +// TestStandaloneCleanMoveWithoutTheACKIsRefused is the chapter's negative +// check N1 made deterministic: the volume is sealed, its blockvolume is +// killed (a signal sends no ACK), and the lease is revoked with the sealed +// generation while no blockvolume runs. No ACK can arrive, so the clean move +// is refused with the documented error, exit 1, and the master keeps no ACK. +func TestStandaloneCleanMoveWithoutTheACKIsRefused(t *testing.T) { + h, cluster, chunkPath, show, volArgs := startPlannedHandoff(t) + must, mustU := fatalOn(t) + + vol := h.start(t, "blockvolume", h.volume, volArgs...) + e := mustU(adoptedEpoch(vol.waitLog(t, 60*time.Second, "blockvolume: volume v1 adopted as PRIMARY at r1@"))) + h.waitPrimary(t, e) + c := dialNVMe(t, h.nvmeAddr, plannedHandoffNQN) + c.write(t, 0, bytes.Repeat([]byte{0xa5}, 4096)) + c.flush(t) + c.close() + out, errOut := h.command(t, "ops", "chunk", "detach", "--plain", "--volume", "v1", "--status-addr", h.statusAddr, "--timeout", "120s") + g := mustU(sealedGen(out, errOut, e)) + out, _ = h.command(t, "ops", "chunk", "show", "--master", h.masterAddr, "--volume", "v1", "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath) + mustU(sealedLayoutHeadPosition(out, e, g)) // HEAD is sealed: only the ACK is missing + vol.kill(t) + + out, _ = h.command(t, "ops", "workspace", "revoke", "--master", h.masterAddr, "--volume", "v1", "--replica", "r1", + "--epoch", fmt.Sprint(e), "--sealed-gen", fmt.Sprint(g)) + must(checkRevoke(out, e, g)) + out, errOut, code := h.run(t, "ops", "workspace", "move", "--clean", "--master", h.masterAddr, "--volume", "v1", "--replica", "r1", + "--epoch", fmt.Sprint(e), "--target-host", "s1", "--target-data", h.dataAddr, "--target-ctrl", h.ctrlAddr, + "--request-id", "move-v1-1") + must(checkCleanMoveRefused(out, errOut, code)) + out, _ = h.command(t, show...) + if showsAck(out, e, g) || !hasLine(out, "recorded ACK: none") { + t.Fatalf("workspace show after the refused move:\n%s\nwant recorded ACK: none", out) + } +} + +const plannedHandoffNQN = "nqn.2026-11.io.seaweedfs:handoff" + +// startPlannedHandoff runs the chapter's steps 1-3 for one host, s1, and +// returns the blockvolume arguments of step 4 and the show command. +func startPlannedHandoff(t *testing.T) (h *plannedHandoffHarness, cluster *w4WeedCluster, chunkPath string, show, volArgs []string) { + t.Helper() + env := startHandoffEnv(t, 1) + return env.h, env.cluster, env.chunkPath, env.show, env.volArgs("s1") +} + +// handoffEnv is a running setup: weed, blockmaster with the cluster spec +// naming every host, and the hosts' blockvolume endpoints. The volume starts +// on s1. +type handoffEnv struct { + h *plannedHandoffHarness + cluster *w4WeedCluster + chunkPath string + show []string + hosts map[string]bvHost + // volExtra is appended to every blockvolume command (a test that pins + // a default the page leaves alone, for example). + volExtra []string + // A crash test restarts exactly this owned master with the same stores. + masterProcess *daemon + masterArgs []string + layoutMu sync.Mutex + layoutIDs map[string]string + // tls, when set, runs every process with mutual TLS (procedure_tls_harness_test.go). + tls *procedureTLS +} + +// bvHost is one host's blockvolume: its server id, endpoints, local root +// and the volume it serves (v1 when empty). server and replica, when set, +// replace id as the server id and r1 as the replica id (several volumes +// under one server id). +type bvHost struct { + id, data, ctrl, status, nvme, root string + volume string + server, replica string +} + +// startHandoffEnv runs the chapter's steps 1-3: a weed cluster, the cluster +// spec with hosts s1..sN, blockmaster with the lifecycle store (and +// masterArgs), and the setup check. +func startHandoffEnv(t *testing.T, n int, masterArgs ...string) *handoffEnv { + t.Helper() + return startHandoffEnvWith(t, n, nil, masterArgs...) +} + +// startHandoffEnvWith is startHandoffEnv with restore targets: each of +// targets (a volume id) is placed on a node of its own, named after it, with +// its own endpoints and local root. A target has placement only, no volume +// record: its restore creates it. +func startHandoffEnvWith(t *testing.T, n int, targets []string, masterArgs ...string) *handoffEnv { + t.Helper() + return startHandoffEnvConfigured(t, n, targets, procedureTLSConfig(), false, masterArgs...) +} + +// startHandoffEnvVolumes is startHandoffEnvWith with ordinary volumes: each +// of volumes gets a volume record from the cluster spec, so it starts +// without a restore. +func startHandoffEnvVolumes(t *testing.T, n int, volumes []string, masterArgs ...string) *handoffEnv { + t.Helper() + return startHandoffEnvConfigured(t, n, volumes, procedureTLSConfig(), true, masterArgs...) +} + +// procedureTLSConfig is nil without mutual TLS, else an empty expiry map. +func procedureTLSConfig() map[string]time.Time { + if procedureTLSOn() { + return map[string]time.Time{} + } + return nil +} + +// startHandoffEnvTLS is startHandoffEnvWith with mutual TLS when tlsNotAfter +// is non-nil (it overrides chosen node certificates' expiry). +func startHandoffEnvTLS(t *testing.T, n int, targets []string, tlsNotAfter map[string]time.Time, masterArgs ...string) *handoffEnv { + return startHandoffEnvConfigured(t, n, targets, tlsNotAfter, true, masterArgs...) +} + +// startHandoffEnvConfigured can reserve target placement without importing a +// VolumeRecord. The restore-create test uses that form so the master creates +// the target's identity and restored image in one request. +func startHandoffEnvConfigured(t *testing.T, n int, targets []string, tlsNotAfter map[string]time.Time, precreateTargets bool, masterArgs ...string) *handoffEnv { + t.Helper() + return startHandoffEnvOnCluster(t, n, targets, tlsNotAfter, precreateTargets, nil, masterArgs...) +} + +// startHandoffEnvOnCluster also admits a caller-owned stock filer behind a +// fault-injection front; ordinary callers keep the default cluster unchanged. +func startHandoffEnvOnCluster(t *testing.T, n int, targets []string, tlsNotAfter map[string]time.Time, precreateTargets bool, cluster *w4WeedCluster, masterArgs ...string) *handoffEnv { + t.Helper() + h := newPlannedHandoffHarness(t) + if cluster == nil { + cluster = startWorkspaceWeed(t) + } + env := &handoffEnv{h: h, cluster: cluster, chunkPath: fmt.Sprintf("/handoff-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}} + must, _ := fatalOn(t) + env.hosts["s1"] = bvHost{id: "s1", data: h.dataAddr, ctrl: h.ctrlAddr, status: h.statusAddr, nvme: h.nvmeAddr, root: filepath.Join(h.dir, "vol")} + for i := 2; i <= n; i++ { + id := fmt.Sprintf("s%d", i) + env.hosts[id] = bvHost{id: id, data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t), root: filepath.Join(h.dir, "vol-"+id)} + } + for _, v := range targets { + id := "n-" + v + env.hosts[id] = bvHost{id: id, data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t), root: filepath.Join(h.dir, "vol-"+id), volume: v} + } + chunkPath := env.chunkPath + if tlsNotAfter != nil { + servers := make([]string, 0, len(env.hosts)) + for _, b := range env.hosts { + servers = append(servers, b.id) + } + env.tls = newProcedureTLS(t, h.dir, servers, tlsNotAfter) + h.cliEnv = env.tls.cliEnv("admin") + masterArgs = append(env.tls.masterArgs(), masterArgs...) + } + + // 1. The cluster spec. + var nodes, volumes strings.Builder + node := func(b bvHost) { + fmt.Fprintf(&nodes, " - server_id: %s\n data_addr: %s\n ctrl_addr: %s\n", b.id, b.data, b.ctrl) + } + volume := func(v, server string, create bool) { + size := "" + if create { + size = " size_bytes: 268435456\n" + } + fmt.Fprintf(&volumes, " - id: %s\n%s replication_factor: 1\n placements:\n - server_id: %s\n replica_id: r1\n", v, size, server) + } + for i := 1; i <= n; i++ { + node(env.hosts[fmt.Sprintf("s%d", i)]) + } + volume("v1", "s1", true) + for _, v := range targets { + node(env.hosts["n-"+v]) + volume(v, "n-"+v, precreateTargets) + } + spec := filepath.Join(h.dir, "cluster-spec.yaml") + must(os.WriteFile(spec, []byte("nodes:\n"+nodes.String()+"volumes:\n"+volumes.String()), 0o644)) + + // 2. blockmaster with the lifecycle store and the cluster spec. + mstate := filepath.Join(h.dir, "master") + env.masterArgs = append([]string{ + "--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"), + "--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr, + "--workspace-rpc"}, masterArgs...) + env.masterArgs = append(env.masterArgs, "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath) + master := h.start(t, "blockmaster", h.master, env.masterArgs...) + env.masterProcess = master + if l := master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded="); !strings.Contains(l, "listen="+h.masterAddr) { + t.Fatalf("blockmaster start line %q does not name listen=%s", l, h.masterAddr) + } + if master.has("blockmaster: WARNING: --topology not supplied or empty") { + t.Fatal("blockmaster warned about a missing topology although the cluster spec gives it") + } + + // 3. The setup answers before any blockvolume runs. + env.show = []string{"ops", "workspace", "show", "--master", h.masterAddr, "--volume", "v1"} + out, _ := h.command(t, env.show...) + must(checkShowBeforeStart(out)) + // Cache the identities imported by the master while it is available. Some + // tests assemble restart arguments after deliberately stopping the master. + env.layoutIDs = make(map[string]string) + env.layoutID("v1") + if precreateTargets { + for _, v := range targets { + env.layoutID(v) + } + } + return env +} + +// volArgs is the chapter's blockvolume command for one host. +func (env *handoffEnv) volArgs(id string) []string { return env.volArgsFor(env.hosts[id]) } + +func (env *handoffEnv) layoutID(volume string) string { + t := env.h.t + t.Helper() + env.layoutMu.Lock() + defer env.layoutMu.Unlock() + if id := env.layoutIDs[volume]; id != "" { + return id + } + conn, err := grpc.NewClient(env.h.masterAddr, env.masterDialOption(t, "admin")) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + // blockmaster logs "lock acquired" before it imports the cluster spec + // (each volume's layout created on the filer) and only serves after + // that, so a lookup right after that line can find it not serving yet: + // retry while it is unavailable, within 60 s. Any other answer (not + // found, refused) fails at once. + var id layout.VolumeID + for end := time.Now().Add(60 * time.Second); ; time.Sleep(500 * time.Millisecond) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + id, err = lifecycleclient.ResolveVolume(ctx, control.NewLifecycleServiceClient(conn), volume) + cancel() + if err == nil { + break + } + if c := status.Code(err); (c != codes.Unavailable && c != codes.DeadlineExceeded) || time.Now().After(end) { + t.Fatalf("resolve layout identity for %s: %v", volume, err) + } + } + if env.layoutIDs == nil { + env.layoutIDs = make(map[string]string) + } + env.layoutIDs[volume] = id.String() + return id.String() +} + +// volArgsFor is the chapter's blockvolume command for b. The default +// scheduled snapshot (daily:7, at a per-volume offset) stays on, as the page +// says; a snapshot inside a test could only make a test fail, never pass. +func (env *handoffEnv) volArgsFor(b bvHost) []string { + lockDir := b.root + ".locks" // each simulated host has its own + _ = os.MkdirAll(lockDir, 0o700) + vol, server, replica := b.volume, b.server, b.replica + if vol == "" { + vol = "v1" + } + if server == "" { + server = b.id + } + if replica == "" { + replica = "r1" + } + return append([]string{"--volume-lock-dir-test-only", lockDir, "--master", env.h.masterAddr, "--server-id", server, "--volume-id", vol, "--replica-id", replica, + "--layout-id", env.layoutID(vol), + "--data-addr", b.data, "--ctrl-addr", b.ctrl, "--status-addr", b.status, + "--durable-root", b.root, "--durable-impl", "walstore-chunk", + "--durable-blocks", "65536", "--durable-blocksize", "4096", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--chunk-control-endpoint", + "--workspace-lease", "--nvme-listen", b.nvme, "--nvme-subsysnqn", plannedHandoffNQN}, append(env.tlsVolumeArgs(server), env.volExtra...)...) +} + +// tlsVolumeArgs is server's node identity when the env runs with mutual TLS. +func (env *handoffEnv) tlsVolumeArgs(server string) []string { + if env.tls == nil { + return nil + } + return env.tls.volumeArgs(server) +} + +func fatalOn(t *testing.T) (func(error), func(uint64, error) uint64) { + must := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + return must, func(v uint64, err error) uint64 { + t.Helper() + must(err) + return v + } +} + +// plannedHandoffHarness owns real binaries, loopback endpoints and process +// lifetimes. +type plannedHandoffHarness struct { + dir string + master, volume, cli string + masterAddr, dataAddr, ctrlAddr, statusAddr, nvmeAddr string + // t logs every sw-block command (logCommand) until the test ends + // (logDone): a runCLI goroutine that outlives it must not call t.Logf. + t *testing.T + logMu sync.Mutex + logDone bool + // cliEnv is added to every sw-block command's environment (its master + // TLS identity when the env runs with mutual TLS). + cliEnv []string +} + +func newPlannedHandoffHarness(t *testing.T) *plannedHandoffHarness { + t.Helper() + if os.Getenv("CHUNKSTORE_WEED") == "" { + t.Fatal("CHUNKSTORE_WEED must name the pinned real SeaweedFS binary") + } + h := &plannedHandoffHarness{dir: t.TempDir(), t: t} + t.Cleanup(func() { + h.logMu.Lock() + h.logDone = true + h.logMu.Unlock() + }) + suffix := "" + if isWindows() { + suffix = ".exe" + } + for _, b := range []struct { + name string + dst *string + }{ + {"blockmaster", &h.master}, {"blockvolume", &h.volume}, {"sw-block", &h.cli}, + } { + *b.dst = filepath.Join(h.dir, b.name+suffix) + if d := os.Getenv("SWBLOCK_TEST_BINS"); d != "" { + // Prebuilt binaries, for a test host without a Go toolchain. + *b.dst = filepath.Join(d, b.name+suffix) + if _, err := os.Stat(*b.dst); err != nil { + t.Fatalf("SWBLOCK_TEST_BINS: %v", err) + } + continue + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + cmd := exec.CommandContext(ctx, "go", "build", "-o", *b.dst, "github.com/seaweedfs/seaweed-block/cmd/"+b.name) + cmd.WaitDelay = 5 * time.Second + out, err := cmd.CombinedOutput() + cancel() + if err != nil { + t.Fatalf("build %s: %v\n%s", b.name, err, out) + } + } + h.masterAddr = handoffAddress(t) + h.dataAddr = handoffAddress(t) + h.ctrlAddr = handoffAddress(t) + h.statusAddr = handoffAddress(t) + h.nvmeAddr = handoffAddress(t) + return h +} + +// captureOutput writes each sw-block answer to $HANDOFF_CAPTURE_DIR, when set, +// as --.stdout/.stderr: the source of testdata/planned-handoff. +func captureOutput(t *testing.T, args []string, stdout, stderr string) { + dir := os.Getenv("HANDOFF_CAPTURE_DIR") + if dir == "" || len(args) < 3 { + return + } + captureSeq++ + base := filepath.Join(dir, fmt.Sprintf("%s-%02d-%s-%s", t.Name(), captureSeq, args[1], args[2])) + _ = os.WriteFile(base+".stdout", []byte(stdout), 0o644) + _ = os.WriteFile(base+".stderr", []byte(stderr), 0o644) +} + +var captureSeq int + +var handoffPorts struct { + sync.Mutex + used map[int]bool +} + +// handoffAddress returns a free loopback address in 10000-19999: below the +// kernel's ephemeral range (32768 and up on Linux; the range is cut at the +// host's own ephemeral low end when that is lower: handoffRange), where an +// outgoing connection can take a port while a restarted daemon waits to bind +// it again, and below the 20000-49999 range startWorkspaceWeed draws from. +func handoffAddress(t *testing.T) string { + t.Helper() + handoffPorts.Lock() + defer handoffPorts.Unlock() + if handoffPorts.used == nil { + handoffPorts.used = map[int]bool{} + } + eph, _ := ephemeralPorts() + rlo, rhi, ok := handoffRange(eph) + if !ok { + t.Fatalf("no handoff port range below this host's ephemeral range (from %d)", eph) + } + for i := 0; i < 500; i++ { + lo, hi := testPortSpan(rlo, rhi) + p := lo + rand.Intn(hi-lo) + if handoffPorts.used[p] || !claimHostPort(p) { + continue + } + addr := fmt.Sprintf("%s:%d", testListenHost(), p) + if ln, err := net.Listen("tcp", addr); err == nil { + ln.Close() + handoffPorts.used[p] = true + return addr + } + } + t.Fatal("no free port below the ephemeral range on " + testListenHost()) + return "" +} + +// daemon is one started child: its log file and its exit. +type daemon struct { + name, log string + done chan struct{} + err error + cancel context.CancelFunc + proc *os.Process +} + +// term sends SIGTERM, as systemctl stop or restart does, and waits for the +// child to exit. +func (d *daemon) term(t *testing.T, timeout time.Duration) { + t.Helper() + if err := d.proc.Signal(syscall.SIGTERM); err != nil { + t.Fatalf("SIGTERM %s: %v", d.name, err) + } + select { + case <-d.done: + case <-time.After(timeout): + t.Fatalf("%s did not exit within %s of SIGTERM", d.name, timeout) + } +} + +// kill kills the child (no ACK is sent on a signal) and waits for it. +func (d *daemon) kill(t *testing.T) { + t.Helper() + began := time.Now() + defer func() { t.Logf("%s SIGKILL-to-reap=%s", d.name, time.Since(began)) }() + d.cancel() + select { + case <-d.done: + case <-time.After(10 * time.Second): + d.waitForKilledReap(t) + } +} + +// start registers cancellation and a bounded join before starting a daemon. +// Each child writes to its own file, and cleanup targets only that child. +// Cancellation kills the child; a test that needs a child to exit by itself +// waits for it with wait. +func (h *plannedHandoffHarness) start(t *testing.T, name, binary string, args ...string) *daemon { + t.Helper() + log, err := os.Create(filepath.Join(h.dir, name+".log")) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + cmd := stripSystemdForTestLockDir(exec.CommandContext(ctx, binary, args...)) + cmd.Dir, cmd.Stdout, cmd.Stderr = h.dir, log, log + cmd.WaitDelay = 5 * time.Second + d := &daemon{name: name, log: log.Name(), done: make(chan struct{}), cancel: cancel} + started := false + t.Cleanup(func() { + stopAt := time.Now() + cancel() + if started { + select { + case <-d.done: + case <-time.After(10 * time.Second): + d.waitForKilledReap(t) + } + } + t.Logf("%s cancellation-to-reap=%s", name, time.Since(stopAt)) + _ = log.Close() + if t.Failed() { + keepFullLog(t, d) + data, _ := os.ReadFile(d.log) + if len(data) > 16000 { + data = data[len(data)-16000:] + } + t.Logf("%s log:\n%s", name, data) + } + }) + if err := cmd.Start(); err != nil { + t.Fatalf("start %s: %v", name, err) + } + started = true + d.proc = cmd.Process + go func() { d.err = cmd.Wait(); close(d.done) }() + return d +} + +// keepFullLog copies a failed test's daemon log, whole, into +// $SWBLOCK_TEST_LOG_DIR when that is set (a gate run collects it): the +// test's own output keeps only the log's tail, and a bring-up decision is +// at its head. +func keepFullLog(t *testing.T, d *daemon) { + if err := keepLogCopy(t.Name(), d.name, d.log); err != nil { + t.Logf("%s: full log not kept: %v", d.name, err) + } +} + +// wait waits up to timeout for the child to exit by itself and returns its +// exit error (nil: status 0). +func (d *daemon) wait(timeout time.Duration) error { + select { + case <-d.done: + return d.err + case <-time.After(timeout): + return fmt.Errorf("%s still running after %s", d.name, timeout) + } +} + +// line returns the first log line containing s ("" if none). +func (d *daemon) line(s string) string { + data, _ := os.ReadFile(d.log) + for _, l := range strings.Split(string(data), "\n") { + if strings.Contains(l, s) { + return l + } + } + return "" +} + +func (d *daemon) has(s string) bool { return d.line(s) != "" } + +// tail is the last n lines of the child's log, for a failure report. +func (d *daemon) tail(n int) string { + b, err := os.ReadFile(d.log) + if err != nil { + return "(log unreadable: " + err.Error() + ")" + } + lines := strings.Split(strings.TrimRight(string(b), "\n"), "\n") + if len(lines) > n { + lines = lines[len(lines)-n:] + } + return strings.Join(lines, "\n") +} + +// waitLog waits for a log line containing s and returns it. A child that +// exits first fails the test at once. +func (d *daemon) waitLog(t *testing.T, timeout time.Duration, s string) string { + t.Helper() + end := time.Now().Add(timeout) + for { + if l := d.line(s); l != "" { + return l + } + select { + case <-d.done: + if l := d.line(s); l != "" { + return l + } + t.Fatalf("%s exited (%v) before logging %q; its log ends:\n%s", d.name, d.err, s, d.tail(40)) + default: + } + if time.Now().After(end) { + t.Fatalf("%s did not log %q within %s; its log ends:\n%s", d.name, s, timeout, d.tail(40)) + } + time.Sleep(100 * time.Millisecond) + } +} + +// command keeps stdout separate from stderr: detach stdout remains JSON while +// its sealed-generation line is read from stderr by the documented sequence. +// The bound covers the detach's own --timeout 120s. +func (h *plannedHandoffHarness) command(t *testing.T, args ...string) (string, string) { + t.Helper() + stdout, stderr, code := h.run(t, args...) + if code != 0 { + t.Fatalf("sw-block %q: exit %d\nstdout: %s\nstderr: %s", args, code, stdout, stderr) + } + return stdout, stderr +} + +// run runs sw-block and returns its output and exit status; only a failure +// to run it at all (or its timeout) fails the test. +func (h *plannedHandoffHarness) run(t *testing.T, args ...string) (string, string, int) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, h.cli, args...) + cmd.Dir = h.dir + if len(h.cliEnv) > 0 { + cmd.Env = append(os.Environ(), h.cliEnv...) + } + cmd.WaitDelay = 5 * time.Second + var stdout, stderr strings.Builder + cmd.Stdout, cmd.Stderr = &stdout, &stderr + err := cmd.Run() + captureOutput(t, args, stdout.String(), stderr.String()) + h.logCommand(args, stdout.String(), stderr.String(), err) + var exit *exec.ExitError + switch { + case err == nil: + return stdout.String(), stderr.String(), 0 + case errors.As(err, &exit) && ctx.Err() == nil: + return stdout.String(), stderr.String(), exit.ExitCode() + } + t.Fatalf("sw-block %q: %v\nstdout: %s\nstderr: %s", args, err, stdout.String(), stderr.String()) + return "", "", -1 +} + +// logCommandCap bounds each logged stream of one sw-block command. +const logCommandCap = 4096 + +// logCommand writes one sw-block command's argv, exit status and output to +// the test log, so a refusal is visible without a rerun. It is safe from the +// goroutines runCLI runs on; after the test ended it logs nothing. +func (h *plannedHandoffHarness) logCommand(args []string, stdout, stderr string, err error) { + h.logMu.Lock() + defer h.logMu.Unlock() + if h.t == nil || h.logDone { + return + } + status := "exit 0" + if err != nil { + status = err.Error() + } + h.t.Logf("sw-block %q: %s\nstdout: %s\nstderr: %s", args, status, capLog(stdout), capLog(stderr)) +} + +func capLog(s string) string { + if len(s) <= logCommandCap { + return s + } + return s[:logCommandCap] + fmt.Sprintf("... (%d more bytes)", len(s)-logCommandCap) +} + +// waitPrimary polls the status endpoint until the volume serves as a +// healthy primary at epoch. +func (h *plannedHandoffHarness) waitPrimary(t *testing.T, epoch uint64) { + t.Helper() + h.waitPrimaryAt(t, h.statusAddr, epoch) +} + +// waitPrimaryAt polls one host's status endpoint until the volume serves +// there as a healthy primary at epoch. +func (h *plannedHandoffHarness) waitPrimaryAt(t *testing.T, statusAddr string, epoch uint64) { + t.Helper() + c := &http.Client{Timeout: 5 * time.Second} + poll(t, 60*time.Second, fmt.Sprintf("status at %s never showed a healthy primary at epoch %d", statusAddr, epoch), func() bool { + resp, err := c.Get("http://" + statusAddr + "/status?volume=v1") + if err != nil { + return false + } + defer resp.Body.Close() + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + return statusPrimary(b, epoch) + }) +} + +func poll(t *testing.T, timeout time.Duration, what string, fn func() bool) { + t.Helper() + end := time.Now().Add(timeout) + for !fn() { + if time.Now().After(end) { + t.Fatal(what) + } + time.Sleep(time.Second) + } +} + +// nvmeInitiator is the smallest NVMe/TCP host the test needs: one admin and +// one IO queue, Write, Flush and Read of namespace 1. It runs in the test +// process, so the test needs neither root nor the kernel's nvme_tcp. +// nvmeIODeadline bounds each NVMe command of the initiator: it is set at dial +// and renewed before every I/O command, so a long read loop on a slow host is +// not bounded as a whole. A var only so a test can shorten it. +var nvmeIODeadline = 60 * time.Second + +type nvmeInitiator struct { + admin, io net.Conn + r *nvme.Reader + w *nvme.Writer + cid uint16 +} + +func dialNVMe(t *testing.T, addr, subNQN string) *nvmeInitiator { + t.Helper() + c := &nvmeInitiator{} + cd := nvme.ConnectData{HostID: [16]byte{0x5e, 0xa1}, SubNQN: subNQN, HostNQN: "nqn.2026-11.io.seaweedfs:handoff-test"} + var cntlID uint16 + for qid := uint32(0); qid <= 1; qid++ { + conn, err := net.DialTimeout("tcp", addr, 5*time.Second) + if err != nil { + t.Fatalf("nvme dial %s: %v", addr, err) + } + _ = conn.SetDeadline(time.Now().Add(nvmeIODeadline)) + r, w := nvme.NewReader(conn), nvme.NewWriter(conn) + if err := w.SendHeaderOnly(0x0, &nvme.ICRequest{PDUMaxR2T: 1}, 120); err != nil { + t.Fatalf("nvme ICReq: %v", err) + } + if ch, err := r.Dequeue(); err != nil || ch.Type != 0x1 { + t.Fatalf("nvme ICResp: type %v err %v", ch, err) + } + if err := r.Receive(&nvme.ICResponse{}); err != nil { + t.Fatalf("nvme ICResp body: %v", err) + } + // The admin queue asks for a controller; the IO queue names it. + cd.CNTLID = 0xFFFF + if qid == 1 { + cd.CNTLID = cntlID + } + buf := make([]byte, 1024) + cd.Marshal(buf) + c.cid++ + cmd := nvme.CapsuleCommand{OpCode: 0x7F, FCType: 0x01, CID: c.cid, D10: qid << 16} + if err := w.SendWithData(0x4, 0, &cmd, 64, buf); err != nil { + t.Fatalf("nvme Connect qid %d: %v", qid, err) + } + resp := nvmeResponse(t, r) + if resp.Status != 0 { + t.Fatalf("nvme Connect qid %d status 0x%04x", qid, resp.Status) + } + if qid == 0 { + c.admin, cntlID = conn, uint16(resp.DW0&0xFFFF) + } else { + c.io, c.r, c.w = conn, r, w + } + } + return c +} + +func nvmeResponse(t *testing.T, r *nvme.Reader) nvme.CapsuleResponse { + t.Helper() + ch, err := r.Dequeue() + if err != nil || ch.Type != 0x5 { + t.Fatalf("nvme response: type %v err %v", ch, err) + } + var resp nvme.CapsuleResponse + if err := r.Receive(&resp); err != nil { + t.Fatalf("nvme response body: %v", err) + } + return resp +} + +func (c *nvmeInitiator) ioCmd(op uint8, lba uint64, blocks int) nvme.CapsuleCommand { + _ = c.io.SetDeadline(time.Now().Add(nvmeIODeadline)) + c.cid++ + cmd := nvme.CapsuleCommand{OpCode: op, CID: c.cid, NSID: 1} + if blocks > 0 { + cmd.D10, cmd.D11, cmd.D12 = uint32(lba), uint32(lba>>32), uint32(blocks-1) + } + return cmd +} + +// hostCommand keeps the raw try methods single-attempt for fault probes. +func hostCommand(t *testing.T, op func() error) { + t.Helper() + started := time.Now() + refused, err := retryLikeHostReporting(nvmeHostMaxRetries, op, func(attempt int, status uint16) { + t.Logf("NVMe retryable completion attempt=%d status=0x%04x retry=%t elapsed=%s", attempt, status, attempt <= nvmeHostMaxRetries, time.Since(started)) + }) + if refused > 0 { + t.Logf("NVMe retryable completions=%d elapsed=%s exhausted=%t", refused, time.Since(started), refused > nvmeHostMaxRetries) + } + if err != nil { + t.Fatal(err) + } +} + +func (c *nvmeInitiator) write(t *testing.T, lba uint64, data []byte) { + t.Helper() + hostCommand(t, func() error { return c.tryWrite(lba, data) }) +} + +func (c *nvmeInitiator) flush(t *testing.T) { + t.Helper() + hostCommand(t, c.tryFlush) +} + +func (c *nvmeInitiator) read(t *testing.T, lba uint64, n int) []byte { + t.Helper() + var data []byte + hostCommand(t, func() (err error) { data, err = c.tryRead(lba, n); return err }) + return data +} + +func (c *nvmeInitiator) close() { + for _, conn := range []net.Conn{c.io, c.admin} { + if conn != nil { + _ = conn.Close() + } + } +} + +// A killed task can remain in uninterruptible filesystem I/O. The containing +// procedure owns its outer ceiling;10s alone is never a product-stop failure. +func (d *daemon) waitForKilledReap(t *testing.T) { + t.Helper() + began := time.Now() + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + ceiling := began.Add(15 * time.Minute) + if deadline, ok := t.Deadline(); ok && deadline.Add(-5*time.Second).Before(ceiling) { + ceiling = deadline.Add(-5 * time.Second) + } + timer := time.NewTimer(time.Until(ceiling)) + defer timer.Stop() + for { + logTaskState(t, d, "SIGKILL reap pending") + select { + case <-d.done: + t.Logf("environment: %s reaped after additional %s (SIGKILL; not graceful stop)", d.name, time.Since(began)) + return + case <-timer.C: + t.Skipf("UNKNOWN: environment reap observation ceiling reached; outstanding name=%s pid=%d, driver retains cleanup ownership", d.name, d.proc.Pid) + case <-ticker.C: + } + } +} +func logTaskState(t *testing.T, d *daemon, reason string) { + t.Helper() + if d.proc == nil { + return + } + dirs, err := filepath.Glob(fmt.Sprintf("/proc/%d/task/*", d.proc.Pid)) + t.Logf("environment: %s name=%s pid=%d at=%s tasks_error=%v", reason, d.name, d.proc.Pid, time.Now().UTC().Format(time.RFC3339Nano), err) + for _, dir := range dirs { + for _, field := range []string{"stat", "wchan", "stack", "io"} { + data, err := os.ReadFile(filepath.Join(dir, field)) + t.Logf("environment: task=%s %s=%q error=%v", filepath.Base(dir), field, data, err) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/probe_ack_profile_test.go b/seaweed-block/cmd/blockvolume/probe_ack_profile_test.go new file mode 100644 index 0000000000..d371d2c5c7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/probe_ack_profile_test.go @@ -0,0 +1,14 @@ +package main + +import "testing" + +// The volume answers every promotion probe with its own --replication-ack, +// in the canonical form the master compares (best_effort, sync_quorum, +// sync_all). +func TestHostConfigAnswersTheVolumesOwnAckProfile(t *testing.T) { + for flag, want := range map[string]string{"best-effort": "best_effort", "sync-quorum": "sync_quorum", "sync-all": "sync_all"} { + if got := hostConfig(flags{replicationAck: flag}, nil).AckProfile; got != want { + t.Fatalf("--replication-ack=%s: AckProfile %q; want %q", flag, got, want) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go new file mode 100644 index 0000000000..8155c33928 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_crash_io_integration_test.go @@ -0,0 +1,442 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "fmt" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" +) + +// Guest I/O crash recovery: kill -9 of the +// holder WITH guest I/O in flight, then a restart inside the lease. Every +// write a Flush acknowledged must read back after the restart +// (INV-WAL-SYNCED-RECOVERED-001); writes not yet acknowledged by a Flush may +// vanish, but what is left of them must be a prefix of the stream in LBA +// order with nothing torn or invented (the writer writes LBAs in order). +// +// The writer is the guest: qd1 NVMe/TCP writes of distinct blocks, a Flush +// every crashIOFlushEvery writes; it records the last LBA a successful +// Flush covered. The holder is killed while the writer is mid-stream. + +const ( + crashIOBase = 2048 // first LBA the writer uses (chunk 2) + crashIOSpan = 40000 + crashIOFlushEvery = 8 +) + +func crashIOBlock(lba uint64) []byte { + s := fmt.Sprintf("crash-io lba %08d|", lba) + b := make([]byte, 4096) + for i := range b { + b[i] = s[i%len(s)] + } + return b +} + +// crashIOWriter writes LBAs crashIOBase.. in order until stopped or an I/O +// fails, and reports how far the Flush acknowledgements reached. +type crashIOWriter struct { + mu sync.Mutex + written int // writes completed (acknowledged by the write itself) + flushed int // writes covered by an acknowledged Flush + err error + done chan struct{} +} + +func startCrashIOWriter(t *testing.T, env *handoffEnv, id string) *crashIOWriter { + t.Helper() + w := &crashIOWriter{done: make(chan struct{})} + c := dialNVMe(t, env.hosts[id].nvme, plannedHandoffNQN) + go func() { + defer close(w.done) + defer c.close() + for n := 0; n < crashIOSpan; n++ { + lba := crashIOBase + uint64(n) + err := c.tryWrite(lba, crashIOBlock(lba)) + if err == nil && n%crashIOFlushEvery == crashIOFlushEvery-1 { + err = c.tryFlush() + if err == nil { + w.mu.Lock() + w.flushed = n + 1 + w.mu.Unlock() + } + } + w.mu.Lock() + if err != nil { + w.err = err + } else { + w.written = n + 1 + } + w.mu.Unlock() + if err != nil { + return + } + } + }() + return w +} + +func (w *crashIOWriter) counts() (written, flushed int, err error) { + w.mu.Lock() + defer w.mu.Unlock() + return w.written, w.flushed, w.err +} + +func TestProcedureCrashWithIOInFlight(t *testing.T) { + env := startHandoffEnv(t, 1) + first := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, first, "s1") + + w := startCrashIOWriter(t, env, "s1") + // Let the stream run until a good number of Flushes acknowledged, so the + // kill lands mid-stream with writes in flight. + poll(t, 60*time.Second, "the writer never got 2000 flushed writes", func() bool { + _, flushed, err := w.counts() + return flushed >= 2000 || err != nil + }) + if _, _, err := w.counts(); err != nil { + t.Fatalf("a write failed before the kill: %v", err) + } + first.kill(t) // SIGKILL while the writer is still writing + select { + case <-w.done: + case <-time.After(70 * time.Second): + t.Fatal("the writer did not stop after the holder was killed") + } + written, flushed, werr := w.counts() + if werr == nil { + t.Fatalf("the writer finished all %d writes before the kill: no I/O was in flight", crashIOSpan) + } + t.Logf("at the kill: %d writes completed, %d covered by an acknowledged Flush; the writer's error: %v", written, flushed, werr) + + again := env.start(t, "blockvolume-s1-again", "s1") + if got := env.adopt(t, again, "s1"); got != e { + t.Fatalf("the restarted holder adopted epoch %d; want %d", got, e) + } + + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + defer c.close() + zero := make([]byte, 4096) + for n := 0; n < flushed; n++ { + lba := crashIOBase + uint64(n) + if got := c.read(t, lba, 4096); !bytes.Equal(got, crashIOBlock(lba)) { + t.Fatalf("flush-acknowledged write %d (LBA %d) is lost or wrong after kill -9 and restart", n, lba) + } + } + // Past the Flush acknowledgements: a prefix of the stream, then zeros. + kept, ended := flushed, false + for n := flushed; n < written+crashIOFlushEvery && n < crashIOSpan; n++ { + lba := crashIOBase + uint64(n) + got := c.read(t, lba, 4096) + switch { + case !ended && bytes.Equal(got, crashIOBlock(lba)): + kept++ + case bytes.Equal(got, zero): + ended = true + default: + t.Fatalf("LBA %d after the last acknowledged Flush holds data out of the stream's order or torn (kept %d)", lba, kept) + } + } + t.Logf("after the restart: all %d flush-acknowledged writes read back; %d writes past the last acknowledged Flush survived as a prefix (%d had completed; one in flight may persist without its reply)", flushed, kept-flushed, written-flushed) +} + +// Gap 1, cell A3.5: kill -9 of a holder serving on a FRESH root (after a +// clean move) while chunk fills from HEAD are in flight. s1 writes one block +// in each of the first fillChunks chunks; after the hand-over, s2 starts +// with no local copy. A reader walks those chunks (each read misses and +// fills) while a writer streams Flush-acknowledged writes into chunks s1 +// never wrote; s2 is SIGKILLed mid-walk and restarted. Every s1 block must +// read back (the fills are redone from HEAD) and every acknowledged s2 write +// must survive. +const ( + fillChunks = 60 + fillWriterBase = 60 * ladderChunkBlocks + fillWriterSpan = 4 * ladderChunkBlocks + fillFlushEvery = 8 +) + +func fillSourceBlock(c int) []byte { + s := fmt.Sprintf("fill-src chunk %03d|", c) + b := make([]byte, 4096) + for i := range b { + b[i] = s[i%len(s)] + } + return b +} + +func TestProcedureCrashOnAFreshRootWithFillsInFlight(t *testing.T) { + env := startHandoffEnv(t, 2) + must, mustU := fatalOn(t) + h := env.h + + old := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, old, "s1") + for c := 0; c < fillChunks; c++ { + env.writeBlock(t, "s1", uint64(c*ladderChunkBlocks), fillSourceBlock(c)) + } + g := env.seal(t, "s1", e) + l := env.sealedLSN(t, e, g) + env.revoke(t, e, g) + if err := old.wait(30 * time.Second); err != nil { + t.Fatalf("s1 after the revocation: %v", err) + } + env.waitAck(t, e, g) + moved, _ := h.command(t, env.moveClean(e, "s2", "move-v1-1")...) + e2 := mustU(movedEpochTo(moved, e, g, l, "s2")) + nw := env.start(t, "blockvolume-s2", "s2") + must(checkClaimDoneBy(nw.waitLog(t, 60*time.Second, "durable: HEAD claim for volume=v1 done in"), e2, "s2")) + if got := env.adopt(t, nw, "s2"); got != e2 { + t.Fatalf("s2 adopted at epoch %d; want %d", got, e2) + } + + // The reader: read misses fill each source chunk from HEAD. + var rmu sync.Mutex + reads, readErr := 0, error(nil) + readerDone := make(chan struct{}) + rc := dialNVMe(t, env.hosts["s2"].nvme, plannedHandoffNQN) + go func() { + defer close(readerDone) + defer rc.close() + for c := 0; c < fillChunks; c++ { + _, err := rc.tryRead(uint64(c*ladderChunkBlocks), 4096) + rmu.Lock() + if err != nil { + readErr = err + rmu.Unlock() + return + } + reads = c + 1 + rmu.Unlock() + } + }() + // The writer: acknowledged local writes into chunks s1 never wrote. + var wmu sync.Mutex + written, flushed := 0, 0 + writerDone := make(chan struct{}) + wc := dialNVMe(t, env.hosts["s2"].nvme, plannedHandoffNQN) + go func() { + defer close(writerDone) + defer wc.close() + for n := 0; n < fillWriterSpan; n++ { + lba := uint64(fillWriterBase + n) + err := wc.tryWrite(lba, crashIOBlock(lba)) + if err == nil && n%fillFlushEvery == fillFlushEvery-1 { + if err = wc.tryFlush(); err == nil { + wmu.Lock() + flushed = n + 1 + wmu.Unlock() + } + } + if err != nil { + return + } + wmu.Lock() + written = n + 1 + wmu.Unlock() + } + }() + poll(t, 60*time.Second, "s2 never got its first fills and acknowledged writes", func() bool { + rmu.Lock() + r := reads + rmu.Unlock() + wmu.Lock() + f := flushed + wmu.Unlock() + return r >= 3 && f >= 8 + }) + nw.kill(t) // SIGKILL with fills and writes in flight + <-readerDone + <-writerDone + rmu.Lock() + readsAtKill, rerr := reads, readErr + rmu.Unlock() + wmu.Lock() + writtenAtKill, flushedAtKill := written, flushed + wmu.Unlock() + if readsAtKill >= fillChunks { + t.Fatalf("the reader finished all %d fills before the kill: no fill was in flight", fillChunks) + } + t.Logf("at the kill: %d of %d source chunks read (filled), reader error %v; %d writes completed, %d covered by a Flush", readsAtKill, fillChunks, rerr, writtenAtKill, flushedAtKill) + + again := env.start(t, "blockvolume-s2-again", "s2") + if got := env.adopt(t, again, "s2"); got != e2 { + t.Fatalf("the restarted s2 adopted epoch %d; want %d", got, e2) + } + c := dialNVMe(t, env.hosts["s2"].nvme, plannedHandoffNQN) + defer c.close() + for k := 0; k < fillChunks; k++ { + if got := c.read(t, uint64(k*ladderChunkBlocks), 4096); !bytes.Equal(got, fillSourceBlock(k)) { + t.Fatalf("source chunk %d (filled before the kill: %t) does not read back after the restart", k, k < readsAtKill) + } + } + for n := 0; n < flushedAtKill; n++ { + lba := uint64(fillWriterBase + n) + if got := c.read(t, lba, 4096); !bytes.Equal(got, crashIOBlock(lba)) { + t.Fatalf("flush-acknowledged write %d (LBA %d) on the fresh root is lost after kill -9 and restart", n, lba) + } + } + t.Logf("after the restart: all %d source chunks and all %d flush-acknowledged writes read back", fillChunks, flushedAtKill) +} + +// tryRead is read returning the error (for readers off the test goroutine). +func (c *nvmeInitiator) tryRead(lba uint64, n int) ([]byte, error) { + cmd := c.ioCmd(0x02, lba, n/4096) + if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil { + return nil, fmt.Errorf("nvme Read: %w", err) + } + var data []byte + for { + ch, err := c.r.Dequeue() + if err != nil { + return nil, fmt.Errorf("nvme Read: %w", err) + } + if ch.Type == 0x5 { + var resp nvme.CapsuleResponse + if err := c.r.Receive(&resp); err != nil { + return nil, fmt.Errorf("nvme Read response: %w", err) + } + if resp.Status != 0 { + return nil, &nvmeStatusError{op: "Read", status: resp.Status} + } + break + } + if ch.Type != 0x7 { + return nil, fmt.Errorf("nvme Read: unexpected PDU type 0x%x", ch.Type) + } + var dh nvme.C2HDataHeader + if err := c.r.Receive(&dh); err != nil { + return nil, fmt.Errorf("nvme C2HData: %w", err) + } + part := make([]byte, c.r.Length()) + if err := c.r.ReceiveData(part); err != nil { + return nil, fmt.Errorf("nvme C2HData payload: %w", err) + } + data = append(data, part...) + } + if len(data) != n { + return nil, fmt.Errorf("nvme Read returned %d bytes; want %d", len(data), n) + } + return data, nil +} + +// Gap 2, procedure part (cells P8.7, P9.4, P11.3): kill -9 of the holder +// during a cut's upload, with real binaries. Image A is cut; every block is +// rewritten and a second cut starts; the holder is SIGKILLed after a delay. +// The kill counts as mid-upload only if chunk objects of the second cut +// reached the filer while HEAD stayed at the first cut's generation; else the +// delay is adapted (shorter if the cut had committed, longer if nothing was +// uploaded) and the step repeats with a new image, up to cutCrashAttempts +// times. After the mid-upload kill and a restart: HEAD verifies whole at +// depth data, every block reads the last image locally, and the next cut, +// read back through a snapshot restored into a new volume, is that image. +const cutCrashAttempts = 6 + +const ( + cutCrashChunks = 48 + cutCrashPer = 64 // blocks written per chunk +) + +func cutCrashBlock(img byte, lba uint64) []byte { + s := fmt.Sprintf("cut-crash %c lba %08d|", img, lba) + b := make([]byte, 4096) + for i := range b { + b[i] = s[i%len(s)] + } + return b +} + +func (env *handoffEnv) writeCutCrashImage(t *testing.T, img byte) { + t.Helper() + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + defer c.close() + for ch := 0; ch < cutCrashChunks; ch++ { + for i := 0; i < cutCrashPer; i++ { + lba := uint64(ch*ladderChunkBlocks + i) + c.write(t, lba, cutCrashBlock(img, lba)) + } + } + c.flush(t) +} + +func (env *handoffEnv) requireCutCrashImage(t *testing.T, hostID string, img byte) { + t.Helper() + c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN) + defer c.close() + for ch := 0; ch < cutCrashChunks; ch++ { + for i := 0; i < cutCrashPer; i++ { + lba := uint64(ch*ladderChunkBlocks + i) + if got := c.read(t, lba, 4096); !bytes.Equal(got, cutCrashBlock(img, lba)) { + t.Fatalf("%s: LBA %d is not image %c", hostID, lba, img) + } + } + } +} + +func TestProcedureCrashDuringACut(t *testing.T) { + env := startHandoffEnvWith(t, 1, []string{"v2"}) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + holder := env.start(t, "blockvolume-v1", "s1") + e := env.adopt(t, holder, "s1") + cut := []string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status} + verify := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data", "--timeout", "5m"} + headGen := func() uint64 { + out, _ := env.h.command(t, env.chunkShow()...) + h, err := parseLayoutHead(out) + if err != nil { + t.Fatal(err) + } + return h.Gen + } + + env.writeCutCrashImage(t, 'A') + cutStart := time.Now() + env.h.command(t, cut...) + delay := time.Since(cutStart) / 2 + img, landed := byte('A'), false + for attempt := 1; attempt <= cutCrashAttempts && !landed; attempt++ { + img++ + env.writeCutCrashImage(t, img) + gen, entries := headGen(), f1FilerEntries(t, env) + done := make(chan int, 1) + go func() { + _, _, code := env.h.run(t, cut...) + done <- code + }() + time.Sleep(delay) + holder.kill(t) + code := <-done + uploaded := f1FilerEntries(t, env) - entries + after := headGen() + switch { + case after != gen: + t.Logf("attempt %d: the cut committed before the kill at %s (HEAD gen %d -> %d, CLI exit %d); shorter", attempt, delay, gen, after, code) + delay /= 2 + case uploaded <= 0: + t.Logf("attempt %d: nothing was uploaded before the kill at %s; longer", attempt, delay) + delay *= 2 + default: + landed = true + t.Logf("attempt %d: killed at %s mid-upload: %d new filer entries, HEAD still gen %d (CLI exit %d)", attempt, delay, uploaded, gen, code) + } + if out, errOut, rc := env.h.run(t, verify...); rc != 0 { + t.Fatalf("attempt %d: HEAD is not whole after the kill (verify exit %d):\n%s\n%s", attempt, rc, out, errOut) + } + holder = env.start(t, fmt.Sprintf("blockvolume-v1-%d", attempt), "s1") + if got := env.adopt(t, holder, "s1"); got != e { + t.Fatalf("attempt %d: the restarted holder adopted epoch %d; want %d", attempt, got, e) + } + env.requireCutCrashImage(t, "s1", img) + } + if !landed { + t.Fatalf("no kill landed mid-upload in %d attempts", cutCrashAttempts) + } + env.h.command(t, cut...) + env.snapshot(t, "s1", "v1", "after-crash") + env.restoreInto(t, "v1", "after-crash", "v2") + env.requireCutCrashImage(t, "n-v2", img) +} diff --git a/seaweed-block/cmd/blockvolume/procedure_diskfull_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_diskfull_integration_test.go new file mode 100644 index 0000000000..f901473a9e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_diskfull_integration_test.go @@ -0,0 +1,471 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" +) + +// Local disk full, with real binaries: blockmaster, a +// real filer (weed, its data elsewhere) and walstore-chunk blockvolumes whose +// durable roots and --host-limit-dir are on small filesystems the harness +// mounts (cmd/blockvolume/testdata/diskfull.sh). A filler file takes the free +// space; deleting it frees it. +// +// 1. The WAL's disk fills under guest I/O: every guest command answers within +// the bound; the first error is the retryable 0x0104 that 1.0 documents +// (a Linux guest then fails the write with EREMOTEIO after about 75 s; +// the permanent class is #484, after GO); image A stays readable; once +// the space is freed, writes succeed without a restart. +// 1b. The holder restarts with the disk still full: it serves reads or +// exits naming the full disk. After the space is freed and a restart, +// every flush-acknowledged block reads back and the next cut moves HEAD +// and verifies. +// 2. A new volume's durable root is full: blockvolume refuses or exits and +// says why; after the space is freed it starts over what is left and +// serves. +// 3. The --host-limit-dir disk is full: a cut is refused naming the full +// disk (background work fails closed, as ruled for #485) and detach +// --plain, the urgent seal, still seals (#486); guest I/O works meanwhile. +// +// Each filed defect is a known-finding row (diskFullFinding): while it +// reproduces the row logs KNOWN FINDING #n and passes; once fixed the row +// fails with FIXED #n until the issue is removed from knownDiskFullFindings, +// which makes it a strict assertion. A defect not in the list fails the test. +// +// Environment: SWBLOCK_DISKFULL_ROOT and SWBLOCK_DISKFULL_LIMIT (two mounted +// filesystems, nothing else on them); CHUNKSTORE_WEED; optional +// SWBLOCK_TEST_BINS and SWBLOCK_REPLAY_LOGS (logs are copied there). +// +// diskFullBound stays below the Linux NVMe host default I/O timeout (30 s) +// with margin: an answer at 29 s would still make a real guest reset the +// controller. +const diskFullBound = 20 * time.Second + +func TestProcedureLocalDiskFull(t *testing.T) { + root, limit := os.Getenv("SWBLOCK_DISKFULL_ROOT"), os.Getenv("SWBLOCK_DISKFULL_LIMIT") + if root == "" && limit == "" { + t.Skip("requires the disk-full harness (two small mounted filesystems)") + } + if root == "" || limit == "" { + t.Fatalf("SWBLOCK_DISKFULL_ROOT=%q and SWBLOCK_DISKFULL_LIMIT=%q must be set together", root, limit) + } + for _, m := range []string{root, limit} { + requireSmallDedicatedMount(t, m) + } + env := startHandoffEnvVolumes(t, 1, []string{"v2"}) + if d := os.Getenv("SWBLOCK_REPLAY_LOGS"); d != "" { + t.Cleanup(func() { copyLogs(t, env.h.dir, d) }) + } + for id, dir := range map[string]string{"s1": "vol", "n-v2": "vol-v2"} { + h := env.hosts[id] + h.root = filepath.Join(root, dir) + env.hosts[id] = h + } + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + cut := []string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status} + verify := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data", "--timeout", "5m"} + headGen := func() uint64 { + out, _ := env.h.command(t, env.chunkShow()...) + hd, err := parseLayoutHead(out) + if err != nil { + t.Fatal(err) + } + return hd.Gen + } + cutAdvances := func(what string) { + t.Helper() + g0 := headGen() + env.h.command(t, cut...) + if g := headGen(); g <= g0 { + t.Fatalf("%s: the cut left HEAD at gen %d (was %d)", what, g, g0) + } + if out, errOut, rc := env.h.run(t, verify...); rc != 0 { + t.Fatalf("%s: HEAD does not verify (exit %d):\n%s\n%s", what, rc, out, errOut) + } + } + + holder := env.start(t, "blockvolume-v1", "s1") + e := env.adopt(t, holder, "s1") + env.writeCutCrashImage(t, 'A') + cutAdvances("before the disk fills") + + // 1. The WAL's disk fills under guest I/O. LBAs 0.. are written in order + // (chunks 0-31 at most); image A in chunks 40-47 is never overwritten here. + fill := fillDisk(t, root, 2<<20) + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + want := map[uint64][]byte{} + var pending []uint64 + next := 0 + writeUntilError := func(n int) error { + for end := next + n; next < end; next++ { + lba := uint64(next) + b := cutCrashBlock('W', lba) + if err := diskFullOp(c, func() error { return c.tryWrite(lba, b) }); err != nil { + return fmt.Errorf("write %d: %w", next, err) + } + pending = append(pending, lba) + if (next+1)%8 == 0 { + if err := diskFullOp(c, c.tryFlush); err != nil { + return fmt.Errorf("flush after write %d: %w", next, err) + } + for _, l := range pending { + want[l] = cutCrashBlock('W', l) + } + pending = pending[:0] + } + } + return nil + } + // 128 MiB: more than the 2 MiB left and more than the preallocated WAL, so + // the WAL fills too when the flusher cannot write extents. + firstErr := writeUntilError(32768) + if errors.Is(firstErr, errDiskFullHang) { + t.Fatalf("case 1: a guest command did not answer within %s on a full disk: %v", diskFullBound, firstErr) + } + // INV-FE-ERROR-RETRY-CLASS-001: ENOSPC is a permanent cause, so NVMe + // Generic/Internal Error with DNR (0x800c). Namespace Not Ready, DNR=0 + // (0x0104) is right only for WAL pressure a cut relieves; with ENOSPC + // behind it a guest would retry for ever: a wrong class, reported. + switch { + case firstErr == nil: + t.Fatalf("case 1: no write failed in %d writes with 2 MiB free: the disk never filled, so this case tested nothing", next) + case strings.Contains(firstErr.Error(), "status 0x800c"): + diskFullFinding(t, 484, false, "case 1: the guest saw the permanent 0x800c for ENOSPC") + case strings.Contains(firstErr.Error(), "status 0x0104"): + if holder.has("no space left on device") { + diskFullFinding(t, 484, true, "case 1: the guest saw retryable 0x0104 (%v) while the holder logs ENOSPC: a permanent cause surfaced as retryable", firstErr) + } else { + diskFullFinding(t, 484, false, "case 1: 0x0104 with no ENOSPC behind it") + } + default: + t.Fatalf("case 1: the guest saw %v, not a documented completion for a full disk", firstErr) + } + t.Logf("case 1: %d flush-acknowledged writes, %d unflushed; first error: %v; frontend ready: %v", + len(want), len(pending), firstErr, env.frontendReadyAt("s1")) + // A full disk never makes existing data unreadable. + readImageA := func(what string, c *nvmeInitiator) { + t.Helper() + for ch := 40; ch < cutCrashChunks; ch++ { + for i := 0; i < cutCrashPer; i += 16 { + lba := uint64(ch*ladderChunkBlocks + i) + var got []byte + err := diskFullOp(c, func() (err error) { got, err = c.tryRead(lba, 4096); return err }) + if err != nil || !bytes.Equal(got, cutCrashBlock('A', lba)) { + t.Fatalf("%s: image A at LBA %d is not readable on a full disk: %v", what, lba, err) + } + } + } + } + readImageA("case 1, after the first write error", c) + // Operator guide: once space is freed, new writes succeed without a + // restart (on Linux the writes made while full failed with EREMOTEIO). + fill.free(t) + if err := writeUntilError(16); err != nil { + t.Fatalf("case 1: after freeing the space, without a restart, writes still fail: %v", err) + } + c.close() + + // 1b. Restart while the disk is still full: serve (reads at least) or exit + // within the bound naming the full disk; never damage acknowledged data. + fill = fillDisk(t, root, 0) + holder.kill(t) + requireDiskFull(t, root, "case 1b, at the restart") + holder = env.start(t, "blockvolume-v1-restart-full", "s1") + served := false + for end := time.Now().Add(60 * time.Second); ; time.Sleep(500 * time.Millisecond) { + if holder.has("blockvolume: volume v1 adopted as PRIMARY at r1@") { + served = true + break + } + exited := false + select { + case <-holder.done: + exited = true + default: + } + if exited { + if !holder.has("no space left on device") { + t.Fatalf("case 1b: the holder exited on a full disk without naming it (%v); log %s", holder.err, holder.log) + } + break + } + if time.Now().After(end) { + t.Fatalf("case 1b: the holder neither served nor exited within 60s on a full disk") + } + } + if served { + env.h.waitPrimaryAt(t, env.hosts["s1"].status, e) + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + readImageA("case 1b, restarted on a full disk", c) + c.close() + t.Logf("case 1b: restarted on a full disk and serves reads") + } else { + t.Logf("case 1b: restart on a full disk exited naming the full disk") + } + fill.free(t) + holder.kill(t) + holder = env.start(t, "blockvolume-v1-after-full-wal", "s1") + if got := env.adopt(t, holder, "s1"); got != e { + t.Fatalf("case 1: the restarted holder adopted epoch %d; want %d", got, e) + } + func() { + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + defer c.close() + for ch := 0; ch < cutCrashChunks; ch++ { + for i := 0; i < cutCrashPer; i++ { + lba := uint64(ch*ladderChunkBlocks + i) + _ = c.io.SetDeadline(time.Now().Add(diskFullBound)) + got := c.read(t, lba, 4096) + if w, ok := want[lba]; ok { + if !bytes.Equal(got, w) { + t.Fatalf("case 1: flush-acknowledged LBA %d lost after the disk filled", lba) + } + } else if !bytes.Equal(got, cutCrashBlock('A', lba)) && !bytes.Equal(got, cutCrashBlock('W', lba)) { + t.Fatalf("case 1: LBA %d reads neither image A nor its unflushed write", lba) + } + } + } + for lba, w := range want { + _ = c.io.SetDeadline(time.Now().Add(diskFullBound)) + if !bytes.Equal(c.read(t, lba, 4096), w) { + t.Fatalf("case 1: flush-acknowledged LBA %d lost after the disk filled", lba) + } + } + }() + cutAdvances("case 1, after the space is freed") + + // 2. A new volume's durable root is full. v1 stops first: its flusher + // would take any space freed on the shared disk. + holder.term(t, 30*time.Second) + fill = fillDisk(t, root, 0) + // Either answer names the full disk within the bound: an exit, or the + // process stays up with its durable recovery faulted (status stays + // available, readiness blocked) and never serves. + v2 := env.start(t, "blockvolume-v2-full", "n-v2") + outcome := "" + for end := time.Now().Add(60 * time.Second); outcome == ""; time.Sleep(500 * time.Millisecond) { + select { + case <-v2.done: + outcome = fmt.Sprintf("exited (%v)", v2.err) + default: + } + switch { + case outcome != "": + case v2.has("durable recovery faulted"): + outcome = "stayed up with durable recovery faulted" + case v2.has("adopted as PRIMARY"): + t.Fatalf("case 2: v2 adopted as primary on a full durable root") + case time.Now().After(end): + t.Fatalf("case 2: blockvolume on a full durable root neither exited nor faulted within 60s; log %s", v2.log) + } + } + // The headroom check refuses the create first (free space below the + // volume size + WAL); without it the create fails with ENOSPC. + if !v2.has("no space left on device") && !v2.has("bytes free; volume v2 needs") { + t.Fatalf("case 2: blockvolume %s without naming the full disk; log %s", outcome, v2.log) + } + v2.kill(t) + fill.free(t) + // What the failed create left behind must not stop the next start. + v2 = env.start(t, "blockvolume-v2", "n-v2") + v2.waitLog(t, 60*time.Second, "blockvolume: volume v2 adopted as PRIMARY at r1@") + t.Logf("case 2: on the full root blockvolume %s naming ENOSPC; after freeing, it started over the partial create and adopted v2", outcome) + + // 3. The --host-limit-dir disk is full. + slots := filepath.Join(limit, "slots") + if err := os.Mkdir(slots, 0o700); err != nil { + t.Fatal(err) + } + fill = fillDisk(t, limit, 0) + env.volExtra = append(env.volExtra, "--host-limit-dir", slots) + holder = env.start(t, "blockvolume-v1-full-limit-dir", "s1") + if got := env.adopt(t, holder, "s1"); got != e { + t.Fatalf("case 3: the holder adopted epoch %d; want %d", got, e) + } + env.writeCutCrashImage(t, 'B') + type cutResult struct { + out string + rc int + } + done := make(chan cutResult, 1) + g0 := headGen() + go func() { // off the test goroutine: no t.Fatal here + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) + defer cancel() + out, errOut, rc, err := runCLI(ctx, env.h, cut...) + if err != nil { + rc, errOut = -1, errOut+err.Error() + } + done <- cutResult{out + errOut, rc} + }() + func() { + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + defer c.close() + lba := uint64(cutCrashChunks * ladderChunkBlocks) + if err := diskFullOp(c, func() error { return c.tryWrite(lba, cutCrashBlock('L', lba)) }); err != nil { + t.Fatalf("case 3: guest write with the host-limit dir full: %v", err) + } + if err := diskFullOp(c, c.tryFlush); err != nil { + t.Fatalf("case 3: guest flush with the host-limit dir full: %v", err) + } + }() + var r cutResult + select { + case r = <-done: + case <-time.After(2 * time.Minute): + t.Fatalf("case 3: a cut with the host-limit dir full did not answer within 2m") + } + // Ruled (issue 485): background work, timer and explicit cuts, fails + // closed when the limiter cannot run, and says why; HEAD stays. + if g := headGen(); r.rc == 0 || g != g0 || !strings.Contains(r.out, "no space left on device") { + t.Fatalf("case 3: with the host-limit dir full a cut must be refused naming the full disk; exit %d, HEAD gen %d (was %d):\n%s", r.rc, g, g0, r.out) + } + t.Logf("case 3: cut with the host-limit dir full exited %d; guest write+flush succeeded meanwhile", r.rc) + // The seal of a planned hand-over must not depend on the limit directory. + out, errOut, rc := env.h.run(t, "ops", "chunk", "detach", "--plain", "--volume", "v1", "--status-addr", env.hosts["s1"].status, "--timeout", "120s") + sealed, sealErr := sealedGen(out, errOut, e) + diskFullFinding(t, 486, rc != 0 || sealErr != nil || sealed <= g0, + "case 3: detach --plain with the host-limit dir full exited %d, sealed gen %d (HEAD was %d, %v):\n%s\n%s", rc, sealed, g0, sealErr, out, errOut) + if g := headGen(); rc == 0 && g != sealed { + t.Fatalf("case 3: detach --plain reported gen %d but HEAD is at gen %d", sealed, g) + } + if o, eo, vrc := env.h.run(t, verify...); rc == 0 && vrc != 0 { + t.Fatalf("case 3: the sealed HEAD does not verify (exit %d):\n%s\n%s", vrc, o, eo) + } + fill.free(t) + t.Logf("slowest guest command answer: %s (bound %s)", diskFullSlowest, diskFullBound) + if !t.Failed() { + fmt.Println("DISKFULL_OK") + } +} + +// knownDiskFullFindings are the filed defects this test still expects. +var knownDiskFullFindings = map[int]bool{484: true} // 486 fixed by #487 + +// diskFullFinding is one defect row: bad reports whether issue's defect +// reproduced in this run. +func diskFullFinding(t *testing.T, issue int, bad bool, format string, args ...any) { + t.Helper() + fail, line := diskFullVerdict(knownDiskFullFindings, issue, bad, fmt.Sprintf(format, args...)) + switch { + case fail: + t.Error(line) + case line != "": + t.Log(line) + } +} + +var ( + errDiskFullHang = errors.New("no answer within the bound") + diskFullSlowest time.Duration +) + +// diskFullOp runs op with a deadline on the I/O queue; a timeout is a hang. +func diskFullOp(c *nvmeInitiator, op func() error) error { + start := time.Now() + _ = c.io.SetDeadline(start.Add(diskFullBound)) + err := op() + if d := time.Since(start); d > diskFullSlowest { + diskFullSlowest = d + } + var ne interface{ Timeout() bool } + if errors.As(err, &ne) && ne.Timeout() { + return fmt.Errorf("%w: %v", errDiskFullHang, err) + } + return err +} + +type diskFiller struct{ path string } + +// fillDisk writes a filler file on dir's filesystem until it is full, then +// shrinks it to leave about keep bytes free. +func fillDisk(t *testing.T, dir string, keep int64) diskFiller { + t.Helper() + path := filepath.Join(dir, fmt.Sprintf("filler-%d", time.Now().UnixNano())) + f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if err != nil { + t.Fatal(err) + } + var n int64 + // 1 MiB writes, then 4 KiB ones, so not even a small file still fits. + for _, size := range []int{1 << 20, 4096} { + buf := make([]byte, size) + for { + w, err := f.Write(buf) + n += int64(w) + if err != nil { + if !errors.Is(err, syscall.ENOSPC) { + t.Fatalf("filler: %v", err) + } + break + } + } + } + if err := f.Sync(); err != nil && !errors.Is(err, syscall.ENOSPC) { + t.Fatalf("filler sync: %v", err) + } + if keep > 0 { + if err := f.Truncate(max(n-keep, 0)); err != nil { + t.Fatal(err) + } + } + if err := f.Close(); err != nil && !errors.Is(err, syscall.ENOSPC) { + t.Fatal(err) + } + var st syscall.Statfs_t + _ = syscall.Statfs(dir, &st) + t.Logf("filled %s: filler %d MiB, %d KiB free", dir, n>>20, int64(st.Bavail)*int64(st.Bsize)>>10) + if free := int64(st.Bavail) * int64(st.Bsize); free > keep+(1<<20) { + t.Fatalf("filled %s but %d bytes are still free (want about %d)", dir, free, keep) + } + return diskFiller{path: path} +} + +func (d diskFiller) free(t *testing.T) { + t.Helper() + if err := os.Remove(d.path); err != nil { + t.Fatal(err) + } +} + +// requireDiskFull fails unless dir's file system has (almost) no free space. +func requireDiskFull(t *testing.T, dir, what string) { + t.Helper() + var st syscall.Statfs_t + if err := syscall.Statfs(dir, &st); err != nil { + t.Fatal(err) + } + if free := int64(st.Bavail) * int64(st.Bsize); free > 64<<10 { + t.Fatalf("%s: the disk is not full (%d bytes free)", what, free) + } +} + +// requireSmallDedicatedMount guards the fill: dir must be the root of its own +// small file system, so the filler can only fill the harness's mount. +func requireSmallDedicatedMount(t *testing.T, dir string) { + t.Helper() + var fs syscall.Statfs_t + var self, parent syscall.Stat_t + if err := syscall.Statfs(dir, &fs); err != nil { + t.Fatal(err) + } + if err := syscall.Stat(dir, &self); err != nil { + t.Fatal(err) + } + if err := syscall.Stat(filepath.Dir(dir), &parent); err != nil { + t.Fatal(err) + } + if size := int64(fs.Blocks) * int64(fs.Bsize); self.Dev == parent.Dev || size > 2<<30 { + t.Fatalf("%s must be a dedicated mount of at most 2 GiB (own device %v, size %d)", dir, self.Dev != parent.Dev, size) + } +} diff --git a/seaweed-block/cmd/blockvolume/procedure_diskfull_kernel_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_diskfull_kernel_integration_test.go new file mode 100644 index 0000000000..35bf233c35 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_diskfull_kernel_integration_test.go @@ -0,0 +1,153 @@ +//go:build subprocess && chunkstore_integration && linux + +package main_test + +import ( + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// What a real Linux guest sees when the local disk under a volume's WAL fills +// (issue #484): the kernel NVMe/TCP initiator connects to the +// volume's own target on this host, the durable root's disk fills, and dd +// writes with O_DIRECT. The test records, for the operator guide, whether dd +// stalls or fails and with what, what the kernel logs, and what happens once +// the space is freed. It records; it asserts only that the kernel connects +// and the namespace appears (data survival is TestProcedureLocalDiskFull's). +// +// Environment: as TestProcedureLocalDiskFull, plus SWBLOCK_DISKFULL_KERNEL=1 +// (root, the nvme-tcp module, a disposable host). +func TestProcedureLocalDiskFullKernelInitiator(t *testing.T) { + if os.Getenv("SWBLOCK_DISKFULL_KERNEL") != "1" { + t.Skip("requires SWBLOCK_DISKFULL_KERNEL=1 on a disposable root host") + } + root := os.Getenv("SWBLOCK_DISKFULL_ROOT") + if root == "" { + t.Fatal("SWBLOCK_DISKFULL_ROOT must be set") + } + env := startHandoffEnvWith(t, 1, nil) + if d := os.Getenv("SWBLOCK_REPLAY_LOGS"); d != "" { + t.Cleanup(func() { copyLogs(t, env.h.dir, d) }) + } + h := env.hosts["s1"] + h.root = filepath.Join(root, "vol") + env.hosts["s1"] = h + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + holder := env.start(t, "blockvolume-v1", "s1") + env.adopt(t, holder, "s1") + + sh := func(cmd string) string { + out, err := exec.Command("bash", "-c", cmd).CombinedOutput() + if err != nil { + t.Logf("KERNEL: %q: %v", cmd, err) + } + return strings.TrimSpace(string(out)) + } + if out := sh("modprobe nvme-tcp && grep -c . /dev/nvme-fabrics >/dev/null; echo ok"); !strings.HasSuffix(out, "ok") { + t.Fatalf("nvme-tcp: %s", out) + } + sh("dmesg -C") + // The namespace device is the one /sys/block entry the connect adds (a + // multipath head nvmeXnY or a plain one; per-path nvmeXcYnZ is hidden). + blocks := func() map[string]bool { + m := map[string]bool{} + ns, _ := filepath.Glob("/sys/block/nvme*n*") + for _, n := range ns { + if b := filepath.Base(n); !strings.Contains(strings.TrimPrefix(b, "nvme"), "c") { + m[b] = true + } + } + return m + } + before := blocks() + host, port, _ := strings.Cut(env.hosts["s1"].nvme, ":") + // Its own host NQN needs its own host ID: the kernel refuses a known host + // ID with a different host NQN. + connect := fmt.Sprintf("transport=tcp,traddr=%s,trsvcid=%s,nqn=%s,hostnqn=nqn.2026-11.io.seaweedfs:diskfull-kernel,hostid=5eb10cc0-d15c-4f00-8000-000000000484", host, port, plannedHandoffNQN) + if out := sh("echo " + connect + " > /dev/nvme-fabrics && echo connected"); !strings.Contains(out, "connected") { + t.Fatalf("kernel connect: %s", out) + } + // Registered at once, by NQN: a later failure must not leave the + // controller connected. + t.Cleanup(func() { + ctrls, _ := filepath.Glob("/sys/class/nvme/nvme*") + for _, c := range ctrls { + if b, _ := os.ReadFile(filepath.Join(c, "subsysnqn")); strings.TrimSpace(string(b)) == plannedHandoffNQN { + _ = os.WriteFile(filepath.Join(c, "delete_controller"), []byte("1"), 0o200) + } + } + }) + var ctrl, dev string + for end := time.Now().Add(30 * time.Second); dev == "" || ctrl == ""; time.Sleep(500 * time.Millisecond) { + ctrls, _ := filepath.Glob("/sys/class/nvme/nvme*") + for _, c := range ctrls { + if b, _ := os.ReadFile(filepath.Join(c, "subsysnqn")); strings.TrimSpace(string(b)) == plannedHandoffNQN { + ctrl = c + } + } + for b := range blocks() { + if !before[b] { + dev = "/dev/" + b + } + } + if time.Now().After(end) { + t.Fatalf("no namespace device for %s (controller %q, device %q)", plannedHandoffNQN, ctrl, dev) + } + } + t.Logf("KERNEL: %s connected as %s (%s); multipath=%s io_timeout=%ss max_retries=%s", plannedHandoffNQN, dev, ctrl, + sh("cat /sys/module/nvme_core/parameters/multipath"), sh("cat /sys/module/nvme_core/parameters/io_timeout"), + sh("cat /sys/module/nvme_core/parameters/max_retries")) + + fill := fillDisk(t, root, 2<<20) + // 128 MiB of O_DIRECT 4 KiB writes, more than the 2 MiB left and the WAL. + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) + defer cancel() + dd := exec.CommandContext(ctx, "dd", "if=/dev/urandom", "of="+dev, "bs=4k", "count=32768", "oflag=direct", "status=progress") + var ddOut strings.Builder + dd.Stdout, dd.Stderr = &ddOut, &ddOut + start := time.Now() + if err := dd.Start(); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { done <- dd.Wait() }() + var ddErr error + finished := false + select { + case ddErr = <-done: + finished = true + t.Logf("KERNEL: with the disk full, dd ended after %s: err=%v\n%s", time.Since(start).Round(time.Second), ddErr, ddOut.String()) + case <-time.After(4 * time.Minute): + t.Logf("KERNEL: with the disk full, dd is still running after 4m (the guest stalls); its progress:\n%s", ddOut.String()) + } + t.Logf("KERNEL: dmesg while full:\n%s", sh("dmesg -T | grep -iE 'nvme|blk_update|I/O error|Buffer I/O' | tail -40")) + fill.free(t) + freed := time.Now() + if !finished { + select { + case ddErr = <-done: + t.Logf("KERNEL: after freeing the space, dd finished %s later: err=%v\n%s", time.Since(freed).Round(time.Second), ddErr, ddOut.String()) + case <-time.After(4 * time.Minute): + t.Logf("KERNEL: dd still running 4m after the space was freed") + cancel() + <-done + } + } else { + // After a failure: does a new write succeed once the space is free? + t.Logf("KERNEL: after freeing, a new O_DIRECT write: %s", sh("dd if=/dev/urandom of="+dev+" bs=4k count=256 oflag=direct 2>&1 | tail -1")) + } + t.Logf("KERNEL: dmesg at the end:\n%s", sh("dmesg -T | grep -iE 'nvme|blk_update|I/O error|Buffer I/O' | tail -40")) + t.Logf("KERNEL: holder log ENOSPC lines: %d; frontend ready: %v", strings.Count(readFile(holder.log), "no space left on device"), env.frontendReadyAt("s1")) + fmt.Println("DISKFULL_KERNEL_RECORDED") +} + +func readFile(p string) string { + b, _ := os.ReadFile(p) + return string(b) +} diff --git a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go new file mode 100644 index 0000000000..4bc555fce0 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go @@ -0,0 +1,550 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "os/exec" + "strings" + "testing" + "time" +) + +// The procedure gate: every operator procedure of docs/volume-lifecycle.md +// runs as written, with real binaries, on blockvolume processes with distinct +// server ids (s1, and s2 where a procedure moves the volume) sharing one +// blockmaster and one SeaweedFS. The two start-time tests and the same-host +// restarts use s1 only. The planned return to the same host is +// TestStandalonePlannedHandoffToTheSameHost. + +// TestProcedurePlannedHandoffToAnotherHost: the planned hand-over from s1 to +// s2. The new holder starts with no local copy, claims the sealed HEAD at the +// new epoch and serves the written block. +func TestProcedurePlannedHandoffToAnotherHost(t *testing.T) { + env := startHandoffEnv(t, 2) + must, mustU := fatalOn(t) + h := env.h + + old := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, old, "s1") + block := pattern("to-another-host!") + env.writeBlock(t, "s1", 0, block) + + // Step 1: read the holder; the lease must be granted. + out, _ := h.command(t, env.show...) + must(checkShowGranted(out, e)) + g := env.seal(t, "s1", e) + l := env.sealedLSN(t, e, g) + env.revoke(t, e, g) + if err := old.wait(30 * time.Second); err != nil { + t.Fatalf("s1 after the revocation: %v; want a clean exit by itself", err) + } + env.waitAck(t, e, g) + + moved, _ := h.command(t, env.moveClean(e, "s2", "move-v1-1")...) + e2 := mustU(movedEpochTo(moved, e, g, l, "s2")) + nw := env.start(t, "blockvolume-s2", "s2") + if got := env.adopt(t, nw, "s2"); got != e2 { + t.Fatalf("s2 adopted at epoch %d; want %d", got, e2) + } + out, _ = h.command(t, env.show...) + must(wantLines(out, fmt.Sprintf("holder: r1@%d (logical replica)", e2), + fmt.Sprintf("move: request=move-v1-1 kind=clean issued=true s1/r1@%d -> s2/r1@%d HEAD generation %d remote LSN %d", e, e2, g, l))) + out, _ = h.command(t, env.chunkShow()...) + must(checkLayoutHeadReopenedBy(out, e2, g, l, "s2")) + if !bytes.Equal(env.readBlock(t, "s2", 0), block) { + t.Fatal("the block written on s1 does not read back on s2") + } + // Control: a block never written reads zero, so the comparison above can + // fail. + if !bytes.Equal(env.readBlock(t, "s2", 8), make([]byte, 4096)) { + t.Fatal("a block never written does not read zero on s2") + } +} + +// TestProcedureSameHostRestartInsideTheLease: the page's restart without a +// hand-over, `systemctl restart`: the holder gets SIGTERM, exits, and is +// started again on its host within the unit's RestartSec (5 s), inside the +// 30 s lease. It keeps holder and epoch and serves again at once from its +// local WAL. +func TestProcedureSameHostRestartInsideTheLease(t *testing.T) { + env := startHandoffEnv(t, 1) + first := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, first, "s1") + block := pattern("restart-in-lease") + env.writeBlock(t, "s1", 0, block) + first.term(t, 30*time.Second) + env.restartServesAtOnce(t, "blockvolume-s1-again", e, block) +} + +// TestProcedureSameHostCrashRestartInsideTheLease: the page's "the holder +// comes back within the lease" after a crash: the process is killed and +// started again within the unit's RestartSec (5 s). The same outcome as a +// restart. +func TestProcedureSameHostCrashRestartInsideTheLease(t *testing.T) { + env := startHandoffEnv(t, 1) + first := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, first, "s1") + block := pattern("crash-in-lease!!") + env.writeBlock(t, "s1", 0, block) + first.kill(t) + env.restartServesAtOnce(t, "blockvolume-s1-again", e, block) +} + +// restartServesAtOnce starts s1 again within 5 s of its exit and requires it +// to serve within 15 s ("at once"), as s1/r1 at the same epoch, with the +// written block. +func (env *handoffEnv) restartServesAtOnce(t *testing.T, name string, e uint64, block []byte) { + t.Helper() + must, _ := fatalOn(t) + started := time.Now() + again := env.start(t, name, "s1") + if got := env.adopt(t, again, "s1"); got != e { + t.Fatalf("the restarted holder adopted epoch %d; want the same epoch %d", got, e) + } + if took := time.Since(started); took > 15*time.Second { + t.Fatalf("the restarted holder served after %s; the page says at once", took.Round(time.Second)) + } + out, _ := env.h.command(t, env.show...) + must(checkShowGranted(out, e)) + env.requireHeadHolder(t, e, "s1") + if !bytes.Equal(env.readBlock(t, "s1", 0), block) { + t.Fatal("the block written before the restart does not read back") + } +} + +// TestProcedureReturnAfterALapsedLease: the holder's process dies and stays +// down past its lease. Started again 65 s after it stopped (the page's +// bound with default flags), it is granted again at the same epoch, reclaims +// HEAD and serves its local WAL. +func TestProcedureReturnAfterALapsedLease(t *testing.T) { + env := startHandoffEnv(t, 2) + must, _ := fatalOn(t) + + first := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, first, "s1") + block := pattern("after-lapsed-ttl") + env.writeBlock(t, "s1", 0, block) + first.kill(t) + stopped := time.Now() + + time.Sleep(time.Until(stopped.Add(65 * time.Second))) + started := time.Now() + back := env.start(t, "blockvolume-s1-back", "s1") + if got := env.adopt(t, back, "s1"); got != e { + t.Fatalf("the returning holder adopted epoch %d; want the same epoch %d", got, e) + } + if took := time.Since(started); took > 30*time.Second { + t.Fatalf("the returning holder served after %s, past its 30 s authority wait", took.Round(time.Second)) + } + if back.has("assignment unavailable, not serving") { + t.Fatal("started 65 s after the stop, the holder still logged the not-serving line") + } + out, _ := env.h.command(t, env.show...) + must(checkShowGranted(out, e)) + env.requireHeadHolder(t, e, "s1") + if !bytes.Equal(env.readBlock(t, "s1", 0), block) { + t.Fatal("the block written before the lapse does not read back") + } +} + +// TestProcedureForcedMoveWithTheOldHostReturning: the holder on s1 dies and +// never comes back in time. A forced move to s2, admitted after the barrier, +// restores the last HEAD: a block cut before the crash is kept, one written +// after the cut is lost, as the lost range says. The old s1 process then +// returns with its old local root and must not serve; s2 keeps serving. +func TestProcedureForcedMoveWithTheOldHostReturning(t *testing.T) { + env := startHandoffEnv(t, 2) + must, mustU := fatalOn(t) + h := env.h + + old := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, old, "s1") + kept, lost := pattern("cut-before-crash"), pattern("after-the-cut!!!") + env.writeBlock(t, "s1", 0, kept) + h.command(t, "ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status) + env.writeBlock(t, "s1", 8, lost) + old.kill(t) + + out := env.forceMove(t, e, "s2", "force-v1-1") + e2, keptLSN := mustU(forcedEpoch(out, e, "s1", "s2")), mustU(forcedKeptLSN(out)) + must(wantLines(out, "next: start volume v1 on s2 (this command moved authority only)")) + if !strings.Contains(out, fmt.Sprintf("writes with LSN <= %d are preserved", keptLSN)) { + t.Fatalf("the forced move printed no lost range at LSN %d:\n%s", keptLSN, out) + } + ranges, _ := h.command(t, "ops", "workspace", "lost-range", "--master", h.masterAddr, "--volume", "v1") + if !strings.Contains(ranges, "range 1 of 1: request force-v1-1, r1@") { + t.Fatalf("lost-range does not show the forced move:\n%s", ranges) + } + + nw := env.start(t, "blockvolume-s2", "s2") + if got := env.adopt(t, nw, "s2"); got != e2 { + t.Fatalf("s2 adopted at epoch %d; want %d", got, e2) + } + if !bytes.Equal(env.readBlock(t, "s2", 0), kept) { + t.Fatal("the block cut before the crash is not on s2") + } + if got := env.readBlock(t, "s2", 8); !bytes.Equal(got, make([]byte, 4096)) { + t.Fatal("the block written after the last cut reads back on s2; the page says it is lost") + } + + // The old host returns with its old local root. blockmaster refuses its + // lease with a typed MOVED (the volume moved to s2 at a newer epoch), so + // it exits 78, which the example unit does not restart + // (RestartPreventExitStatus=78); an operator's start again ends the same + // way. Each time it must not take s2's line as its own (a holder is server + // and replica), report its frontend ready or listen for I/O; it logs + // `exiting status=78 reason=moved`. + back := env.oldHostRefuses(t, "blockvolume-s1-back", env.hosts["s1"], e2, 78) + time.Sleep(5 * time.Second) + again := env.oldHostRefuses(t, "blockvolume-s1-restarted", env.hosts["s1"], e2, 78) + // Control: on a fresh local root there is no stale root; the master's + // MOVED refusal alone ends it, also with status 78. + fresh := env.hosts["s1"] + fresh.root = fresh.root + "-fresh" + freshRoot := env.oldHostRefuses(t, "blockvolume-s1-fresh-root", fresh, e2, 78) + // A line carries its owner and that owner's endpoints: every line + // delivered at the forced epoch carries s2's own endpoints, never another + // host's. A returning source can instead be refused MOVED before the + // assignment stream delivers anything (volume-lifecycle.md, do-not list). + if bad := wrongOwnerEndpoints(e2, env.hosts["s2"], nw, back, again, freshRoot); len(bad) > 0 { + t.Errorf("epoch-%d owner evidence invalid (want data=%s ctrl=%s in every delivery, or a moved refusal before delivery):\n%s", + e2, env.hosts["s2"].data, env.hosts["s2"].ctrl, strings.Join(bad, "\n")) + } + env.h.waitPrimaryAt(t, env.hosts["s2"].status, e2) + if !bytes.Equal(env.readBlock(t, "s2", 0), kept) { + t.Fatal("s2 no longer serves the kept block after the old host returned") + } +} + +// TestProcedureRevokeWithoutACKThenForcedMove: the volume is sealed, its +// process is gone before the revoke (so no process ever sends the ACK), and +// the lease is revoked with the sealed generation. The clean move is refused; +// only a forced move to another node remains, and since HEAD is sealed, +// nothing acknowledged is lost. Killing before the revoke makes the missing +// ACK certain; the page's row "Revoked, but no ACK" has the same outcome. +func TestProcedureRevokeWithoutACKThenForcedMove(t *testing.T) { + env := startHandoffEnv(t, 2) + must, mustU := fatalOn(t) + h := env.h + + old := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, old, "s1") + block := pattern("sealed-no-ack!!!") + env.writeBlock(t, "s1", 0, block) + g := env.seal(t, "s1", e) + l := env.sealedLSN(t, e, g) + old.kill(t) + env.revoke(t, e, g) + o, eo, code := h.run(t, env.moveClean(e, "s2", "move-v1-1")...) + must(checkCleanMoveRefused(o, eo, code)) + + out := env.forceMove(t, e, "s2", "force-v1-1") + e2 := mustU(forcedEpoch(out, e, "s1", "s2")) + if got := mustU(forcedKeptLSN(out)); got != l { + t.Fatalf("the forced move kept LSN %d; want the sealed HEAD's %d", got, l) + } + nw := env.start(t, "blockvolume-s2", "s2") + if got := env.adopt(t, nw, "s2"); got != e2 { + t.Fatalf("s2 adopted at epoch %d; want %d", got, e2) + } + if !bytes.Equal(env.readBlock(t, "s2", 0), block) { + t.Fatal("the sealed block does not read back on s2") + } +} + +// TestProcedureStartInsideTheBarrierWaitIsReGranted: the holder's process +// dies and is started again 40 s later: its lease has ended, the re-grant +// barrier (at least 50 s and at most 65 s after the stop, default flags) has +// not passed, and it passes within the process's 30 s authority wait. It must not +// serve while its renewals are still refused for the barrier; once +// re-granted it serves its local WAL at the same epoch. +func TestProcedureStartInsideTheBarrierWaitIsReGranted(t *testing.T) { + env := startHandoffEnv(t, 1) + first := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, first, "s1") + block := pattern("inside-the-wait!") + env.writeBlock(t, "s1", 0, block) + first.kill(t) + time.Sleep(40 * time.Second) + + back := env.start(t, "blockvolume-s1-back", "s1") + var ready []time.Time + end := time.Now().Add(90 * time.Second) + for time.Now().Before(end) { + if env.servingNow("s1") { + ready = append(ready, time.Now()) + if len(ready) >= 5 { + break + } + } + time.Sleep(200 * time.Millisecond) + } + if len(ready) == 0 { + t.Fatal("the returning holder never served within 90 s") + } + // Started before the barrier, its renewals must have been refused for it + // at least once; the UTC log timestamp retains its microseconds. + last := lastLogTime(back, "clock-skew margin has not elapsed") + if last.IsZero() { + t.Fatal("started 40 s after the stop, the returning holder logged no renewal refused for the barrier") + } + if ready[0].Before(last) { + t.Errorf("the returning holder served at %s, while its renewal was still refused for the barrier at %s: it served without a lease", + ready[0].Format("15:04:05.000"), last.Format("15:04:05.000000")) + } + if !back.has("workspace lease: re-granted after ") { + t.Error("the returning holder served without logging its re-grant") + } + if got := env.adopt(t, back, "s1"); got != e { + t.Fatalf("the returning holder adopted epoch %d; want the same epoch %d", got, e) + } + if !bytes.Equal(env.readBlock(t, "s1", 0), block) { + t.Fatal("the block written before the stop does not read back") + } +} + +// lastLogTime is the UTC instant of the last standard log line containing s, +// retaining its fractional seconds, or zero. The process log uses UTC even when +// the test runner's local timezone differs. +func lastLogTime(d *daemon, s string) time.Time { + data, _ := os.ReadFile(d.log) + var last time.Time + for _, l := range strings.Split(string(data), "\n") { + fields := strings.Fields(l) + if strings.Contains(l, s) && len(fields) >= 2 { + if ts, err := time.ParseInLocation("2006/01/02 15:04:05.999999", fields[0]+" "+fields[1], time.UTC); err == nil { + last = ts + } + } + } + return last +} + +// exitCode is a child's exit status (-1 when it did not exit with one). +func exitCode(err error) int { + var exit *exec.ExitError + if err == nil { + return 0 + } + if errors.As(err, &exit) { + return exit.ExitCode() + } + return -1 +} + +// oldHostRefuses starts the old holder b after the volume moved to epoch e2 +// on another host, and returns it. While it runs it must not adopt the new +// line, report its frontend ready or listen; it must log a refusal and exit +// with wantExit. +func (env *handoffEnv) oldHostRefuses(t *testing.T, name string, b bvHost, e2 uint64, wantExit int) *daemon { + t.Helper() + d := env.h.start(t, name, env.h.volume, env.volArgsFor(b)...) + var failures []string + end := time.Now().Add(60 * time.Second) + for alive := true; alive && time.Now().Before(end); { + if l := d.line(fmt.Sprintf("adopted as PRIMARY at r1@%d", e2)); l != "" { + failures = append(failures, "it adopted the new holder's line: "+l) + } + if env.frontendReadyAt("s1") { + failures = append(failures, "its status reports FrontendPrimaryReady") + } + if listening(b.nvme) { + failures = append(failures, "its NVMe/TCP target listens") + } + select { + case <-d.done: + alive = false + case <-time.After(500 * time.Millisecond): + } + } + if err := d.wait(5 * time.Second); exitCode(err) != wantExit { + failures = append(failures, fmt.Sprintf("it did not exit with status %d: %v", wantExit, err)) + } + if wantExit == 78 && !d.has("exiting status=78 reason=moved") { + failures = append(failures, "it did not log `exiting status=78 reason=moved`") + } + if wantExit != 78 && !d.has("refusing to attach volume=v1") && !d.has("workspace lease: stale authority") && !d.has("foreign assignment") { + failures = append(failures, "it logged no refusal (stale root, stale authority, or another server's assignment)") + } + if len(failures) > 0 { + t.Errorf("%s after the forced move: %s", name, strings.Join(failures, "; ")) + } + return d +} + +// servingNow reports whether the host serves: its frontend is ready or its +// NVMe/TCP target accepts connections. +func (env *handoffEnv) servingNow(id string) bool { + return env.frontendReadyAt(id) || listening(env.hosts[id].nvme) +} + +// requireHeadHolder checks that HEAD is active, held by host/r1 at epoch e. +func (env *handoffEnv) requireHeadHolder(t *testing.T, e uint64, host string) { + t.Helper() + out, _ := env.h.command(t, env.chunkShow()...) + head, err := parseLayoutHead(out) + if err != nil { + t.Fatal(err) + } + if head.State != "" || head.ClaimID == "" || head.Epoch != e || head.Holder != host+"/r1" { + t.Fatalf("HEAD %+v; want live at epoch %d held by %s/r1", head, e, host) + } +} + +func (env *handoffEnv) start(t *testing.T, name, id string) *daemon { + t.Helper() + return env.h.start(t, name, env.h.volume, env.volArgs(id)...) +} + +// adopt waits for the process to adopt v1 as primary, its host to report it +// a healthy primary, and its frontend to admit guest I/O +// (FrontendPrimaryReady), and returns the epoch. Healthy alone is not +// enough: until the frontend admits I/O, a write is answered "namespace not +// ready" (retryable), which the test's initiator does not retry. +func (env *handoffEnv) adopt(t *testing.T, d *daemon, id string) uint64 { + t.Helper() + _, mustU := fatalOn(t) + e := mustU(adoptedEpoch(d.waitLog(t, 60*time.Second, "blockvolume: volume v1 adopted as PRIMARY at r1@"))) + env.h.waitPrimaryAt(t, env.hosts[id].status, e) + poll(t, 60*time.Second, fmt.Sprintf("%s: the holder adopted epoch %d but never reported its frontend ready", id, e), func() bool { + return env.frontendReadyAt(id) + }) + return e +} + +// frontendReadyAt reports whether the host's status shows v1's frontend +// ready to serve. +func (env *handoffEnv) frontendReadyAt(id string) bool { + c := &http.Client{Timeout: 2 * time.Second} + resp, err := c.Get("http://" + env.hosts[id].status + "/status?volume=v1") + if err != nil { + return false + } + defer resp.Body.Close() + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + return frontendReady(b) +} + +// listening reports whether something accepts TCP connections at addr. +func listening(addr string) bool { + c, err := net.DialTimeout("tcp", addr, time.Second) + if err != nil { + return false + } + c.Close() + return true +} + +func (env *handoffEnv) writeBlock(t *testing.T, id string, lba uint64, data []byte) { + t.Helper() + c := dialNVMe(t, env.hosts[id].nvme, plannedHandoffNQN) + defer c.close() + c.write(t, lba, data) + c.flush(t) +} + +func (env *handoffEnv) readBlock(t *testing.T, id string, lba uint64) []byte { + t.Helper() + c := dialNVMe(t, env.hosts[id].nvme, plannedHandoffNQN) + defer c.close() + return c.read(t, lba, 4096) +} + +func (env *handoffEnv) seal(t *testing.T, id string, e uint64) uint64 { + t.Helper() + _, mustU := fatalOn(t) + out, errOut := env.h.command(t, "ops", "chunk", "detach", "--plain", "--volume", "v1", "--status-addr", env.hosts[id].status, "--timeout", "120s") + return mustU(sealedGen(out, errOut, e)) +} + +func (env *handoffEnv) chunkShow() []string { + return []string{"ops", "chunk", "show", "--master", env.h.masterAddr, "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath} +} + +func (env *handoffEnv) sealedLSN(t *testing.T, e, g uint64) uint64 { + t.Helper() + _, mustU := fatalOn(t) + out, _ := env.h.command(t, env.chunkShow()...) + return mustU(sealedLayoutHeadPosition(out, e, g)) +} + +func (env *handoffEnv) revoke(t *testing.T, e, g uint64) { + t.Helper() + must, _ := fatalOn(t) + out, _ := env.h.command(t, "ops", "workspace", "revoke", "--master", env.h.masterAddr, "--volume", "v1", "--replica", "r1", + "--epoch", fmt.Sprint(e), "--sealed-gen", fmt.Sprint(g)) + must(checkRevoke(out, e, g)) +} + +func (env *handoffEnv) waitAck(t *testing.T, e, g uint64) { + t.Helper() + poll(t, 30*time.Second, fmt.Sprintf("workspace show never reported the ACK of r1@%d at generation %d", e, g), func() bool { + out, _ := env.h.command(t, env.show...) + return showsAck(out, e, g) + }) +} + +func (env *handoffEnv) moveClean(e uint64, target, request string) []string { + b := env.hosts[target] + return []string{"ops", "workspace", "move", "--clean", "--master", env.h.masterAddr, "--volume", "v1", "--replica", "r1", + "--epoch", fmt.Sprint(e), "--target-host", b.id, "--target-data", b.data, "--target-ctrl", b.ctrl, "--request-id", request} +} + +// forceMove runs the page's forced move: --dry-run until it says admitted +// (the barrier: at most 65 s after the holder stopped, with defaults, plus a +// margin), then the move itself, whose stdout it returns. +func (env *handoffEnv) forceMove(t *testing.T, e uint64, target, request string) string { + t.Helper() + b := env.hosts[target] + args := []string{"ops", "workspace", "force-move", "--master", env.h.masterAddr, "--volume", "v1", + "--target-host", b.id, "--target-data", b.data, "--target-ctrl", b.ctrl, + "--request-id", request, "--confirm-forced", fmt.Sprintf("v1@%d", e)} + first, _ := env.h.command(t, append(args, "--dry-run")...) + if !previewAdmitted(first) && !strings.Contains(first, "admissible at ") { + t.Fatalf("a refused preview does not say when the move is admissible:\n%s", first) + } + poll(t, 90*time.Second, "the forced move was never admitted", func() bool { + out, _ := env.h.command(t, append(args, "--dry-run")...) + return previewAdmitted(out) + }) + out, _ := env.h.command(t, args...) + return out +} + +// wrongOwnerEndpoints returns every "assignment stream delivery" log line at epoch e (in any of ds) whose data or control +// endpoint is not owner's, plus an entry for each recipient whose log cannot be +// read or shows neither an epoch-e delivery nor the documented MOVED refusal. +func wrongOwnerEndpoints(e uint64, owner bvHost, ds ...*daemon) []string { + var bad []string + tag := fmt.Sprintf(" epoch=%d ev=", e) + for _, d := range ds { + raw, err := os.ReadFile(d.log) + if err != nil { + bad = append(bad, d.name+": log unreadable: "+err.Error()) + continue + } + seen := 0 + for _, l := range strings.Split(string(raw), "\n") { + if !strings.Contains(l, "assignment stream delivery") || !strings.Contains(l, tag) { + continue + } + seen++ + if !strings.Contains(l, fmt.Sprintf("data=%q", owner.data)) || !strings.Contains(l, fmt.Sprintf("ctrl=%q", owner.ctrl)) { + bad = append(bad, d.name+": "+strings.TrimSpace(l)) + } + } + if seen == 0 && !strings.Contains(string(raw), "blockvolume: exiting status=78 reason=moved") { + // Mere absence proves nothing. The master's typed MOVED refusal + // ends an old source's stream before any fact can be delivered. + bad = append(bad, d.name+": no epoch delivery logged") + } + } + return bad +} diff --git a/seaweed-block/cmd/blockvolume/procedure_layout_head_checks_test.go b/seaweed-block/cmd/blockvolume/procedure_layout_head_checks_test.go new file mode 100644 index 0000000000..abb8110b1b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_layout_head_checks_test.go @@ -0,0 +1,61 @@ +package main_test + +import ( + "encoding/json" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// chunk show marshals layout.Head, not the on-store headDoc or the retired +// storage HEAD. Keep the procedure checks tied to that actual output type. +func TestProcedureLayoutHeadChecksReadProductShape(t *testing.T) { + show := func(h layout.Head) string { + t.Helper() + b, err := json.Marshal(struct { + Head layout.Head `json:"head"` + }{h}) + if err != nil { + t.Fatal(err) + } + return string(b) + } + sealed := layout.Head{Gen: 7, Epoch: 3, Holder: "s1/r1", ClaimID: "claim", + Position: 91, State: layout.StateDetached, Current: &layout.RootName{Hash: layout.Hash{1}}} + if got, err := sealedLayoutHeadPosition(show(sealed), 3, 7); err != nil || got != 91 { + t.Fatalf("detached layout image: position=%d err=%v", got, err) + } + live := sealed + live.Gen, live.Epoch, live.Holder, live.ClaimID, live.State = 8, 4, "s2/r1", "next-claim", layout.StateLive + if err := checkLayoutHeadReopenedBy(show(live), 4, 7, 91, "s2"); err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name string + mutate func(*layout.Head) + }{ + {"generation", func(h *layout.Head) { h.Gen = 6 }}, + {"epoch", func(h *layout.Head) { h.Epoch++ }}, + {"holder", func(h *layout.Head) { h.Holder = "foreign/r1" }}, + {"claim", func(h *layout.Head) { h.ClaimID = "" }}, + {"image", func(h *layout.Head) { h.Current = nil }}, + {"state", func(h *layout.Head) { h.State = layout.StateDeleting }}, + } { + t.Run(tc.name, func(t *testing.T) { + h := sealed + tc.mutate(&h) + if _, err := sealedLayoutHeadPosition(show(h), 3, 7); err == nil { + t.Fatal("invalid detached proof accepted") + } + h = live + tc.mutate(&h) + if err := checkLayoutHeadReopenedBy(show(h), 4, 7, 91, "s2"); err == nil { + t.Fatal("invalid successor accepted") + } + }) + } + live.Position++ + if err := checkLayoutHeadReopenedBy(show(live), 4, 7, 91, "s2"); err == nil { + t.Fatal("changed committed position accepted") + } +} diff --git a/seaweed-block/cmd/blockvolume/procedure_log_time_contract_test.go b/seaweed-block/cmd/blockvolume/procedure_log_time_contract_test.go new file mode 100644 index 0000000000..fbc987b76a --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_log_time_contract_test.go @@ -0,0 +1,36 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +func TestProcedureLogTimesUseTheUTCInstant(t *testing.T) { + old := time.Local + time.Local = time.FixedZone("UTC-8", -8*60*60) + defer func() { time.Local = old }() + const reason = "clock-skew margin has not elapsed" + for _, tc := range []struct { + name, stamp string + nanos int + }{ + {"microseconds", "2026/11/29 05:12:42.123456", 123456000}, + {"whole-second", "2026/11/29 05:12:42", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "holder.log") + if err := os.WriteFile(path, []byte(tc.stamp+" "+reason+"\n"), 0600); err != nil { + t.Fatal(err) + } + got := lastLogTime(&daemon{log: path}, reason) + want := time.Date(2026, 11, 29, 5, 12, 42, tc.nanos, time.UTC) + if !got.Equal(want) { + t.Fatalf("log instant %s; want %s", got.Format(time.RFC3339Nano), want.Format(time.RFC3339Nano)) + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/procedure_master_revoke_crash_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_master_revoke_crash_integration_test.go new file mode 100644 index 0000000000..7b3c70b1f7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_master_revoke_crash_integration_test.go @@ -0,0 +1,146 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "context" + "errors" + "fmt" + "os" + "os/exec" + "strings" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" +) + +// P13.6 / INV-WS-CLEAN-MOVE-001 / INV-WS-REVOKE-ACK-001: +// Revoking survives blockmaster SIGKILL; after restart, the same holder +// may finish its valid drain and ACK before a clean move reads the data. +func TestProcedureMasterKilledWhileRevoking(t *testing.T) { + masterKilledWhileRevoking(t, true) +} + +// The live holder must also finish after a master crash without a test- +// induced pause consuming its lease. Lease expiry here is a product finding. +func TestProcedureMasterKilledWhileRevokingWithoutHolderPause(t *testing.T) { + masterKilledWhileRevoking(t, false) +} + +func masterKilledWhileRevoking(t *testing.T, freeze bool) { + t.Helper() + env := startHandoffEnv(t, 2) + holder := env.start(t, "holder-before-master-kill", "s1") + e := env.adopt(t, holder, "s1") + want := bytes.Repeat([]byte{0x6d}, 4096) + env.writeBlock(t, "s1", 7, want) + g := env.seal(t, "s1", e) + l := env.sealedLSN(t, e, g) + // Freeze only the owned holder so it cannot race an ACK past the + // observed Revoking/no-ACK boundary. This is not a graceful master stop. + conn, err := grpc.NewClient(env.h.masterAddr, env.masterDialOption(t, "s1")) // it renews as the holder + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ws := control.NewWorkspaceServiceClient(conn) + identity := &control.WorkspaceIdentity{VolumeId: "v1", ReplicaId: "r1", ServerId: "s1", Epoch: e} + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + // This probe updates the master's lease view, not the holder's monotonic + // deadline. The holder still has to finish using its own renewal history. + lease, err := ws.RenewWorkspaceLease(ctx, identity) + cancel() + if err != nil || lease.GetValidForNs() <= 0 { + t.Fatalf("pre-crash lease: %v %v", lease, err) + } + validity := time.Duration(lease.GetValidForNs()) + frozenAt := time.Now() + if freeze { + if err := holder.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatal(err) + } + } + env.revoke(t, e, g) + requireRevoking := func() { + t.Helper() + out, _ := env.h.command(t, env.show...) + if !hasLine(out, fmt.Sprintf("epoch: %d", e)) || !hasLine(out, "lease state: revoking") || + !hasLine(out, "recorded ACK: none") { + t.Fatalf("want the same Revoking line and no ACK:\n%s", out) + } + } + if freeze { + requireRevoking() + } + env.masterProcess.kill(t) + var exited *exec.ExitError + if !errors.As(env.masterProcess.err, &exited) { + t.Fatalf("master did not have a signal exit: %v", env.masterProcess.err) + } + status, ok := exited.Sys().(syscall.WaitStatus) + if !ok || !status.Signaled() || status.Signal() != syscall.SIGKILL { + t.Fatalf("master exit %v; want SIGKILL", exited) + } + restarted := env.h.start(t, "blockmaster-after-revoke-kill", env.h.master, env.masterArgs...) + restarted.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + if freeze { + requireRevoking() + out, errs, code := env.h.run(t, env.moveClean(e, "s2", "before-ack")...) + if err := checkCleanMoveRefused(out, errs, code); err != nil { + t.Fatal(err) + } + b := env.hosts["s2"] + out, errs, code = env.h.run(t, "ops", "workspace", "force-move", "--master", env.h.masterAddr, + "--volume", "v1", "--target-host", b.id, "--target-data", b.data, "--target-ctrl", b.ctrl, + "--request-id", "before-expiry", "--confirm-forced", fmt.Sprintf("v1@%d", e), "--dry-run") + if code != 0 || !strings.Contains(out, "forced move not admitted:") || !strings.Contains(out, "admissible at ") { + t.Fatalf("forced preview must affirmatively refuse unexpired lease: code=%d out=%s err=%s", code, out, errs) + } + requireRevoking() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + renewed, renewErr := ws.RenewWorkspaceLease(ctx, identity) + cancel() + t.Logf("post-reload renewal: reply=%v error=%v", renewed, renewErr) + if renewErr != nil || !renewed.GetRevoking() || renewed.GetValidForNs() <= 0 { + t.Fatalf("PRODUCT: reloaded master cannot answer the valid Revoking holder: %v %v", renewed, renewErr) + } + } + if got := env.sealedLSN(t, e, g); got != l { + t.Fatalf("master restart changed the sealed LSN %d -> %d", l, got) + } + if freeze { + elapsed := time.Since(frozenAt) + t.Logf("frozen duration=%s, sampled host lease validity=%s, required below one third", elapsed, validity) + if elapsed >= validity/3 { + t.Fatal("INCONCLUSIVE: test pause consumed too much lease validity") + } + if err := holder.proc.Signal(syscall.SIGCONT); err != nil { + t.Fatal(err) + } + } + if err := holder.wait(30 * time.Second); err != nil { + // Diagnostic output on failure, not a successful exit-75 classification: + // the public journal view and both logs distinguish the barrier from a + // test-induced delay. Every nonzero holder exit still fails this test. + out, _, code := env.h.run(t, env.show...) + masterLog, _ := os.ReadFile(restarted.log) + holderLog, _ := os.ReadFile(holder.log) + t.Fatalf("PRODUCT: holder failed restored revocation (paused=%t, exit=%d): %v; master journal view code=%d: %s; master log=%s; holder log=%s", freeze, exitCode(err), err, code, out, masterLog, holderLog) + } + env.waitAck(t, e, g) + out, _ := env.h.command(t, env.moveClean(e, "s2", "move-v1-1")...) + _, mustU := fatalOn(t) + e2 := mustU(movedEpochTo(out, e, g, l, "s2")) + target := env.start(t, "holder-after-restored-revocation", "s2") + if got := env.adopt(t, target, "s2"); got != e2 { + t.Fatalf("move target adopted epoch %d; want %d", got, e2) + } + env.requireHeadHolder(t, e2, "s2") + if got := env.readBlock(t, "s2", 7); !bytes.Equal(got, want) { + t.Fatal("clean move after master SIGKILL lost the acknowledged block") + } +} diff --git a/seaweed-block/cmd/blockvolume/procedure_plain_detach_crash_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_plain_detach_crash_integration_test.go new file mode 100644 index 0000000000..9b191303c2 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_plain_detach_crash_integration_test.go @@ -0,0 +1,151 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "os/exec" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// P12.6 / INV-WS-SEAL-REPLAY-001: a SIGKILL during plain-seal upload +// must not strand the hand-over. The kill is witnessed by a new immutable +// key and an unchanged active HEAD, not by a delay or a successful CLI exit. +func TestProcedureKillDuringPlainDetachThenCompleteHandoff(t *testing.T) { + env := startHandoffEnv(t, 2) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off", "--chunk-upload-concurrency", "1"} + holder := env.start(t, "holder-before-detach-kill", "s1") + e := env.adopt(t, holder, "s1") + env.writeCutCrashImage(t, 'A') + env.h.command(t, "ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status) + out, _ := env.h.command(t, env.chunkShow()...) + before, err := parseLayoutHead(out) + if err != nil || before.State != "" || before.ClaimID == "" || before.Epoch != e { + t.Fatalf("baseline HEAD: %+v: %v", before, err) + } + env.writeCutCrashImage(t, 'B') + keys := plainDetachStoredKeys(t, env) + cli := env.h.start(t, "plain-detach-interrupted", env.h.cli, "ops", "chunk", "detach", "--plain", + "--volume", "v1", "--status-addr", env.hosts["s1"].status, "--timeout", "120s") + uploadDeadline := time.Now().Add(60 * time.Second) + for { + select { + case <-cli.done: + t.Fatal("detach finished before the mid-upload kill witness") + default: + } + if plainDetachStoredKeys(t, env) > keys { + break + } + if time.Now().After(uploadDeadline) { + t.Fatal("plain detach stored no new immutable chunk") + } + time.Sleep(2 * time.Millisecond) + } + // Stop only this child before reading the remote proof, so the uploader + // cannot cross its CAS while the test verifies where the kill will land. + if err := holder.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatal(err) + } + out, _ = env.h.command(t, env.chunkShow()...) + atKill, err := parseLayoutHead(out) + if err != nil || atKill.Gen != before.Gen || atKill.State != "" || atKill.ClaimID != before.ClaimID || atKill.Position != before.Position { + t.Fatalf("missed mid-upload window: before=%+v stopped=%+v: %v", before, atKill, err) + } + t.Logf("kill witness: immutable keys %d -> %d, HEAD gen=%d LSN=%d remains active", keys, plainDetachStoredKeys(t, env), atKill.Gen, atKill.Position) + select { + case <-cli.done: + t.Fatal("detach completed or aborted before the verified kill window") + default: + } + holder.kill(t) + var exited *exec.ExitError + if !errors.As(holder.err, &exited) { + t.Fatalf("holder did not have a signal exit: %v", holder.err) + } + status, ok := exited.Sys().(syscall.WaitStatus) + if !ok || !status.Signaled() || status.Signal() != syscall.SIGKILL { + t.Fatalf("holder exit %v; want SIGKILL", exited) + } + if err := cli.wait(15 * time.Second); err == nil { + t.Fatal("interrupted detach unexpectedly returned success") + } + select { + case <-cli.done: + default: + t.Fatal("interrupted detach command did not join") + } + // No graceful Close ran. Reopen the same root and prove every Flush- + // acknowledged block survives before retrying the public plain detach. + holder = env.start(t, "holder-after-detach-kill", "s1") + if got := env.adopt(t, holder, "s1"); got != e { + t.Fatalf("reopened epoch %d; want %d", got, e) + } + env.requireCutCrashImage(t, "s1", 'B') + g := env.seal(t, "s1", e) + l := env.sealedLSN(t, e, g) + if l <= before.Position { + t.Fatalf("retry did not publish the acknowledged image: remote LSN %d <= baseline %d", l, before.Position) + } + if again := env.seal(t, "s1", e); again != g { + t.Fatalf("plain seal replay changed generation %d -> %d", g, again) + } + env.revoke(t, e, g) + if err := holder.wait(30 * time.Second); err != nil { + t.Fatalf("revoked restarted holder did not exit cleanly: %v", err) + } + env.waitAck(t, e, g) + out, _ = env.h.command(t, env.moveClean(e, "s2", "move-v1-1")...) + _, mustU := fatalOn(t) + e2 := mustU(movedEpochTo(out, e, g, l, "s2")) + next := env.start(t, "holder-after-clean-move", "s2") + if got := env.adopt(t, next, "s2"); got != e2 { + t.Fatalf("clean move adopted epoch %d; want %d", got, e2) + } + // A fresh root on another host cannot satisfy this from the source WAL. + env.requireCutCrashImage(t, "s2", 'B') + verified, _ := env.h.command(t, "ops", "chunk", "verify", "--volume", "v1", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, + "--depth", "data", "--timeout", "60s") + var result layout.VerifyResult + if err := json.Unmarshal([]byte(verified), &result); err != nil || !result.Complete || + len(result.Findings) != 0 || result.Chunks == 0 { + t.Fatalf("post-move data verify incomplete or corrupt: %s: %v", verified, err) + } +} + +// This is the real filer's public listing of immutable key bindings, not +// directory/intent growth. Every non-200, malformed or truncated listing +// fails instead of supplying a positive crash-stage witness. +func plainDetachStoredKeys(t *testing.T, env *handoffEnv) int { + t.Helper() + c := &http.Client{Timeout: 3 * time.Second} + req, err := http.NewRequest(http.MethodGet, "http://"+env.cluster.filerHTTP+env.chunkPath+"/v1/keys/?limit=1000", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Accept", "application/json") + resp, err := c.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var listing struct { + Entries []json.RawMessage + ShouldDisplayLoadMore bool + } + if resp.StatusCode != http.StatusOK { + t.Fatal(fmt.Errorf("immutable key listing status %d", resp.StatusCode)) + } + if err := json.NewDecoder(resp.Body).Decode(&listing); err != nil || listing.ShouldDisplayLoadMore { + t.Fatalf("immutable key listing incomplete: %v, more=%t", err, listing.ShouldDisplayLoadMore) + } + return len(listing.Entries) +} diff --git a/seaweed-block/cmd/blockvolume/procedure_powerloss_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_powerloss_integration_test.go new file mode 100644 index 0000000000..a8ea00e254 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_powerloss_integration_test.go @@ -0,0 +1,192 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "context" + "fmt" + "os" + "path" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// Power loss on a chunk volume (INV-FE-FLUSH-SYNC-001), +// with real binaries: blockmaster, a real filer (weed, its data off the +// replayed device) and a walstore-chunk blockvolume whose durable root is on +// a dm-log-writes device. Each power cut freezes the holder (SIGSTOP), so +// neither its disk nor the filer moves past the mark, marks the log, kills +// the holder, replays the log only up to the mark onto a fresh device (the +// harness puts a new log-writes layer on it and remounts it at the same +// path), restarts the holder and requires every flush-acknowledged block, +// then a cut that moves HEAD to a new generation and verifies at depth data; +// at the end a snapshot restored into a new volume is the last image. The phases: +// +// 1. image A flushed and cut (committed, WAL trimmed), then a power cut; +// 2. image B over the same LBAs, flushed, one more write without a flush, +// then a power cut (image A in HEAD must not show through); +// 3. a new image flushed, a cut started, a power cut while it uploads (the +// first applied object-create reply is held until the holder is killed). +// +// Environment: SWBLOCK_REPLAY_ROOT and SWBLOCK_REPLAY_CUT as for +// TestPowerLossReplayAckedWritesSurvive; CHUNKSTORE_WEED; optional +// SWBLOCK_TEST_BINS and SWBLOCK_REPLAY_LOGS. +func TestPowerLossReplayChunkVolume(t *testing.T) { + root, cutTool := os.Getenv("SWBLOCK_REPLAY_ROOT"), os.Getenv("SWBLOCK_REPLAY_CUT") + if root == "" && cutTool == "" { + t.Skip("requires the isolated dm-log-writes replay harness") + } + if root == "" || cutTool == "" { + t.Fatalf("SWBLOCK_REPLAY_ROOT=%q and SWBLOCK_REPLAY_CUT=%q must be set together", root, cutTool) + } + if testListenHost() != "127.0.0.1" { + t.Fatal("causal filer fixture requires loopback") + } + var boundary *snapshotFilerBoundary + cluster := startWorkspaceWeedWith(t, t.TempDir(), w4WeedOpts{VolumeSizeLimitMB: 256, VolumeMax: 32, + FilerBind: "127.0.0.2", FilerFront: func(c *w4WeedCluster) { boundary = newSnapshotFilerBoundary(t, c) }}) + env := startHandoffEnvOnCluster(t, 1, []string{"v2"}, procedureTLSConfig(), false, cluster) + id, err := layout.ParseVolumeID(env.layoutID("v1")) + if err != nil { + t.Fatal(err) + } + boundary.id = id + boundary.dir = path.Join(env.chunkPath, layout.VolumeDir("v1", id)) + if d := os.Getenv("SWBLOCK_REPLAY_LOGS"); d != "" { + t.Cleanup(func() { copyLogs(t, env.h.dir, d) }) + } + h := env.hosts["s1"] + h.root = filepath.Join(root, "vol") + env.hosts["s1"] = h + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + cut := []string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status} + verify := []string{"ops", "chunk", "verify", "--master", env.h.masterAddr, "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data", "--timeout", "5m"} + headGen := func() uint64 { + out, _ := env.h.command(t, env.chunkShow()...) + hd, err := parseLayoutHead(out) + if err != nil { + t.Fatal(err) + } + return hd.Gen + } + + holder := env.start(t, "blockvolume-v1", "s1") + e := env.adopt(t, holder, "s1") + cuts := 0 + // powerCut ends at a restarted holder that serves every acknowledged block + // of img, and a cut that verifies; with advance, that cut must move HEAD to + // a new generation (a cut that uploads nothing would leave it). frozenGen, + // when not 0, is the HEAD generation seen while frozen: it must still hold + // after the kill, so no HEAD write from before the freeze landed later. + powerCut := func(phase string, img byte, frozenGen uint64, advance bool, afterKill func()) { + t.Helper() + if err := holder.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatalf("%s: freeze the holder: %v", phase, err) + } + runReplayCut(t, cutTool, "mark") + holder.kill(t) + if afterKill != nil { + afterKill() + } + if frozenGen != 0 { + if g := headGen(); g != frozenGen { + t.Fatalf("%s: HEAD moved from gen %d to %d after the freeze: the cut was not in progress at the mark", phase, frozenGen, g) + } + } + runReplayCut(t, cutTool, "replay") + cuts++ + holder = env.start(t, fmt.Sprintf("blockvolume-v1-after-cut-%d", cuts), "s1") + if got := env.adopt(t, holder, "s1"); got != e { + t.Fatalf("%s: the restarted holder adopted epoch %d; want %d", phase, got, e) + } + env.requireCutCrashImage(t, "s1", img) + g0 := headGen() + env.h.command(t, cut...) + if g := headGen(); advance && g <= g0 { + t.Fatalf("%s: the cut after the replay left HEAD at gen %d (was %d): the replayed writes were not published", phase, g, g0) + } + if out, errOut, rc := env.h.run(t, verify...); rc != 0 { + t.Fatalf("%s: HEAD does not verify after the replay (exit %d):\n%s\n%s", phase, rc, out, errOut) + } + t.Logf("%s: power cut %d replayed; image %c read back; the next cut committed and verified", phase, cuts, img) + } + + // Phase 1: a committed cut before the power cut. + env.writeCutCrashImage(t, 'A') + env.h.command(t, cut...) + powerCut("phase 1 (after a committed cut)", 'A', 0, false, nil) + + // Phase 2: overwrite with B; then a write the guest never flushed. + env.writeCutCrashImage(t, 'B') + extra := uint64(cutCrashChunks * ladderChunkBlocks) + before := func() []byte { + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + defer c.close() + return c.read(t, extra, 4096) + }() + func() { + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + defer c.close() + c.write(t, extra, cutCrashBlock('x', extra)) + }() + powerCut("phase 2 (between a write and its flush)", 'B', 0, true, nil) + func() { + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + defer c.close() + got := c.read(t, extra, 4096) + if !bytes.Equal(got, before) && !bytes.Equal(got, cutCrashBlock('x', extra)) { + t.Fatalf("phase 2: the unflushed block reads neither its old nor its new content") + } + }() + + // Phase 3: hold the stock filer's first applied object-create answer. + // Begin itself advances HEAD; generation movement is not proof of Commit. + // Observe an open session and unchanged Current at the actual object boundary. + img := byte('C') + env.writeCutCrashImage(t, img) + beforeHead := boundary.head(t) + reached := boundary.arm("OBJECT", "") + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) + defer cancel() + done := make(chan struct{}) + go func() { defer close(done); _, _, _, _ = runCLI(ctx, env.h, cut...) }() + t.Cleanup(func() { cancel(); boundary.unblock(); <-done }) + select { + case <-reached: + case <-time.After(30 * time.Second): + cancel() + boundary.unblock() + <-done + t.Fatal("inconclusive: cut never reached applied object boundary") + } + if err := holder.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatal(err) + } + frozen := boundary.head(t) + if frozen.Activity.Kind != layout.ActSnap || frozen.Activity.Session == "" || frozen.Current == nil || beforeHead.Current == nil || *frozen.Current != *beforeHead.Current { + t.Fatalf("object boundary is not an open unpublished cut: before=%+v frozen=%+v", beforeHead, frozen) + } + t.Logf("phase 3: applied object held, HEAD gen=%d open session=%s Current unchanged", frozen.Gen, frozen.Activity.Session) + // Mark and kill while the holder is stopped, then release the old RPC before + // checking the exact frozen HEAD and restarting from the replayed device. + powerCut("phase 3 (cut in progress)", img, frozen.Gen, true, func() { boundary.unblock(); <-done }) + // What the filer holds is the image: a snapshot restored into a new volume. + env.snapshot(t, "s1", "v1", "after-power-cuts") + env.restoreInto(t, "v1", "after-power-cuts", "v2") + env.requireCutCrashImage(t, "n-v2", img) + fmt.Printf("REPLAY_chunk_OK power_cuts=%d last_image=%c\n", cuts, img) +} + +func copyLogs(t *testing.T, from, to string) { + logs, _ := filepath.Glob(filepath.Join(from, "*.log")) + for _, l := range logs { + if b, err := os.ReadFile(l); err == nil { + _ = os.WriteFile(filepath.Join(to, filepath.Base(l)), b, 0o644) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go new file mode 100644 index 0000000000..bf9fda3f1c --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go @@ -0,0 +1,139 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "context" + "fmt" + "io" + "net" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// This opt-in procedure uses the kernel's block I/O retry path, not passthrough +// commands or the userspace test initiator. The lab's retained build overlay +// holds the holder's first write Busy for 2 s before any storage I/O. +func TestProcedureKernelReadinessRetryDelay(t *testing.T) { + if os.Getenv("SWBLOCK_NVME_RETRY_KERNEL") != "1" { + t.Skip("requires a disposable root Linux host and the retained 2s Busy overlay") + } + budget, err := os.ReadFile("/sys/module/nvme_core/parameters/max_retries") + if err != nil || strings.TrimSpace(string(budget)) != "5" { + t.Fatalf("kernel max_retries=%q err=%v; require default5", budget, err) + } + uuid, err := os.ReadFile("/proc/sys/kernel/random/uuid") + if err != nil { + t.Fatal(err) + } + token := strings.TrimSpace(string(uuid)) + nqn := "nqn.2026-12.io.seaweedfs:retry-" + strings.ReplaceAll(token, "-", "") + root := t.TempDir() + receipt := filepath.Join(root, "busy-started") + t.Setenv("SWBLOCK_TEST_BUSY_RECEIPT", receipt) + env := startHandoffEnvWith(t, 1, nil) + env.volExtra = []string{"--nvme-subsysnqn", nqn, "--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + holder := env.start(t, "kernel-retry-holder", "s1") + env.adopt(t, holder, "s1") + host, port, err := net.SplitHostPort(env.hosts["s1"].nvme) + if err != nil { + t.Fatal(err) + } + fabric, err := os.OpenFile("/dev/nvme-fabrics", os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + var controller string + connected := false + // Keep the fabrics fd (and its kernel controller reference) until teardown. + t.Cleanup(func() { + defer func() { + if err := fabric.Close(); err != nil { + t.Errorf("close fabrics handle: %v", err) + } + }() + if controller == "" { + if connected { + t.Error("connected controller identity unresolved; cleanup not proven") + } + return + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := disconnectRetryController(ctx, controller, nqn); err != nil { + t.Errorf("owned controller teardown unresolved: %v", err) + } + }) + _, err = fabric.WriteString(fmt.Sprintf("transport=tcp,traddr=%s,trsvcid=%s,nqn=%s,hostnqn=nqn.2026-12.io.seaweedfs:host-%s,hostid=%s,nr_io_queues=1", host, port, nqn, token, token)) + if err != nil { + t.Fatalf("kernel connect: %v", err) + } + connected = true + answer, err := io.ReadAll(io.LimitReader(fabric, 4096)) + if err != nil { + t.Fatalf("read acquired controller identity: %v", err) + } + instance, err := retryControllerInstance(string(answer)) + if err != nil { + t.Fatal(err) + } + controller = filepath.Join("/sys/class/nvme", fmt.Sprintf("nvme%d", instance)) + t.Logf("acquired own controller %s answer=%q", controller, answer) + var device string + for end := time.Now().Add(20 * time.Second); time.Now().Before(end); time.Sleep(50 * time.Millisecond) { + blocks, _ := filepath.Glob("/sys/block/nvme*n*") + for _, block := range blocks { + got, _ := os.ReadFile(filepath.Join(block, "device", "subsysnqn")) + if strings.TrimSpace(string(got)) == nqn { + candidate := "/dev/" + filepath.Base(block) + info, statErr := os.Stat(candidate) + if os.IsNotExist(statErr) { + continue + } // hidden multipath component + if statErr != nil { + t.Fatalf("stat own namespace %s: %v", candidate, statErr) + } + if info.Mode()&os.ModeDevice == 0 || info.Mode()&os.ModeCharDevice != 0 { + t.Fatalf("own namespace %s is not a block device: %s", candidate, info.Mode()) + } + device = candidate + break + } + } + if device != "" { + break + } + } + if device == "" { + t.Fatalf("no own namespace for %s", nqn) + } + payload := bytes.Repeat([]byte{0x6d}, 4096) + source := filepath.Join(root, "payload") + if err := os.WriteFile(source, payload, 0600); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + started := time.Now() + out, err := exec.CommandContext(ctx, "dd", "if="+source, "of="+device, "bs=4096", "count=1", "oflag=direct", "conv=nocreat,fdatasync", "status=none").CombinedOutput() + elapsed := time.Since(started) + t.Logf("kernel default retries=5 device=%s write_elapsed=%s err=%v output=%s", device, elapsed, err, out) + if err != nil { + t.Fatalf("kernel write failed inside 2s Busy window: %v %s", err, out) + } + if elapsed < 1900*time.Millisecond { + t.Fatalf("2s hold was not exercised: elapsed=%s", elapsed) + } + if _, err := os.Stat(receipt); err != nil { + t.Fatalf("missing controlled Busy witness: %v", err) + } + got, err := exec.CommandContext(ctx, "dd", "if="+device, "bs=4096", "count=1", "iflag=direct", "status=none").Output() + if err != nil || !bytes.Equal(got, payload) { + t.Fatalf("kernel readback err=%v bytes=%d equal=%t", err, len(got), bytes.Equal(got, payload)) + } +} diff --git a/seaweed-block/cmd/blockvolume/procedure_store_down_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_store_down_integration_test.go new file mode 100644 index 0000000000..0f7a352eb5 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_store_down_integration_test.go @@ -0,0 +1,382 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "context" + "errors" + "fmt" + "io/fs" + "os" + "path" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// The SeaweedFS side down during a cut, then back, +// with real binaries: image B is written and a cut starts; once +// its uploads have begun, the filer (or the volume server) is killed. For a +// minute the guest keeps writing and flushing over NVMe/TCP while the test +// records how the cut answers and how much copy-on-write side data the +// stalled cut keeps on the local root. Then the store comes back. +// +// The store goes down inside the cut by construction: a filer front holds +// the reply to the cut's first applied chunk-object create, the store is +// stopped while that reply is held, then the reply is released. The cut +// cannot commit while one of its uploads is unanswered. With +// E1_TEST_SKIP_BOUNDARY=1 the front holds nothing and the test fails as +// inconclusive (the control). +// +// Asserted, in every variant: the store goes down mid-cut (uploads begun, +// HEAD unmoved); the guest keeps writing with no error and every command +// answers within storeDownBound; the cut the outage hit fails; after the +// store returns a later cut moves HEAD and verifies at depth data; no COW +// side file is left; a snapshot restored into a new volume is the last +// flushed image (each pass writes new bytes). Recorded for the operator +// guide: the slowest answer, when and how the stalled cut answered, the peak +// COW side bytes. +// +// Runs 4 variants of about 2-3 minutes: go test -timeout 30m. +const storeDownBound = 20 * time.Second + +func TestProcedureStoreDownDuringACut(t *testing.T) { + for _, down := range []string{"filer", "volume"} { + t.Run(down, func(t *testing.T) { storeDownDuringACut(t, down, 0, false) }) + } + // 4 MiB: the reserve's half holds no 4 MiB chunk, so stage() uploads the + // whole dirty set before the cut point and opens no copy-on-write window; + // with the store down that upload fails. No local space, guest undisturbed. + t.Run("volume-cow-reserve-exceeded", func(t *testing.T) { storeDownDuringACut(t, "volume", 4<<20, false) }) + // 400 MiB: the 48 captured 4 MiB chunks fit in half of it, so the cut + // opens its copy-on-write window; asserted to stay within reserve/2 and + // to close when the cut fails. + t.Run("volume-cow-window-400MiB", func(t *testing.T) { storeDownDuringACut(t, "volume", 400<<20, true) }) +} + +func storeDownDuringACut(t *testing.T, down string, cowBytes int64, cowWindow bool) { + if testListenHost() != "127.0.0.1" { + t.Fatal("the causal filer front requires loopback") + } + var boundary *snapshotFilerBoundary + cluster := startWorkspaceWeedWith(t, t.TempDir(), w4WeedOpts{VolumeSizeLimitMB: 256, VolumeMax: 32, + FilerBind: "127.0.0.2", FilerFront: func(c *w4WeedCluster) { boundary = newSnapshotFilerBoundary(t, c) }}) + env := startHandoffEnvOnCluster(t, 1, []string{"v2"}, procedureTLSConfig(), false, cluster) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + if cowBytes > 0 { + // Not under a temporary directory: the host-limit launch check refuses one. + home, err := os.UserHomeDir() + if err != nil { + t.Fatal(err) + } + dir, err := os.MkdirTemp(home, ".swblock-test-host-limit-") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + env.volExtra = append(env.volExtra, "--host-limit-dir", dir, "--host-limit-cow-bytes", fmt.Sprint(cowBytes)) + } + holder := env.start(t, "blockvolume-v1", "s1") + env.adopt(t, holder, "s1") + id, err := layout.ParseVolumeID(env.layoutID("v1")) + if err != nil { + t.Fatal(err) + } + boundary.id = id + boundary.dir = path.Join(env.chunkPath, layout.VolumeDir("v1", id)) + cut := []string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status} + verify := []string{"ops", "chunk", "verify", "--master", env.h.masterAddr, "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data", "--timeout", "5m"} + headGen := func() uint64 { + out, _ := env.h.command(t, env.chunkShow()...) + hd, err := parseLayoutHead(out) + if err != nil { + t.Fatal(err) + } + return hd.Gen + } + // headImage is HEAD's committed image (its current root and position). + // A cut's session begin also writes HEAD (a new generation) before its + // first upload, so the generation alone does not tell a commit apart. + headImage := func() string { + out, _ := env.h.command(t, env.chunkShow()...) + hd, err := parseLayoutHead(out) + if err != nil { + t.Fatal(err) + } + return fmt.Sprintf("%s@%d", hd.Current, hd.Position) + } + // sideBytes sums the copy-on-write side files anywhere under the host's + // root: a store lives in its volume's own directory (-), and + // its side file is created next to it. + // A census it cannot complete fails the test: only a file removed while + // it is walked (the window closing) is skipped. + sideBytes := func() int64 { + var n int64 + err := filepath.WalkDir(env.hosts["s1"].root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + return nil + } + return err + } + if d.IsDir() || !strings.Contains(d.Name(), ".cut-cow-") { + return nil + } + st, err := os.Stat(p) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return err + } + n += st.Size() + return nil + }) + if err != nil { + t.Fatalf("copy-on-write side-file census: %v", err) + } + return n + } + + env.writeCutCrashImage(t, 'A') + env.h.command(t, cut...) + env.writeCutCrashImage(t, 'B') + want := map[uint64][]byte{} + for ch := 0; ch < cutCrashChunks; ch++ { + for i := 0; i < cutCrashPer; i++ { + lba := uint64(ch*ladderChunkBlocks + i) + want[lba] = cutCrashBlock('B', lba) + } + } + + // A cut starts; the store goes down while the reply to its first applied + // chunk-object create is held, so before the cut can commit. + image := headImage() + reached := boundary.arm("OBJECT", "") + type cutAnswer struct { + rc int + out string + at time.Duration + } + answered := make(chan cutAnswer, 1) + cutStart := time.Now() + cutCtx, cutCancel := context.WithTimeout(context.Background(), 8*time.Minute) + cutDone := make(chan struct{}) + // Off the test goroutine: runCLI never fails the test, and cleanup waits + // for it so nothing outlives the test. + go func() { + defer close(cutDone) + out, errOut, rc, err := runCLI(cutCtx, env.h, cut...) + if err != nil { + rc, errOut = -1, errOut+err.Error() + } + answered <- cutAnswer{rc, out + errOut, time.Since(cutStart)} + }() + t.Cleanup(func() { boundary.unblock(); cutCancel(); <-cutDone }) + select { + case <-reached: + case <-time.After(30 * time.Second): + t.Fatalf("%s: inconclusive: the cut applied no chunk-object create within 30s, so the store would not go down mid-cut", down) + } + if got := headImage(); got != image { + t.Fatalf("%s: the cut committed (HEAD image %s -> %s) while one of its uploads was unanswered", down, image, got) + } + if d := os.Getenv("E1_TEST_DELAY_KILL"); d != "" { + // Control: a kill delayed past the upload's own timeout, so the cut + // gives up while the store is healthy; the check below must call + // the run inconclusive. + if wait, err := time.ParseDuration(d); err == nil { + time.Sleep(wait) + } + } + env.cluster.stopProc(t, down) + // The outage is inside the cut only if the held upload was still + // waiting when the store went down: a held call whose caller gave up + // (the upload's 30 s context) means the cut failed with the store + // healthy. + if held, why := boundary.stillHeld(); !held { + t.Fatalf("%s: inconclusive: the held upload was not waiting when the store went down (%s)", down, why) + } + boundary.unblock() + downAt := time.Now() + t.Logf("%s killed %s after the cut started", down, downAt.Sub(cutStart).Round(time.Millisecond)) + + // A minute of guest writes and flushes while the store is down. + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + var pending []uint64 + var errs int + var slowest time.Duration + var cutWhileDown *cutAnswer + peakSide := sideBytes() + op := func(f func() error) error { + start := time.Now() + _ = c.io.SetDeadline(start.Add(storeDownBound)) + err := f() + if d := time.Since(start); d > slowest { + slowest = d + } + var ne interface{ Timeout() bool } + if errors.As(err, &ne) && ne.Timeout() { + t.Fatalf("%s down: a guest command did not answer within %s: %v", down, storeDownBound, err) + } + return err + } + written := 0 + pendingBytes := map[uint64][]byte{} + for n := 0; time.Since(downAt) < time.Minute; n++ { + ch, i := (n/cutCrashPer)%cutCrashChunks, n%cutCrashPer + lba := uint64(ch*ladderChunkBlocks + i) + // Each pass over the image writes new bytes ('C', 'D', ...), so a lost + // tail of rewrites is visible at the read-back. + b := cutCrashBlock(byte('C'+n/(cutCrashChunks*cutCrashPer)), lba) + if err := op(func() error { return c.tryWrite(lba, b) }); err != nil { + errs++ + continue + } + written++ + pending = append(pending, lba) + pendingBytes[lba] = b + if len(pending) == 8 { + if err := op(c.tryFlush); err != nil { + errs++ + } else { + for _, l := range pending { + want[l] = pendingBytes[l] + } + } + pending = pending[:0] + clear(pendingBytes) + } + if s := sideBytes(); s > peakSide { + peakSide = s + } + if cutWhileDown == nil { + select { + case a := <-answered: + cutWhileDown = &a + default: + } + } + time.Sleep(10 * time.Millisecond) + } + // The last partial batch is flushed too, so every write is acknowledged + // and the read-back can name each block's bytes. + if len(pending) > 0 { + if err := op(c.tryFlush); err != nil { + errs++ + } else { + for _, l := range pending { + want[l] = pendingBytes[l] + } + } + } + c.close() + t.Logf("%s down 60s (COW reserve %d): guest writes %d, errors %d, slowest answer %s, frontend ready %v, peak COW side bytes %d", + down, cowBytes, written, errs, slowest.Round(time.Millisecond), env.frontendReadyAt("s1"), peakSide) + // Guest I/O is not delayed by the outage, in every variant. + if written == 0 || errs != 0 || slowest >= storeDownBound { + t.Fatalf("%s down: the guest was disturbed: %d writes, %d errors, slowest answer %s", down, written, errs, slowest) + } + if cutWhileDown != nil { + t.Logf("%s down: the cut answered while it was down, after %s, exit %d: %s", down, cutWhileDown.at.Round(time.Millisecond), cutWhileDown.rc, firstLine(cutWhileDown.out)) + } else { + t.Logf("%s down: the cut had not answered after %s", down, time.Since(cutStart).Round(time.Second)) + } + if cowBytes > 0 && !cowWindow { + // A dirty set larger than half the reserve is staged before the cut + // point: the cut fails in its upload, with no copy-on-write window + // and no local space. + if peakSide != 0 || (cutWhileDown != nil && strings.Contains(cutWhileDown.out, "capture copy")) { + t.Fatalf("%s down: a staged cut used local copy-on-write space (peak %d) or opened a window: %+v", down, peakSide, cutWhileDown) + } + } + if cowWindow { + // The reserve bounds the copy-on-write window: stage() opens it only + // when the captured chunks fit in half the reserve. + switch { + case cutWhileDown == nil || !strings.Contains(cutWhileDown.out, "capture copy"): + t.Fatalf("%s down: the cut did not fail inside a copy-on-write window (no 'capture copy'): %+v", down, cutWhileDown) + case peakSide == 0 || peakSide > cowBytes/2: + t.Fatalf("%s down: peak COW side bytes %d, want > 0 and <= half the %d reserve", down, peakSide, cowBytes) + case sideBytes() != 0: + t.Fatalf("%s down: %d COW side bytes left after the cut failed: the window did not close", down, sideBytes()) + case written == 0: + t.Fatalf("%s down: the guest wrote nothing while the window was open", down) + } + t.Logf("%s down: COW window measured: peak %d <= reserve/2 %d, closed on the failure", down, peakSide, cowBytes/2) + } + + // The store comes back. + env.cluster.restartProc(t, down) + backAt := time.Now() + // The store is back when HEAD reads through it again: the filer front + // accepts at once, while the real filer behind it may still be starting. + readable := func(end time.Time) bool { // one read, bounded by the whole wait's deadline + ctx, cancel := context.WithDeadline(context.Background(), end) + defer cancel() + _, _, rc, err := runCLI(ctx, env.h, env.chunkShow()...) + return err == nil && rc == 0 + } + for end := time.Now().Add(time.Minute); !readable(end); time.Sleep(time.Second) { + if time.Now().After(end) { + t.Fatalf("%s back: HEAD not readable within 1m of the restart", down) + } + } + stalled := cutWhileDown + if stalled == nil { + select { + case a := <-answered: + stalled = &a + t.Logf("%s back: the stalled cut answered %s after the restart, exit %d: %s", down, time.Since(backAt).Round(time.Millisecond), a.rc, firstLine(a.out)) + case <-time.After(5 * time.Minute): + t.Fatalf("%s back: the cut started before the outage never answered", down) + } + } + // The cut the outage hit must have failed; HEAD is read again after its + // answer, so only a later cut can satisfy the check below. + if stalled.rc == 0 { + t.Fatalf("%s: the cut the outage hit reported success: %s", down, firstLine(stalled.out)) + } + gen := headGen() + var g uint64 + for end := time.Now().Add(2 * time.Minute); ; time.Sleep(2 * time.Second) { + _, _, rc := env.h.run(t, cut...) + if g = headGen(); rc == 0 && g > gen { + break + } + if time.Now().After(end) { + t.Fatalf("%s back: no cut committed within 2m (HEAD gen %d, was %d)", down, g, gen) + } + } + t.Logf("%s back: a cut committed %s after the restart (HEAD gen %d -> %d)", down, time.Since(backAt).Round(time.Millisecond), gen, g) + if out, errOut, rc := env.h.run(t, verify...); rc != 0 { + t.Fatalf("%s back: HEAD does not verify (exit %d):\n%s\n%s", down, rc, out, errOut) + } + if s := sideBytes(); s != 0 { + t.Fatalf("%s back: %d COW side bytes left on the local root after a committed cut", down, s) + } + env.snapshot(t, "s1", "v1", "after-"+down+"-down") + env.restoreInto(t, "v1", "after-"+down+"-down", "v2") + for _, host := range []string{"s1", "n-v2"} { + c := dialNVMe(t, env.hosts[host].nvme, plannedHandoffNQN) + for lba, w := range want { + if got := c.read(t, lba, 4096); !bytes.Equal(got, w) { + c.close() + t.Fatalf("%s back: %s LBA %d is not the last flushed write", down, host, lba) + } + } + c.close() + } + fmt.Printf("STORE_DOWN_OK %s\n", down) +} + +func firstLine(s string) string { + if i := bytes.IndexByte([]byte(s), '\n'); i >= 0 { + return s[:i] + } + return s +} diff --git a/seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go b/seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go new file mode 100644 index 0000000000..65c6563ca4 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_tls_harness_test.go @@ -0,0 +1,137 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +// procedureTLS is the procedure harness's mutual-TLS setup: one CA, the +// master's certificate, one node certificate per server id (CN = server id), +// an admin and an operator certificate, and the role file. With it the +// harness runs blockmaster with --tls-*/--role-file, every blockvolume with +// --master-tls-*, and every sw-block command with SW_BLOCK_TLS_* (admin). +type procedureTLS struct { + dir string + ca *authtest.CA + roles string + notAfter map[string]time.Time // per certificate name, when set +} + +// procedureTLSOn reports whether the procedure gate runs on the TLS binaries +// (T14): SW_BLOCK_PROCEDURE_TLS=1. +func procedureTLSOn() bool { return os.Getenv("SW_BLOCK_PROCEDURE_TLS") == "1" } + +func (p *procedureTLS) path(name, ext string) string { return filepath.Join(p.dir, name+ext) } + +// issue writes name.crt/name.key for CN cn and adds its role-file line. +func (p *procedureTLS) issue(t *testing.T, name, cn, role string, notAfter time.Time) { + t.Helper() + leaf := p.ca.Issue(t, cn, notAfter) + leaf.WriteFiles(t, p.dir, name) + if role != "" { + p.addRole(t, leaf.Fingerprint, role, cn) + } +} + +func (p *procedureTLS) addRole(t *testing.T, fingerprint, role, id string) { + t.Helper() + f, err := os.OpenFile(p.roles, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600) + if err != nil { + t.Fatal(err) + } + defer f.Close() + if _, err := fmt.Fprintln(f, fingerprint, role, id); err != nil { + t.Fatal(err) + } +} + +// removeRole drops id's line from the role file (a revocation before SIGHUP +// or a restart). +func (p *procedureTLS) removeRole(t *testing.T, id string) { + t.Helper() + raw, err := os.ReadFile(p.roles) + if err != nil { + t.Fatal(err) + } + var keep []string + for _, l := range strings.Split(strings.TrimRight(string(raw), "\n"), "\n") { + if f := strings.Fields(l); len(f) == 3 && f[2] == id { + continue + } + keep = append(keep, l) + } + if err := os.WriteFile(p.roles, []byte(strings.Join(keep, "\n")+"\n"), 0o600); err != nil { + t.Fatal(err) + } +} + +// newProcedureTLS issues the master, admin and operator certificates and one +// node certificate per server id (notAfter overrides a node's expiry). +func newProcedureTLS(t *testing.T, dir string, servers []string, notAfter map[string]time.Time) *procedureTLS { + t.Helper() + p := &procedureTLS{dir: filepath.Join(dir, "tls"), notAfter: notAfter} + if err := os.MkdirAll(p.dir, 0o700); err != nil { + t.Fatal(err) + } + p.roles = p.path("roles", "") + p.ca = authtest.NewCA(t, "procedure CA") + p.ca.WriteCA(t, p.dir) + day := time.Now().Add(24 * time.Hour) + p.issue(t, "master", "blockmaster", "", day) + p.issue(t, "admin", "procedure-admin", "admin", day) + p.issue(t, "operator", "procedure-operator", "operator", day) + seen := map[string]bool{} + for _, s := range servers { + if seen[s] { + continue + } + seen[s] = true + exp := day + if at, ok := notAfter[s]; ok { + exp = at + } + p.issue(t, s, s, "node", exp) + } + return p +} + +func (p *procedureTLS) masterArgs() []string { + return []string{"--tls-cert", p.path("master", ".crt"), "--tls-key", p.path("master", ".key"), + "--tls-client-ca", p.path("ca", ".crt"), "--role-file", p.roles, "--audit-log", p.path("audit", ".log")} +} + +// volumeArgs is the node identity of server for blockvolume. +func (p *procedureTLS) volumeArgs(server string) []string { + return []string{"--master-tls-cert", p.path(server, ".crt"), "--master-tls-key", p.path(server, ".key"), "--master-ca", p.path("ca", ".crt")} +} + +// cliEnv is the identity name (admin, operator, a server id) for sw-block. +func (p *procedureTLS) cliEnv(name string) []string { + return []string{"SW_BLOCK_TLS_CERT=" + p.path(name, ".crt"), "SW_BLOCK_TLS_KEY=" + p.path(name, ".key"), "SW_BLOCK_TLS_CA=" + p.path("ca", ".crt")} +} + +// masterDialOption is the transport for a test's own gRPC client of the env's +// master, acting as name (admin, operator or a server id) with mutual TLS, +// plaintext otherwise. +func (env *handoffEnv) masterDialOption(t *testing.T, name string) grpc.DialOption { + t.Helper() + if env.tls == nil { + return grpc.WithTransportCredentials(insecure.NewCredentials()) + } + d, err := link.ClientCredentials(link.TLSFiles{Cert: env.tls.path(name, ".crt"), Key: env.tls.path(name, ".key"), CA: env.tls.path("ca", ".crt")}, "") + if err != nil { + t.Fatal(err) + } + return d +} diff --git a/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go new file mode 100644 index 0000000000..e655ddb910 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_tls_integration_test.go @@ -0,0 +1,294 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "context" + "fmt" + "os" + "strings" + "syscall" + "testing" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// Phase 0 procedure tests on the TLS binaries (the gate's T6-T13). Each runs +// real blockmaster, blockvolume and sw-block processes with mutual TLS. + +func startTLSEnv(t *testing.T, n int, targets []string, notAfter map[string]time.Time) *handoffEnv { + t.Helper() + if notAfter == nil { + notAfter = map[string]time.Time{} + } + return startHandoffEnvTLS(t, n, targets, notAfter) +} + +func (env *handoffEnv) dialAs(t *testing.T, name string) *grpc.ClientConn { + t.Helper() + conn, err := grpc.NewClient(env.h.masterAddr, env.masterDialOption(t, name)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + return conn +} + +func wantCode(t *testing.T, what string, err error, want codes.Code) { + t.Helper() + if status.Code(err) != want { + t.Fatalf("%s: %v; want %s", what, err, want) + } +} + +// T8: a node certificate acting for another server's volume (s2's identity +// renewing, ACKing, heartbeating and subscribing as s1) is refused at each +// call, and s1's lease and service are unaffected. +func TestProcedureTLSWrongNodeCertificateIsRefused(t *testing.T) { + env := startTLSEnv(t, 2, nil, nil) + d := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, d, "s1") + block := pattern("wrong-node-cert!") + env.writeBlock(t, "s1", 0, block) + + conn := env.dialAs(t, "s2") + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + id := &control.WorkspaceIdentity{VolumeId: "v1", ReplicaId: "r1", Epoch: e, ServerId: "s1"} + ws := control.NewWorkspaceServiceClient(conn) + _, err := ws.RenewWorkspaceLease(ctx, id) + wantCode(t, "s2's certificate renewing s1's lease", err, codes.PermissionDenied) + _, err = ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 1}) + wantCode(t, "s2's certificate ACKing for s1", err, codes.PermissionDenied) + _, err = control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ReadsLevel: 1, ServerId: "s1"}) + wantCode(t, "s2's certificate heartbeating as s1", err, codes.PermissionDenied) + stream, err := control.NewAssignmentServiceClient(conn).SubscribeAssignments(ctx, &control.SubscribeRequest{VolumeId: "v1", ReplicaId: "r1", ServerId: "s1"}) + if err == nil { + _, err = stream.Recv() + } + wantCode(t, "s2's certificate subscribing as s1", err, codes.PermissionDenied) + + // s1 keeps its lease past one TTL and still serves the block. + time.Sleep(35 * time.Second) + if d.has("workspace lease: fenced") || !env.frontendReadyAt("s1") { + t.Fatal("s1 lost its lease or its frontend after the refused calls") + } + if !bytes.Equal(env.readBlock(t, "s1", 0), block) { + t.Fatal("s1 no longer reads its block") + } +} + +// T11: a role file corrupted and reloaded (SIGHUP) under load keeps the +// previous table: no fence, no change. +func TestProcedureTLSCorruptRoleFileAtReloadChangesNothing(t *testing.T) { + env := startTLSEnv(t, 1, nil, nil) + d := env.start(t, "blockvolume-s1", "s1") + env.adopt(t, d, "s1") + good, err := os.ReadFile(env.tls.roles) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(env.tls.roles, []byte("sha256:not-a-fingerprint node s1\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := env.masterProcess.proc.Signal(syscall.SIGHUP); err != nil { + t.Fatal(err) + } + env.masterProcess.waitLog(t, 10*time.Second, "NOT reloaded, the previous table stays") + deadline := time.Now().Add(40 * time.Second) // more than one lease TTL under writes + for i := uint64(0); time.Now().Before(deadline); i++ { + b := bytes.Repeat([]byte{byte(i)}, 4096) + env.writeBlock(t, "s1", i%64, b) + if !bytes.Equal(env.readBlock(t, "s1", i%64), b) { + t.Fatalf("write %d did not read back after the corrupt reload", i) + } + time.Sleep(500 * time.Millisecond) + } + if d.has("workspace lease: fenced") || !env.frontendReadyAt("s1") { + t.Fatal("the holder fenced after a corrupt role file was refused") + } + if err := os.WriteFile(env.tls.roles, good, 0o600); err != nil { + t.Fatal(err) + } +} + +// T12: blockmaster restarted with one holder removed from the role file: +// that holder fences (its renewals are refused until its lease ends); the +// other holder keeps serving. +func TestProcedureTLSMasterRestartWithAHolderRemoved(t *testing.T) { + env := startTLSEnv(t, 1, []string{"v2"}, nil) + d1 := env.start(t, "blockvolume-s1", "s1") + env.adopt(t, d1, "s1") + d2 := env.h.start(t, "blockvolume-n-v2", env.h.volume, env.volArgsFor(env.hosts["n-v2"])...) + d2.waitLog(t, 60*time.Second, "blockvolume: volume v2 adopted as PRIMARY at r1@") + + env.tls.removeRole(t, "s1") + env.masterProcess.kill(t) + env.masterProcess = env.h.start(t, "blockmaster-restarted", env.h.master, env.masterArgs...) + env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + + // s1 cannot renew any more: it fences within its lease and exits. + if err := d1.wait(90 * time.Second); err == nil { + t.Fatal("s1 exited 0; want the fence exit") + } + if !d1.has("workspace lease: fenced volume=v1") { + t.Fatalf("s1 exited without a lease fence line (log %s)", d1.log) + } + // n-v2 keeps renewing and serving. + time.Sleep(5 * time.Second) + select { + case <-d2.done: + t.Fatalf("n-v2 exited although its line is still in the role file: %v", d2.err) + default: + } + if d2.has("workspace lease: fenced") { + t.Fatal("n-v2 fenced although its line is still in the role file") + } +} + +// T13: sw-block without a client certificate against the TLS master is +// refused at the handshake; it exits "not authorized" (5) and names the cure. +// (A forced move by an operator is refused at the master: T7 and +// TestForcedMoveNeedsAnAdmin.) +func TestProcedureTLSPlaintextClientIsRefusedWithTheCure(t *testing.T) { + env := startTLSEnv(t, 1, nil, nil) + admin := env.h.cliEnv + env.h.cliEnv = []string{"SW_BLOCK_TLS_CERT=", "SW_BLOCK_TLS_KEY=", "SW_BLOCK_TLS_CA="} + _, stderr, code := env.h.run(t, env.show...) + if code != 5 || !strings.Contains(stderr, "SW_BLOCK_TLS_CERT") || !strings.Contains(stderr, "mutual TLS") { + t.Fatalf("plaintext sw-block against the TLS master: exit %d, stderr %q; want 5 naming SW_BLOCK_TLS_CERT and mutual TLS", code, stderr) + } + env.h.cliEnv = admin + if _, _, code := env.h.run(t, env.show...); code != 0 { + t.Fatalf("admin show: exit %d", code) + } +} + +// fencedHolderThenForcedMove is T6/T7's flow: s1 serves and publishes block 0 +// (seal), then lose() takes its certificate away. s1 fences and exits; when +// operatorFirst, an operator's forced move is refused as not authorized; the +// admin's forced move is admitted at the sealed LSN with its lost range +// recorded, and s2 serves block 0. +func fencedHolderThenForcedMove(t *testing.T, env *handoffEnv, lose func(), operatorFirst bool) { + t.Helper() + _, mustU := fatalOn(t) + d := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, d, "s1") + kept := pattern("published-block!") + env.writeBlock(t, "s1", 0, kept) + g := env.seal(t, "s1", e) + l := env.sealedLSN(t, e, g) + + lose() + if err := d.wait(150 * time.Second); err == nil { + t.Fatal("s1 exited 0 after losing its certificate; want the fence exit") + } + if !d.has("workspace lease: fenced volume=v1") { + t.Fatalf("s1 exited without a lease fence line (log %s)", d.log) + } + + if operatorFirst { + admin := env.h.cliEnv + env.h.cliEnv = env.tls.cliEnv("operator") + b := env.hosts["s2"] + args := []string{"ops", "workspace", "force-move", "--master", env.h.masterAddr, "--volume", "v1", + "--target-host", b.id, "--target-data", b.data, "--target-ctrl", b.ctrl, + "--request-id", "force-by-operator", "--confirm-forced", fmt.Sprintf("v1@%d", e)} + poll(t, 120*time.Second, "the forced move preview never admitted (operator)", func() bool { + out, _, _ := env.h.run(t, append(args, "--dry-run")...) + return previewAdmitted(out) + }) + _, stderr, code := env.h.run(t, args...) + if code != 5 || !strings.Contains(stderr, "admin") { + t.Fatalf("operator forced move: exit %d, stderr %q; want 5 (not authorized) naming admin", code, stderr) + } + env.h.cliEnv = admin + } + + out := env.forceMove(t, e, "s2", "force-v1-tls") + e2 := mustU(forcedEpoch(out, e, "s1", "s2")) + if got := mustU(forcedKeptLSN(out)); got != l { + t.Fatalf("the forced move kept LSN %d; want the sealed HEAD's %d", got, l) + } + ranges, _ := env.h.command(t, "ops", "workspace", "lost-range", "--master", env.h.masterAddr, "--volume", "v1") + if !strings.Contains(ranges, "range 1 of 1: request force-v1-tls, r1@") { + t.Fatalf("lost-range does not show the forced move:\n%s", ranges) + } + nw := env.start(t, "blockvolume-s2", "s2") + if got := env.adopt(t, nw, "s2"); got != e2 { + t.Fatalf("s2 adopted at epoch %d; want %d", got, e2) + } + if !bytes.Equal(env.readBlock(t, "s2", 0), kept) { + t.Fatal("the published block does not read back on s2") + } + // Control: a block never written reads zero. + if !bytes.Equal(env.readBlock(t, "s2", 8), make([]byte, 4096)) { + t.Fatal("a block never written does not read zero on s2") + } +} + +// T6: the holder's certificate expires on the master clock while it serves +// (NotAfter set close in the test CA; no clock is stepped). +func TestProcedureTLSExpiredHolderCertificate(t *testing.T) { + env := startTLSEnv(t, 2, nil, map[string]time.Time{"s1": time.Now().Add(75 * time.Second)}) + fencedHolderThenForcedMove(t, env, func() {}, false) // the expiry comes by itself +} + +// T7: the holder's line is removed from the role file and blockmaster +// reloads it (SIGHUP) while the holder serves. +func TestProcedureTLSRevokedHolderCertificate(t *testing.T) { + env := startTLSEnv(t, 2, nil, nil) + fencedHolderThenForcedMove(t, env, func() { + env.tls.removeRole(t, "s1") + if err := env.masterProcess.proc.Signal(syscall.SIGHUP); err != nil { + t.Fatal(err) + } + env.masterProcess.waitLog(t, 10*time.Second, "tls/roles reloaded") + }, true) +} + +// T9: the daily reconnect, with the connection age set to 10 s: the holder's +// lease keeps renewing through 20 forced reconnects (fresh handshakes), it +// never fences, it keeps serving writes, and its assignment stream resumes +// after each reconnect. +func TestProcedureTLSLeasesSurviveForcedReconnects(t *testing.T) { + env := startHandoffEnvTLS(t, 1, nil, map[string]time.Time{}, "--tls-connection-age-test-only", "10s") + d := env.start(t, "blockvolume-s1", "s1") + env.adopt(t, d, "s1") + deadline := time.Now().Add(6 * time.Minute) + for i := uint64(0); time.Now().Before(deadline); i++ { + if strings.Count(tlsReadLog(t, d.log), "blockvolume: subscribe stream:") >= 20 { + break + } + b := bytes.Repeat([]byte{byte(i)}, 4096) + env.writeBlock(t, "s1", i%64, b) + if !bytes.Equal(env.readBlock(t, "s1", i%64), b) { + t.Fatalf("write %d did not read back across the reconnects", i) + } + time.Sleep(2 * time.Second) + } + log := tlsReadLog(t, d.log) + if n := strings.Count(log, "blockvolume: subscribe stream:"); n < 20 { + t.Fatalf("%d stream reconnects in 6 minutes; want 20", n) + } + if n := strings.Count(log, "blockvolume: assignment stream delivery"); n < 20 { + t.Fatalf("the assignment stream delivered %d times; want it to resume after each of 20 reconnects", n) + } + if d.has("workspace lease: fenced") || !env.frontendReadyAt("s1") { + t.Fatal("the holder fenced or stopped serving across the forced reconnects") + } +} + +func tlsReadLog(t *testing.T, path string) string { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(b) +} diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go new file mode 100644 index 0000000000..410264bafc --- /dev/null +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -0,0 +1,302 @@ +package main + +import ( + "context" + "errors" + "fmt" + "os" + "os/signal" + "sync" + "syscall" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const ( + exitWorkspaceRetry = 75 + exitWorkspaceSuperseded = 78 + exitWorkspaceRevoked = 79 + // Post-drain ACK wait; M2 Revoking -> Revoked, Part D. It covers the + // guard's stop reply (the resource owner has drained by then) and its + // ACK attempts, which the guard repeats until the lease deadline when an + // answer is lost. The units kill the process TimeoutStopSec=30s after + // the stop (deploy/systemd). Before this wait the drain is bounded by + // WorkspaceDrainTimeout (5 s); after it, superviseProcess waits at most + // WorkspaceDrainTimeout (5 s) for the exit. 30 s - 5 s - 5 s = 20 s, + // less 1 s margin = 19 s. The guard's attempts end at the lease deadline + // (about 20 s after the last renewal); attempts still running here end + // as an unconfirmed ACK (exit 75), as before. + workspaceLeaseCloseoutTimeout = 19 * time.Second +) + +type workspaceExit struct { + code int + reason string + // detail is the operator's cure, printed on the final exit line. + detail string +} + +// INV-WS-STARTUP-RETRY-001: the first outcome is immutable. The channel is a +// single latched wakeup, not a queue of competing shutdown events. +type processExit struct { + parent context.Context + once sync.Once + done chan struct{} + decision chan workspaceExit + startupMu sync.Mutex + startupCtx context.Context + startupCancel context.CancelFunc +} + +func newProcessExit(ctx context.Context) *processExit { + startupCtx, cancel := context.WithCancel(ctx) + return &processExit{parent: ctx, done: make(chan struct{}), decision: make(chan workspaceExit, 1), startupCtx: startupCtx, startupCancel: cancel} +} + +// INV-WS-STARTUP-RETRY-001: once the resource owner takes shutdown, startup +// outcomes cannot arbitrate it. ACK success is still selected only after ACK. +func (e *processExit) stopChunkStartup() { + e.startupMu.Lock() + defer e.startupMu.Unlock() + e.startupCancel() +} +func (e *processExit) chooseChunkStartup(out workspaceExit) { + e.startupMu.Lock() + defer e.startupMu.Unlock() + if e.startupCtx.Err() == nil { + e.choose(out) + } +} + +func (e *processExit) choose(out workspaceExit) { + e.once.Do(func() { + if e.parent.Err() != nil { + out = workspaceExit{reason: "signal"} + } + e.decision <- out // exactly one send fits the buffer without blocking under a provider lock + close(e.done) + }) +} + +// The original resource owner still drains everything. This outer process +// owner bounds even a stuck Close or deferred cleanup; main alone calls Exit. +func run(f flags) int { + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + return superviseProcess(ctx, func(e *processExit) int { return runVolume(f, e) }) +} + +// INV-WS-STARTUP-RETRY-001: M2 process exit owns the cleanup bound. +func superviseProcess(ctx context.Context, work func(*processExit) int) int { + e := newProcessExit(ctx) + finished := make(chan int, 1) + go func() { finished <- work(e) }() + var out workspaceExit + select { + case code := <-finished: + select { + case out = <-e.decision: + return reportWorkspaceExit(out) + default: + return code + } + case <-ctx.Done(): + e.choose(workspaceExit{reason: "signal"}) + out = <-e.decision + case out = <-e.decision: + } + if out.code == 0 { + <-finished + return 0 + } + timer := time.NewTimer(volume.WorkspaceDrainTimeout) + defer timer.Stop() + return finishWorkspaceExit(out, finished, timer.C) +} + +func finishWorkspaceExit(out workspaceExit, finished <-chan int, deadline <-chan time.Time) int { + select { + case <-finished: + case <-deadline: + } + return reportWorkspaceExit(out) +} + +func reportWorkspaceExit(out workspaceExit) int { + if out.code != 0 { + if out.detail != "" { + fmt.Fprintf(os.Stderr, "blockvolume: exiting status=%d reason=%s cure=%q\n", out.code, out.reason, out.detail) + } else { + fmt.Fprintf(os.Stderr, "blockvolume: exiting status=%d reason=%s\n", out.code, out.reason) + } + } + return out.code +} + +// INV-WS-STARTUP-RETRY-001: one decision combines a newer other-replica +// authority fact and the provider's generation-bound foreign-HEAD proof. +// durableOpenFatalExit is the exit of a fatal durable storage open: 78 with +// reason store_format_newer for a store written by a newer format (no +// restart can open it), else 1 as before. +func durableOpenFatalExit(err error) (int, string) { + if errors.Is(err, storage.ErrStoreFormatNewer) { + return exitWorkspaceSuperseded, "store_format_newer" + } + return 1, "" +} + +func workspaceRetryOutcome(reason string, h *volume.Host, claimSuperseded bool) workspaceExit { + if claimSuperseded || h.IsCurrentReplicaSuperseded() { + return workspaceExit{code: exitWorkspaceSuperseded, reason: "superseded"} + } + return workspaceExit{code: exitWorkspaceRetry, reason: reason} +} + +// M2 startup outcome; INV-WS-STARTUP-RETRY-001. Workspace chunk primaries only. +func watchChunkStartup(ctx context.Context, e *processExit, f flags, h *volume.Host, p *durable.DurableProvider) { + if !f.workspaceLease || f.durableImpl != "walstore-chunk" { + return + } + for { + if chooseChunkStartupExit(e, f, h, p) { + return + } + + select { + case <-e.startupCtx.Done(): + return + case <-ctx.Done(): + return + case <-e.done: + return + case <-p.ChunkStartupUpdates(): + } + } +} + +// chunkRuntimeFenceProvider reports a runtime HEAD fence of the attached layer. +type chunkRuntimeFenceProvider interface { + ChunkRuntimeFenced(string) bool + ChunkRuntimeFenceUpdates() <-chan struct{} +} + +// watchChunkRuntimeFence: a HEAD fence after startup, while the lease may +// still be valid, ends the process with no restart (78 head_fenced): another +// holder owns HEAD (INV-FE-PRIMARY-READY-OPERATIONAL-001). Workspace chunk +// primaries only. +func watchChunkRuntimeFence(ctx context.Context, e *processExit, f flags, p chunkRuntimeFenceProvider) { + if !f.workspaceLease || f.durableImpl != "walstore-chunk" { + return + } + for { + if p.ChunkRuntimeFenced(f.volumeID) { + e.choose(workspaceExit{code: exitWorkspaceSuperseded, reason: "head_fenced"}) + return + } + select { + case <-ctx.Done(): + return + case <-e.done: + return + case <-p.ChunkRuntimeFenceUpdates(): + } + } +} + +// M2 process exit / Revoking -> Revoked; INV-WS-STARTUP-RETRY-001. +func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan workspaceStopRequest, done <-chan error) (*workspaceStopRequest, <-chan error) { + select { + case <-e.parent.Done(): + e.choose(workspaceExit{reason: "signal"}) + return nil, done + case <-e.done: + return nil, done + case request := <-requests: + fmt.Fprintln(os.Stderr, "blockvolume: stopping: the workspace lease guard fenced and requested the drain") + e.stopChunkStartup() + out := workspaceExit{reason: "revoked"} + if !h.WorkspaceLeaseRevoking() { + out = workspaceRetryOutcome("lease_expired", h, false) + } + if out.code != 0 { + e.choose(out) + } + return &request, done + case err := <-done: + e.stopChunkStartup() + fmt.Fprintln(os.Stderr, "blockvolume: workspace lease stopped:", err) + e.choose(workspaceRetryOutcome("lease_expired", h, false)) + return nil, nil + } +} + +// An ACKed revocation completes with status zero. A failure to confirm that +// ACK is retryable; a signal observed first still retains the signal status. +// M2 Revoking -> Revoked; INV-WS-REVOKE-ACK-001, INV-WS-STARTUP-RETRY-001. +func finishWorkspaceLease(e *processExit, f flags, h *volume.Host, done <-chan error) { + if done == nil { + return + } + select { + case err := <-done: + if err == nil { + e.choose(workspaceExit{reason: "revoked"}) + return + } + fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout:", err) + case <-time.After(workspaceLeaseCloseoutTimeout): + fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout deadline") + } + e.choose(workspaceExit{code: exitWorkspaceRetry, reason: "revoke_ack_unconfirmed"}) +} + +// The provider publishes only a generation-bound outcome and an atomic choice. +type chunkStartupOutcomeProvider interface { + ChunkStartupOutcome(string) (uint64, bool) + ChunkStartupSuperseded(string, uint64) bool + ChooseChunkStartupExit(string, uint64, func()) bool +} + +func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p chunkStartupOutcomeProvider) bool { + if !f.workspaceLease || f.durableImpl != "walstore-chunk" { + return false + } + gen, failed := p.ChunkStartupOutcome(f.volumeID) + if !failed { + return false + } + // INV-WS-STARTUP-RETRY-001: one exit decision consumes both proof + // sources; the provider rechecks the claim generation below. + out := workspaceRetryOutcome("assignment_timeout", h, p.ChunkStartupSuperseded(f.volumeID, gen)) + if identity, ok := p.(interface{ ChunkStartupIdentityRefused(string, uint64) bool }); ok && identity.ChunkStartupIdentityRefused(f.volumeID, gen) { + out = workspaceExit{code: exitWorkspaceSuperseded, reason: "layout_identity_mismatch", detail: "VOLUME/HEAD disagrees with --layout-id; retry with the layout id from the master's volume record"} + } + // A HEAD written by a newer version is permanent for this binary: exit 78, + // never the restartable 75 (a restart reads the same HEAD again). A master + // final reason below (moved, deleted, revoked) still names the exit. + if nv, ok := p.(interface{ ChunkStartupNewerVersion(string, uint64) bool }); ok && nv.ChunkStartupNewerVersion(f.volumeID, gen) { + out = workspaceExit{code: exitWorkspaceSuperseded, reason: "head_newer_version", detail: "HEAD was written by a newer version: run a newer binary"} + } + if h != nil { + // Typed MOVED/DELETED refusals exit 78 and a recorded revocation + // (FINAL) exits 79 at once; both are permanent, + // never a restart loop to the unit's start limit. It is the reason + // that ended the wait, so it names the exit even when a newer + // foreign line was also observed (superseded). + if _, final := h.MasterWaitState(); final != "" { + out = workspaceExit{code: exitWorkspaceSuperseded, reason: final, detail: h.MasterWaitDetail()} + if final == "revoked" { + out.code = exitWorkspaceRevoked + } + } + } + if c, ok := p.(interface{ ChunkStartupCure(string, uint64) string }); ok { + if cure := c.ChunkStartupCure(f.volumeID, gen); cure != "" { + out.detail = cure + } + } + return p.ChooseChunkStartupExit(f.volumeID, gen, func() { e.chooseChunkStartup(out) }) +} diff --git a/seaweed-block/cmd/blockvolume/process_exit_ack_retry_test.go b/seaweed-block/cmd/blockvolume/process_exit_ack_retry_test.go new file mode 100644 index 0000000000..ffec0c18ec --- /dev/null +++ b/seaweed-block/cmd/blockvolume/process_exit_ack_retry_test.go @@ -0,0 +1,108 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "regexp" + "strconv" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// A revocation ACK whose first answer is lost to a busy master (its call +// timed out, or the master was unavailable) is asked again, and the repeat's +// answer completes the stop with status 0, not 75. Any other first answer +// is final: one ACK, exit 75. +func TestWorkspaceRevocationAckIsAskedAgainAfterALostAnswer(t *testing.T) { + for _, c := range []struct { + name string + first error + acks int32 + code int + }{ + {"deadline exceeded once", status.Error(codes.DeadlineExceeded, "context deadline exceeded"), 2, 0}, + {"unavailable once", status.Error(codes.Unavailable, "workspace ACK: read detached HEAD: busy"), 2, 0}, + {"refused (final)", status.Error(codes.FailedPrecondition, "workspace revoke ACK: stale or unsolicited"), 1, 75}, + } { + t.Run(c.name, func(t *testing.T) { + var stream *exitAssignmentStream + h, send := exitAuthorityHost(t, func(s *exitAssignmentStream) { + stream = s + s.revoke = true + s.ackFirstError = c.first + }) + send("r", 1) + ctx, cancel := context.WithCancel(context.Background()) + doneConsumed := false + requests, done := startWorkspaceLease(ctx, h) + t.Cleanup(func() { + cancel() + if !doneConsumed { + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("lease worker did not join") + } + } + }) + e := newProcessExit(ctx) + f := flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v", replicaID: "r"} + request, leaseDone := waitWorkspaceStop(e, f, h, requests, done) + if request == nil || !h.WorkspaceLeaseRevoking() { + t.Fatal("real planned drain not acquired") + } + me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + st := layoutProofStore{h: layout.Head{Gen: 1, Epoch: 1, Holder: "s/r", ClaimID: "k", State: layout.StateDetached, Activity: layout.Activity{Kind: layout.ActIdle}}, found: true} + gen, proofErr := workspaceLayoutDetachedGeneration(request.ctx, st, request.id, me) + if proofErr != nil { + t.Fatal(proofErr) + } + request.reply <- workspaceStopResult{gen: gen} + finishWorkspaceLease(e, f, h, leaseDone) + doneConsumed = true + out := <-e.decision + if got := stream.acks.Load(); got != c.acks { + t.Fatalf("%d ACK calls; want %d", got, c.acks) + } + if out.code != c.code { + t.Fatalf("stop classified %+v; want status %d", out, c.code) + } + }) + } +} + +// The closeout (with its repeated ACK attempts) fits the shipped units' stop +// budget: the drain before it and superviseProcess's exit wait after it +// (each volume.WorkspaceDrainTimeout) plus the closeout stay under every +// blockvolume unit's TimeoutStopSec, and the closeout leaves room for at +// least two ACK attempts. +func TestWorkspaceCloseoutFitsTheUnitsStopBudget(t *testing.T) { + if workspaceLeaseCloseoutTimeout < 2*volume.WorkspaceAckTimeout { + t.Fatalf("closeout %v leaves no room for a second %v ACK attempt", workspaceLeaseCloseoutTimeout, volume.WorkspaceAckTimeout) + } + units, err := filepath.Glob(filepath.Join("..", "..", "deploy", "systemd", "sw-blockvolume*.service")) + if err != nil || len(units) == 0 { + t.Fatalf("no blockvolume units found: %v", err) + } + for _, unit := range units { + raw, err := os.ReadFile(unit) + if err != nil { + t.Fatal(err) + } + m := regexp.MustCompile(`(?m)^TimeoutStopSec=(\d+)s\s*$`).FindSubmatch(raw) + if m == nil { + t.Fatalf("%s: no TimeoutStopSec=s", unit) + } + n, _ := strconv.Atoi(string(m[1])) + stop := time.Duration(n) * time.Second + if total := volume.WorkspaceDrainTimeout + workspaceLeaseCloseoutTimeout + volume.WorkspaceDrainTimeout; total >= stop { + t.Fatalf("%s: drain %v + closeout %v + exit wait %v = %v, not under TimeoutStopSec %v", unit, volume.WorkspaceDrainTimeout, workspaceLeaseCloseoutTimeout, volume.WorkspaceDrainTimeout, total, stop) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/process_exit_authority_test.go b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go new file mode 100644 index 0000000000..b8b42a36b6 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/process_exit_authority_test.go @@ -0,0 +1,740 @@ +package main + +import ( + "bytes" + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "net" + "sync/atomic" + "testing" + "time" +) + +type exitAssignmentStream struct { + control.UnimplementedAssignmentServiceServer + control.UnimplementedObservationServiceServer + control.UnimplementedWorkspaceServiceServer + revoke bool + refuse error // when set, every renewal is refused with it + streamRefuse error // the master may refuse a restarted source before an assignment + // identityRefusals: the first this many stream calls are refused with + // the typed IDENTITY detail. + identityRefusals atomic.Int32 + ackError error + // ackFirstError, when set, answers only the first ACK (counted, not + // recorded) with it; later ones get ackError. + ackFirstError error + acks atomic.Int32 + facts chan *control.AssignmentFact +} + +func (s *exitAssignmentStream) RenewWorkspaceLease(_ context.Context, id *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) { + if s.refuse != nil { + return nil, s.refuse + } + return &control.WorkspaceLeaseFact{VolumeId: id.VolumeId, ReplicaId: id.ReplicaId, Epoch: id.Epoch, ValidForNs: int64(30 * time.Second), Revoking: s.revoke}, nil +} +func (s *exitAssignmentStream) AckWorkspaceRevoked(_ context.Context, a *control.WorkspaceRevocationAck) (*control.WorkspaceEmpty, error) { + if a.GetHeadGen() != 1 { + return nil, errors.New("ACK lacks the stored detached proof") + } + if s.acks.Add(1) == 1 && s.ackFirstError != nil { + return nil, s.ackFirstError + } + return &control.WorkspaceEmpty{}, s.ackError +} +func (s *exitAssignmentStream) ReportHeartbeat(context.Context, *control.HeartbeatReport) (*control.HeartbeatAck, error) { + return &control.HeartbeatAck{}, nil +} +func (s *exitAssignmentStream) SubscribeAssignments(_ *control.SubscribeRequest, stream control.AssignmentService_SubscribeAssignmentsServer) error { + if s.streamRefuse != nil { + return s.streamRefuse + } + if s.identityRefusals.Add(-1) >= 0 { + st, _ := status.New(codes.FailedPrecondition, `assignment stream: server id "s" is not registered`). + WithDetails(&control.WorkspaceLeaseRefusal{Kind: control.WorkspaceLeaseRefusal_IDENTITY, Identity: "unregistered"}) + return st.Err() + } + for { + select { + case <-stream.Context().Done(): + return stream.Context().Err() + case f := <-s.facts: + if err := stream.Send(f); err != nil { + return err + } + } + } +} + +func TestRestartedMovedSourceExits78WithoutAnOwnLine(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + refusal, err := status.New(codes.FailedPrecondition, "workspace moved to holder node-b at epoch 8"). + WithDetails(&control.WorkspaceLeaseRefusal{Kind: control.WorkspaceLeaseRefusal_MOVED}) + if err != nil { + t.Fatal(err) + } + h, _ := exitAuthorityHost(t, func(s *exitAssignmentStream) { s.streamRefuse = refusal.Err() }) + for { + if _, final := h.MasterWaitState(); final == "moved" { + break + } + select { + case <-ctx.Done(): + t.Fatal("the master's typed MOVED never reached the restarted source") + case <-time.After(time.Millisecond): + } + } + if h.Adapter().Projection().Epoch != 0 || h.IsCurrentReplicaSuperseded() { + t.Fatal("fixture acquired an own line or inferred supersession") + } + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, &exitStartupOutcome{expired: true}) { + t.Fatal("no startup decision") + } + if out := <-e.decision; out.code != 78 || out.reason != "moved" || out.detail != refusal.Message() { + t.Fatalf("moved restart chose %+v; want 78 moved, never retry 75", out) + } +} +func exitAuthorityHost(t *testing.T, configure ...func(*exitAssignmentStream)) (*volume.Host, func(string, uint64)) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + stream := &exitAssignmentStream{facts: make(chan *control.AssignmentFact, 4)} + for _, f := range configure { + f(stream) + } + control.RegisterWorkspaceServiceServer(srv, stream) + control.RegisterAssignmentServiceServer(srv, stream) + control.RegisterObservationServiceServer(srv, stream) + go srv.Serve(ln) + t.Cleanup(srv.Stop) + h, err := volume.New(volume.Config{WorkspaceLease: true, MasterAddr: ln.Addr().String(), ServerID: "s", VolumeID: "v", ReplicaID: "r", DataAddr: "127.0.0.1:1", CtrlAddr: "127.0.0.1:2"}) + if err != nil { + t.Fatal(err) + } + h.Start() + t.Cleanup(func() { + if err := h.Close(); err != nil { + t.Error(err) + } + }) + return h, func(replica string, epoch uint64) { + t.Helper() + stream.facts <- &control.AssignmentFact{VolumeId: "v", ReplicaId: replica, ServerId: "s", Epoch: epoch, EndpointVersion: 1} + deadline := time.NewTimer(3 * time.Second) + defer deadline.Stop() + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for { + ready := false + if replica == "r" { + ready = h.Adapter().Projection().Epoch == epoch + } else { + f := h.LastOtherLine() + ready = f != nil && f.ReplicaId == replica && f.Epoch == epoch + } + if ready { + return + } + select { + case <-deadline.C: + t.Fatal("assignment observation did not arrive") + case <-tick.C: + } + } + } +} + +// Exercise the real Host subscription and the process stop seam, including a +// historical other-replica record retained after the master assigns us again. +func TestWorkspaceRetryUsesNewestOwnAssignment(t *testing.T) { + for _, tc := range []struct { + name string + facts []struct { + replica string + epoch uint64 + } + want int + }{ + {"old other then own", []struct { + replica string + epoch uint64 + }{{"other", 6}, {"r", 7}}, 75}, + {"own then newer other", []struct { + replica string + epoch uint64 + }{{"r", 5}, {"other", 6}}, 78}, + {"never assigned", []struct { + replica string + epoch uint64 + }{{"other", 6}}, 75}, + {"empty replica newer epoch", []struct { + replica string + epoch uint64 + }{{"r", 5}, {"", 7}}, 75}, + {"same replica higher epoch", []struct { + replica string + epoch uint64 + }{{"r", 5}, {"r", 7}}, 75}, + } { + t.Run(tc.name, func(t *testing.T) { + h, send := exitAuthorityHost(t) + for _, f := range tc.facts { + send(f.replica, f.epoch) + } + e := newProcessExit(context.Background()) + done := make(chan error, 1) + done <- errors.New("lease ended") + waitWorkspaceStop(e, flags{volumeID: "v", replicaID: "r"}, h, nil, done) + if out := <-e.decision; out.code != tc.want { + t.Fatalf("lease end classified %+v, want%d", out, tc.want) + } + }) + } +} +func TestWorkspaceUnconfirmedRevokeHasOwnReason(t *testing.T) { + h, _ := exitAuthorityHost(t) + e := newProcessExit(context.Background()) + done := make(chan error, 1) + done <- errors.New("ACK answer lost") + finishWorkspaceLease(e, flags{volumeID: "v", replicaID: "r"}, h, done) + if out := <-e.decision; out.code != 75 || out.reason != "revoke_ack_unconfirmed" { + t.Fatalf("unconfirmed ACK classified %+v", out) + } +} + +// Controlled provider outcome at its public generation/selection seam. The +// real provider deadline/retained-state boundary is tested in durable. +type exitStartupOutcome struct{ expired bool } + +func (s *exitStartupOutcome) ChunkStartupSuperseded(string, uint64) bool { return false } +func (s *exitStartupOutcome) ChunkStartupOutcome(string) (uint64, bool) { return 1, s.expired } +func (s *exitStartupOutcome) ChooseChunkStartupExit(_ string, gen uint64, choose func()) bool { + if gen != 1 || !s.expired { + return false + } + choose() + return true +} + +func TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck(t *testing.T) { + for _, failAck := range []bool{false, true} { + t.Run(map[bool]string{false: "ACK succeeds", true: "ACK lost"}[failAck], func(t *testing.T) { + var stream *exitAssignmentStream + h, send := exitAuthorityHost(t, func(s *exitAssignmentStream) { + stream = s + s.revoke = true + if failAck { + s.ackError = errors.New("ACK answer lost") + } + }) + send("r", 1) + ctx, cancel := context.WithCancel(context.Background()) + doneConsumed := false + requests, done := startWorkspaceLease(ctx, h) + t.Cleanup(func() { + cancel() + if !doneConsumed { + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("lease worker did not join") + } + } + }) + e := newProcessExit(ctx) + f := flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v", replicaID: "r"} + // The real guard sets revoked, sends its stop request, and waits for the + // resource owner's drain reply. No success is selected yet. + request, leaseDone := waitWorkspaceStop(e, f, h, requests, done) + if request == nil || !h.WorkspaceLeaseRevoking() { + t.Fatal("real planned drain not acquired") + } + // Deliver expiry only after the real guard's planned drain owns + // shutdown, while its resource-owner reply is deliberately held. + p := &exitStartupOutcome{expired: true} + chooseChunkStartupExit(e, f, h, p) + select { + case out := <-e.decision: + t.Fatalf("startup overrode the pending real drain: %+v", out) + default: + } + // The real proof reader supplies the generation to the real lease + // worker; a constant here would not join the two safety checks. + me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + st := layoutProofStore{h: layout.Head{Gen: 1, Epoch: 1, Holder: "s/r", ClaimID: "k", State: layout.StateDetached, Activity: layout.Activity{Kind: layout.ActIdle}}, found: true} + gen, proofErr := workspaceLayoutDetachedGeneration(request.ctx, st, request.id, me) + if proofErr != nil { + t.Fatal(proofErr) + } + request.reply <- workspaceStopResult{gen: gen} + finishWorkspaceLease(e, f, h, leaseDone) + doneConsumed = true + out := <-e.decision + if stream.acks.Load() != 1 { + t.Fatal("real guard did not send proof ACK") + } + if !failAck && out.code != 0 { + t.Fatalf("ACKed stop restarted: %+v", out) + } + if failAck && (out.code != 75 || out.reason != "revoke_ack_unconfirmed") { + t.Fatalf("unconfirmed ACK: %+v", out) + } + }) + } +} + +// The real provider must carry the claim's filer proof to the process owner, +// even when the master stream has never reported another replica. +type claimExitView struct { + assigned atomic.Bool + epoch uint64 +} + +func (v *claimExitView) Projection() frontend.Projection { + if !v.assigned.Load() { + return frontend.Projection{VolumeID: "v"} + } + epoch := v.epoch + if epoch == 0 { + epoch = 1 + } + return frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: epoch, Healthy: true} +} + +// A layout HEAD held by another server at the granted epoch is a final +// refusal. The master has not delivered a newer foreign assignment, so the +// process must derive its exit from the provider's observed HEAD. +func TestWorkspaceForeignHeadClaimChoosesNoRetry(t *testing.T) { + for _, tc := range []struct { + name string + headEpoch uint64 + grantEpoch uint64 + deferred bool + wantExit bool + }{ + {"foreign holder at granted epoch", 1, 1, false, true}, + {"foreign holder above granted epoch", 2, 1, false, true}, + {"foreign holder after assignment", 1, 1, true, true}, + {"foreign holder below granted epoch", 1, 2, false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + testWorkspaceLayoutForeignClaimExit(t, tc.headEpoch, tc.grantEpoch, tc.deferred, tc.wantExit) + }) + } +} + +func testWorkspaceLayoutForeignClaimExit(t *testing.T, headEpoch, grantEpoch uint64, deferred, wantExit bool) { + t.Helper() + ctx := context.Background() + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v", ID: id} + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), &maintenanceBlobs{d: map[string][]byte{}}, "/exit-layout") + if err != nil { + t.Fatal(err) + } + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + st, err := cat.Store(ref) + if err != nil { + t.Fatal(err) + } + foreign, found, err := st.ReadHead(ctx) + if err != nil || !found { + t.Fatalf("initial HEAD: found=%v err=%v", found, err) + } + foreign.Epoch, foreign.Holder, foreign.ClaimID = headEpoch, "other/r", "other-claim" + if err := st.UpdateHead(ctx, foreign.Gen, foreign, layout.CauseCommit); err != nil { + t.Fatal(err) + } + foreign, _, err = st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + view := &claimExitView{epoch: grantEpoch} + view.assigned.Store(!deferred) + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r", + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return st, nil }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, ref, me) + }, + } + p, err := durable.NewDurableProvider(cfg, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + _, err = p.RecoverVolume(ctx, "v") + if deferred { + if err != nil { + t.Fatalf("recovery before assignment: %v", err) + } + view.assigned.Store(true) + select { + case <-p.ChunkStartupUpdates(): + case <-time.After(3 * time.Second): + t.Fatal("foreign layout HEAD did not end deferred startup") + } + } else if wantExit && !errors.Is(err, layout.ErrNotHolder) && !errors.Is(err, layout.ErrStaleEpoch) { + t.Fatalf("layout Start refusal: %v; want not-holder or stale-epoch", err) + } + if !wantExit { + if err != nil { + t.Fatalf("newer grant did not claim: %v", err) + } + if _, ended := p.ChunkStartupOutcome("v"); ended { + t.Fatal("newer grant ended startup") + } + claimed, _, err := st.ReadHead(ctx) + if err != nil || claimed.Epoch != grantEpoch || claimed.Holder != "s/r" || claimed.Gen <= foreign.Gen { + t.Fatalf("newer grant did not claim HEAD: %+v err=%v", claimed, err) + } + return + } + if _, ended := p.ChunkStartupOutcome("v"); !ended { + t.Fatal("foreign layout HEAD did not end startup") + } + h, _ := exitAuthorityHost(t) + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) { + t.Fatal("foreign layout HEAD did not select an exit") + } + if out := <-e.decision; out.code != 78 { + t.Fatalf("foreign layout HEAD chose %+v; want 78", out) + } + after, _, err := st.ReadHead(ctx) + if err != nil || after.Gen != foreign.Gen || after.Holder != foreign.Holder || after.ClaimID != foreign.ClaimID { + t.Fatalf("refused Start changed HEAD: before=%+v after=%+v err=%v", foreign, after, err) + } +} + +// Unlike a move BACK to an older foreign publication, this local root's +// assignment is older than the foreign HEAD: another holder has superseded it. +func TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry(t *testing.T) { + for _, deferred := range []bool{false, true} { + t.Run(map[bool]string{false: "immediate", true: "waiting"}[deferred], func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + h, _ := exitAuthorityHost(t) + root := t.TempDir() + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v", ID: id} + blobs := &maintenanceBlobs{d: map[string][]byte{}} + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), blobs, "/exit-layout") + if err != nil { + t.Fatal(err) + } + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + st, err := cat.Store(ref) + if err != nil { + t.Fatal(err) + } + view := &claimExitView{} + view.assigned.Store(true) + open := func() *durable.DurableProvider { + t.Helper() + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r", + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return st, nil }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, ref, me) + }, + } + p, err := durable.NewDurableProvider(cfg, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + return p + } + first := open() + if _, err := first.RecoverVolume(ctx, "v"); err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{0x73}, 4096) + if _, err := first.LogicalStorage("v").Write(0, want); err != nil { + t.Fatal(err) + } + if _, err := first.LogicalStorage("v").Sync(); err != nil { + t.Fatal(err) + } + if err := first.Close(); err != nil { + t.Fatal(err) + } + before, found, err := st.ReadHead(ctx) + if err != nil || !found { + t.Fatalf("claimed layout HEAD: found=%v err=%v", found, err) + } + foreign := before + foreign.Epoch, foreign.Holder, foreign.ClaimID = 2, "other/r", "other-claim" + if err := st.UpdateHead(ctx, before.Gen, foreign, layout.CauseCommit); err != nil { + t.Fatal(err) + } + view.assigned.Store(!deferred) + second := open() + _, err = second.RecoverVolume(ctx, "v") + if deferred { + if err != nil { + t.Fatal(err) + } + view.assigned.Store(true) + select { + case <-second.ChunkStartupUpdates(): + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + } else if !errors.Is(err, layout.ErrStaleEpoch) { + t.Fatalf("old root refusal=%v", err) + } + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, second) { + t.Fatal("foreign HEAD attach refusal retained the superseded process") + } + if out := <-e.decision; out.code != 78 { + t.Fatalf("old holder exit=%+v", out) + } + if got, err := second.LogicalStorage("v").Read(0); err != nil || !bytes.Equal(got, want) { + t.Fatalf("refusal lost local acknowledged bytes: %v", err) + } + after, found, err := st.ReadHead(ctx) + if err != nil || !found || after.Gen != before.Gen+1 || after.Holder != "other/r" || after.ClaimID != "other-claim" || blobs.n != 0 { + t.Fatalf("refusal mutated HEAD/payload: %+v found=%v puts=%d err=%v", after, found, blobs.n, err) + } + + }) + } +} + +type displacedClaimExitView struct{} + +func (displacedClaimExitView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: "v", ReplicaID: "B", Epoch: 3, Healthy: true} +} + +type displacedLayoutClaimStore struct { + layout.StartStore + epoch uint64 + raced bool +} + +func (s *displacedLayoutClaimStore) UpdateHead(ctx context.Context, expected uint64, next layout.Head, cause layout.HeadWriteCause) error { + if !s.raced { + s.raced = true + current, found, err := s.StartStore.ReadHead(ctx) + if err != nil || !found { + return errors.New("racing layout HEAD unavailable") + } + late := current + late.Epoch, late.Holder, late.ClaimID = s.epoch, "C", "late-claim" + if err := s.StartStore.UpdateHead(ctx, current.Gen, late, cause); err != nil { + return err + } + } + return s.StartStore.UpdateHead(ctx, expected, next, cause) +} + +// The claim's conditional update loses to another holder. A re-read at or +// above the grant proves a final exit; below it, a new Start can claim. +func TestWorkspaceDisplacedClaimUsesAssignedEpoch(t *testing.T) { + for _, tc := range []struct { + name string + epoch uint64 + final bool + }{ + {"late lower epoch", 2, false}, + {"equal epoch foreign holder", 3, true}, + {"higher epoch foreign holder", 4, true}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + ref := chunkstore.VolumeRef{Name: "v", ID: id} + cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), &maintenanceBlobs{d: map[string][]byte{}}, "/exit-layout") + if err != nil { + t.Fatal(err) + } + if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + base, err := cat.Store(ref) + if err != nil { + t.Fatal(err) + } + initial, found, err := base.ReadHead(ctx) + if err != nil || !found { + t.Fatalf("initial HEAD: found=%v err=%v", found, err) + } + initial.Epoch, initial.Holder, initial.ClaimID = 1, "A", "first-claim" + if err := base.UpdateHead(ctx, initial.Gen, initial, layout.CauseCommit); err != nil { + t.Fatal(err) + } + store := &displacedLayoutClaimStore{StartStore: base, epoch: tc.epoch} + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "B", + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return store, nil }, + ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + return chunkstore.NewLayoutRemote(cat, ref, me) + }, + } + p, err := durable.NewDurableProvider(cfg, displacedClaimExitView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(ctx, "v"); !errors.Is(err, layout.ErrPrecondition) { + t.Fatalf("claim race: %v; want HEAD precondition", err) + } + if !store.raced { + t.Fatal("controlled HEAD race did not run") + } + if tc.final { + h, _ := exitAuthorityHost(t) + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) { + t.Fatal("displaced layout claim did not choose an exit") + } + if out := <-e.decision; out.code != 78 { + t.Fatalf("displaced claim chose %+v; want 78", out) + } + } else if _, ended := p.ChunkStartupOutcome("v"); ended { + t.Fatal("a lower racing epoch ended startup") + } + after, found, err := base.ReadHead(ctx) + if err != nil || !found || after.Gen != initial.Gen+2 || after.Epoch != tc.epoch || after.Holder != "C" { + t.Fatalf("refused claim changed racing HEAD: %+v found=%v err=%v", after, found, err) + } + }) + } +} + +// A typed MOVED or DELETED renewal refusal, seen by the real host's guard, +// turns the startup outcome into 78 with that reason; a refusal without the +// detail stays 75 assignment_timeout. +func TestChunkStartupExitFinalGives78(t *testing.T) { + refusal := func(kind control.WorkspaceLeaseRefusal_Kind) error { + st, err := status.New(codes.FailedPrecondition, "workspace lease: server identity does not match the current holder"). + WithDetails(&control.WorkspaceLeaseRefusal{Kind: kind}) + if err != nil { + t.Fatal(err) + } + return st.Err() + } + for _, tc := range []struct { + name string + refuse error + foreign bool // the stream also delivered a newer line naming another replica + code int + reason string + }{ + {"moved", refusal(control.WorkspaceLeaseRefusal_MOVED), false, exitWorkspaceSuperseded, "moved"}, + {"moved, newer foreign line also seen", refusal(control.WorkspaceLeaseRefusal_MOVED), true, exitWorkspaceSuperseded, "moved"}, + {"deleted", refusal(control.WorkspaceLeaseRefusal_DELETED), false, exitWorkspaceSuperseded, "deleted"}, + {"no detail", status.Error(codes.FailedPrecondition, "workspace lease: server identity does not match the current holder"), false, exitWorkspaceRetry, "assignment_timeout"}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + h, assign := exitAuthorityHost(t, func(s *exitAssignmentStream) { s.refuse = tc.refuse }) + assign("r", 1) + leaseCtx, stopLease := context.WithCancel(ctx) + done := make(chan error, 1) + go func() { + done <- h.RunWorkspaceLease(leaseCtx, func(context.Context, *control.WorkspaceIdentity) (uint64, error) { return 1, nil }) + }() + t.Cleanup(func() { stopLease(); <-done }) + if tc.reason == "assignment_timeout" { + time.Sleep(2 * time.Second) // a renewal or two, refused without a detail + if _, final := h.MasterWaitState(); final != "" { + t.Fatalf("a refusal without a detail was taken as final %q", final) + } + } + for tc.reason != "assignment_timeout" { + if _, final := h.MasterWaitState(); final != "" { + if tc.foreign { + assign("r2", 2) + if !h.IsCurrentReplicaSuperseded() { + t.Fatal("fixture: the newer foreign line does not supersede") + } + } + break + } + select { + case <-ctx.Done(): + t.Fatal("the guard's refusal never reached the host") + case <-time.After(20 * time.Millisecond): + } + } + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, &exitStartupOutcome{expired: true}) { + t.Fatal("the startup outcome selected no exit") + } + out := <-e.decision + if out.code != tc.code || out.reason != tc.reason { + t.Fatalf("exit %+v; want %d %s", out, tc.code, tc.reason) + } + }) + } +} + +// An identity refusal on the assignment stream ends when the stream (which +// checks the holder's identity) delivers an assignment after the +// registration is fixed, not 30 s later by decay. +func TestIdentityRefusalEndsOnADeliveredAssignment(t *testing.T) { + h, assign := exitAuthorityHost(t, func(s *exitAssignmentStream) { s.identityRefusals.Store(1) }) + deadline := time.Now().Add(10 * time.Second) + for { + if w := h.MasterWaitStatus(); w != nil && w.Reason == "identity refused: unregistered" { + break + } + if time.Now().After(deadline) { + t.Fatalf("the stream's identity refusal never showed: %+v", h.MasterWaitStatus()) + } + time.Sleep(10 * time.Millisecond) + } + assign("r", 1) // the next stream is accepted and delivers + deadline = time.Now().Add(5 * time.Second) + for { + if w := h.MasterWaitStatus(); w == nil || w.Reason != "identity refused: unregistered" { + return + } + if time.Now().After(deadline) { + t.Fatal("a delivered assignment did not end the identity refusal") + } + time.Sleep(10 * time.Millisecond) + } +} diff --git a/seaweed-block/cmd/blockvolume/process_exit_revoked_test.go b/seaweed-block/cmd/blockvolume/process_exit_revoked_test.go new file mode 100644 index 0000000000..65610793e9 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/process_exit_revoked_test.go @@ -0,0 +1,57 @@ +package main + +import ( + "context" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "os" + "os/exec" + "strings" + "testing" + "time" +) + +func TestRestartedRecordedRevocationExitsFinalOnce(t *testing.T) { + if os.Getenv("SWB_RECORDED_REVOKE_CHILD") == "1" { + refusal, e := status.New(codes.FailedPrecondition, "volume was moved or revoked; inspect workspace state and complete the intended move; leave this unit stopped").WithDetails(&control.WorkspaceLeaseRefusal{Kind: control.WorkspaceLeaseRefusal_FINAL}) + if e != nil { + t.Fatal(e) + } + h, send := exitAuthorityHost(t, func(s *exitAssignmentStream) { s.refuse = refusal.Err() }) + send("r", 1) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + startWorkspaceLease(ctx, h) // the restarted holder receives FINAL on renewal + for { + if _, final := h.MasterWaitState(); final != "" { + break + } + select { + case <-ctx.Done(): + t.Fatal("typed final renewal never ended the startup wait") + case <-time.After(time.Millisecond): + } + } + code := superviseProcess(ctx, func(e *processExit) int { + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, &exitStartupOutcome{expired: true}) { + t.Fatal("no final decision") + } + e.choose(workspaceExit{code: 75, reason: "later retry must lose"}) + return 0 + }) + os.Exit(code) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestRestartedRecordedRevocationExitsFinalOnce$", "-test.count=1") + cmd.Env = append(os.Environ(), "SWB_RECORDED_REVOKE_CHILD=1") + out, e := cmd.CombinedOutput() + exit, ok := e.(*exec.ExitError) + if !ok || exit.ExitCode() != 79 || strings.Count(string(out), "exiting status=79 reason=revoked") != 1 { + t.Fatalf("restarted revoked holder: %v output=%s; want one final exit 79", e, out) + } + if strings.Contains(string(out), "exiting status=75") { + t.Fatalf("restart loop outcome: %s", out) + } +} diff --git a/seaweed-block/cmd/blockvolume/process_exit_test.go b/seaweed-block/cmd/blockvolume/process_exit_test.go new file mode 100644 index 0000000000..ac6d56dfea --- /dev/null +++ b/seaweed-block/cmd/blockvolume/process_exit_test.go @@ -0,0 +1,93 @@ +package main + +import ( + "context" + "errors" + "os" + "os/exec" + "testing" + "time" +) + +func TestWorkspaceExitFirstOutcomeIsLatched(t *testing.T) { + for _, first := range []workspaceExit{{code: 75, reason: "lease_expired"}, {code: 78, reason: "superseded"}, {code: 0, reason: "revoked"}} { + e := newProcessExit(context.Background()) + e.choose(first) + e.choose(workspaceExit{code: 75, reason: "assignment_timeout"}) + <-e.done + if got := <-e.decision; got != first { + t.Fatalf("first=%+v changed to %+v", first, got) + } + e.choose(workspaceExit{code: 78, reason: "superseded"}) + select { + case got := <-e.decision: + t.Fatalf("later outcome published: %+v", got) + default: + } + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + e := newProcessExit(ctx) + e.choose(workspaceExit{code: 78, reason: "superseded"}) + if got := <-e.decision; got.code != 0 || got.reason != "signal" { + t.Fatalf("observed signal lost: %+v", got) + } +} + +func TestWorkspaceExitDoesNotWaitForBlockedFrontendClose(t *testing.T) { + finished := make(chan int) // a frontend Close that never returns + deadline := make(chan time.Time, 1) + deadline <- time.Time{} + if code := finishWorkspaceExit(workspaceExit{code: 75, reason: "lease_expired"}, finished, deadline); code != 75 { + t.Fatalf("code=%d", code) + } + // Cleanup errors do not overwrite an already selected retry/no-retry status. + done := make(chan int, 1) + done <- 1 + if code := finishWorkspaceExit(workspaceExit{code: 78, reason: "superseded"}, done, make(chan time.Time)); code != 78 { + t.Fatalf("code=%d", code) + } +} + +func TestWorkspacePlannedStopKeepsSuccess(t *testing.T) { + code := superviseProcess(context.Background(), func(e *processExit) int { + e.choose(workspaceExit{reason: "revoked"}) + return 0 // the close/ACK owner completed normally + }) + if code != 0 { + t.Fatalf("planned stop would restart: %d", code) + } +} + +// A real child process contains the stuck resource owner. An injected event +// tests the select above; this witness also covers deferred-cleanup isolation. +func TestWorkspaceRetryProcessExitsWhenCloseBlocks(t *testing.T) { + if os.Getenv("GAP1_BLOCKED_CLOSE_CHILD") == "1" { + code := superviseProcess(context.Background(), func(e *processExit) int { + e.choose(workspaceExit{code: 75, reason: "lease_expired"}) + select {} // the frontend/resource owner's Close never returns + }) + os.Exit(code) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestWorkspaceRetryProcessExitsWhenCloseBlocks$") + cmd.Env = append(os.Environ(), "GAP1_BLOCKED_CLOSE_CHILD=1") + out, err := cmd.CombinedOutput() + var exit *exec.ExitError + if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 75 { + t.Fatalf("blocked close exit: %v %s", err, out) + } +} + +func TestWorkspaceSignalFirstKeepsZeroAfterLaterFailure(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + code := superviseProcess(ctx, func(e *processExit) int { + e.choose(workspaceExit{code: 78, reason: "superseded"}) + return 1 // a later cleanup error cannot replace the chosen signal status + }) + if code != 0 { + t.Fatalf("first signal status changed to %d", code) + } +} diff --git a/seaweed-block/cmd/blockvolume/ready_latch.go b/seaweed-block/cmd/blockvolume/ready_latch.go new file mode 100644 index 0000000000..4c8b37c0c5 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/ready_latch.go @@ -0,0 +1,88 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "io" + "reflect" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +type primaryOpenProvider interface { + Open(context.Context, string) (frontend.Backend, error) +} + +type durableIdentityLatchProvider interface { + LatchVolumeIdentity(string) (bool, error) +} + +func startReadyAssignmentLoop(ch <-chan adapter.AssignmentInfo, f flags, prov primaryOpenProvider, stdout, stderr io.Writer) { + go func() { + for info := range ch { + handleReadyAssignment(info, f, prov, stdout, stderr) + } + }() +} + +func handleReadyAssignment(info adapter.AssignmentInfo, f flags, prov primaryOpenProvider, stdout, stderr io.Writer) { + if f.printReadyLine && stdout != nil { + _ = json.NewEncoder(stdout).Encode(readyLine{ + Component: "blockvolume", + Phase: "assignment-received", + VolumeID: info.VolumeID, + ReplicaID: info.ReplicaID, + Epoch: info.Epoch, + EndpointVersion: info.EndpointVersion, + }) + } + if providerIsNil(prov) || info.VolumeID != f.volumeID || info.ReplicaID != f.replicaID || info.Epoch == 0 { + return + } + + if latcher, ok := prov.(durableIdentityLatchProvider); ok { + latched, err := latcher.LatchVolumeIdentity(info.VolumeID) + if err != nil { + if stderr != nil { + fmt.Fprintf(stderr, "blockvolume: durable lineage latch failed volume=%s replica=%s epoch=%d ev=%d: %v\n", + info.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion, err) + } + return + } + if stderr != nil { + fmt.Fprintf(stderr, "blockvolume: durable lineage latched volume=%s replica=%s epoch=%d ev=%d changed=%t\n", + info.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion, latched) + } + return + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := prov.Open(ctx, info.VolumeID); err != nil { + if stderr != nil { + fmt.Fprintf(stderr, "blockvolume: durable primary lineage ensure failed volume=%s replica=%s epoch=%d ev=%d: %v\n", + info.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion, err) + } + return + } + if stderr != nil { + fmt.Fprintf(stderr, "blockvolume: durable primary lineage ensured volume=%s replica=%s epoch=%d ev=%d\n", + info.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion) + } +} + +func providerIsNil(prov primaryOpenProvider) bool { + if prov == nil { + return true + } + v := reflect.ValueOf(prov) + switch v.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: + return v.IsNil() + default: + return false + } +} diff --git a/seaweed-block/cmd/blockvolume/ready_latch_test.go b/seaweed-block/cmd/blockvolume/ready_latch_test.go new file mode 100644 index 0000000000..748f915531 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/ready_latch_test.go @@ -0,0 +1,124 @@ +package main + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +type recordingPrimaryOpenProvider struct { + volumeID string + calls int + err error +} + +func (p *recordingPrimaryOpenProvider) Open(_ context.Context, volumeID string) (frontend.Backend, error) { + p.calls++ + p.volumeID = volumeID + return nil, p.err +} + +type recordingLatchProvider struct { + recordingPrimaryOpenProvider + latchVolumeID string + latchCalls int + latchChanged bool + latchErr error +} + +func (p *recordingLatchProvider) LatchVolumeIdentity(volumeID string) (bool, error) { + p.latchCalls++ + p.latchVolumeID = volumeID + return p.latchChanged, p.latchErr +} + +func TestReadyAssignment_PrimaryEnsuresDurableLineageAndPrintsReadyLine(t *testing.T) { + prov := &recordingPrimaryOpenProvider{} + var stdout, stderr bytes.Buffer + + handleReadyAssignment(adapter.AssignmentInfo{ + VolumeID: "v1", ReplicaID: "r2", Epoch: 2, EndpointVersion: 1, + }, flags{ + volumeID: "v1", replicaID: "r2", printReadyLine: true, + }, prov, &stdout, &stderr) + + if prov.calls != 1 || prov.volumeID != "v1" { + t.Fatalf("Open calls=%d volume=%q, want 1/v1", prov.calls, prov.volumeID) + } + if got := stdout.String(); !strings.Contains(got, `"phase":"assignment-received"`) || + !strings.Contains(got, `"epoch":2`) { + t.Fatalf("ready line missing assignment fields: %s", got) + } + if got := stderr.String(); !strings.Contains(got, "durable primary lineage ensured volume=v1 replica=r2 epoch=2 ev=1") { + t.Fatalf("ensure log mismatch: %s", got) + } +} + +func TestReadyAssignment_UsesDurableIdentityLatchWhenAvailable(t *testing.T) { + prov := &recordingLatchProvider{latchChanged: true} + var stderr bytes.Buffer + + handleReadyAssignment(adapter.AssignmentInfo{ + VolumeID: "v1", ReplicaID: "r2", Epoch: 2, EndpointVersion: 1, + }, flags{ + volumeID: "v1", replicaID: "r2", + }, prov, nil, &stderr) + + if prov.latchCalls != 1 || prov.latchVolumeID != "v1" { + t.Fatalf("LatchVolumeIdentity calls=%d volume=%q, want 1/v1", prov.latchCalls, prov.latchVolumeID) + } + if prov.calls != 0 { + t.Fatalf("Open must not be called when durable identity latch is available: %d", prov.calls) + } + if got := stderr.String(); !strings.Contains(got, "durable lineage latched volume=v1 replica=r2 epoch=2 ev=1 changed=true") { + t.Fatalf("latch log mismatch: %s", got) + } +} + +func TestReadyAssignment_IgnoresOtherReplica(t *testing.T) { + prov := &recordingPrimaryOpenProvider{} + + handleReadyAssignment(adapter.AssignmentInfo{ + VolumeID: "v1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, + }, flags{ + volumeID: "v1", replicaID: "r2", + }, prov, nil, nil) + + if prov.calls != 0 { + t.Fatalf("Open called for other replica: %d", prov.calls) + } +} + +func TestReadyAssignment_IgnoresTypedNilProvider(t *testing.T) { + var prov *recordingPrimaryOpenProvider + + handleReadyAssignment(adapter.AssignmentInfo{ + VolumeID: "v1", ReplicaID: "r2", Epoch: 2, EndpointVersion: 1, + }, flags{ + volumeID: "v1", replicaID: "r2", + }, prov, nil, nil) +} + +func TestReadyAssignment_ReportsDurableEnsureFailure(t *testing.T) { + prov := &recordingPrimaryOpenProvider{err: errors.New("boom")} + var stderr bytes.Buffer + + handleReadyAssignment(adapter.AssignmentInfo{ + VolumeID: "v1", ReplicaID: "r2", Epoch: 2, EndpointVersion: 1, + }, flags{ + volumeID: "v1", replicaID: "r2", + }, prov, nil, &stderr) + + if prov.calls != 1 { + t.Fatalf("Open calls=%d, want 1", prov.calls) + } + if got := stderr.String(); !strings.Contains(got, "durable primary lineage ensure failed") || + !strings.Contains(got, "boom") { + t.Fatalf("failure log mismatch: %s", got) + } +} diff --git a/seaweed-block/cmd/blockvolume/recovery_primary_wait_support_test.go b/seaweed-block/cmd/blockvolume/recovery_primary_wait_support_test.go new file mode 100644 index 0000000000..c47da0eafe --- /dev/null +++ b/seaweed-block/cmd/blockvolume/recovery_primary_wait_support_test.go @@ -0,0 +1,90 @@ +package main_test + +import ( + "fmt" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/storage" + "time" +) + +// The ceiling bounds the experiment, not product recovery. Reaching it is +// UNKNOWN even if a PRIMARY line arrives in the same observation. +type recoveryPrimaryWait struct { + began, last time.Time + lastAvailable time.Time + process string + phase storage.RecoveryPhase + completed uint64 + awaiting bool + fenceBytes, replayRecords uint64 + windowStarted bool + workActive bool +} + +func newRecoveryPrimaryWait(now time.Time) *recoveryPrimaryWait { + return &recoveryPrimaryWait{began: now, last: now, lastAvailable: now} +} +func (w *recoveryPrimaryWait) observe(now time.Time, s volume.RecoveryProgressStatus, adopted bool, available bool) (string, error) { + if now.Sub(w.began) >= 15*time.Minute { + return "unknown", nil + } + if !available { + if now.Sub(w.lastAvailable) >= 30*time.Second { + return "unknown", nil + } + return "waiting", nil + } + w.lastAvailable = now + if s.Stalled { + return "", fmt.Errorf("recovery_stalled at phase %d completed %d", s.Phase, s.Completed) + } + if s.ProcessID != "" { + if w.process != "" && w.process != s.ProcessID { + return "", fmt.Errorf("holder incarnation changed: %s -> %s", w.process, s.ProcessID) + } + w.process = s.ProcessID + } + if s.FenceBytes > w.fenceBytes || s.ReplayRecords > w.replayRecords { + completedAt := s.CounterProgressAt + if completedAt.IsZero() { + return "unknown", nil + } + if w.windowStarted && !w.awaiting && completedAt.Sub(w.last) >= 30*time.Second { + return "", fmt.Errorf("completed recovery gap reached30s before late work") + } + w.fenceBytes, w.replayRecords, w.last = s.FenceBytes, s.ReplayRecords, completedAt + w.windowStarted = true + w.workActive = true + } + if !w.windowStarted && (s.Phase == storage.RecoveryReplay || s.Phase == storage.RecoveryFence) { + w.windowStarted = true + w.workActive = true + w.last = now + } + w.phase, w.completed = s.Phase, s.Completed + + if w.windowStarted && s.AwaitingAuthority && !w.awaiting && !s.AuthorityWaitSince.IsZero() && s.AuthorityWaitSince.Sub(w.last) >= 30*time.Second { + return "", fmt.Errorf("silence reached30s before authority pause") + } + if s.AwaitingAuthority || w.awaiting { + w.last = now + } + w.awaiting = s.AwaitingAuthority + if !s.AwaitingAuthority && (s.Phase == storage.RecoveryReplay || s.Phase == storage.RecoveryFence) && now.Sub(w.last) >= 30*time.Second { + return "", fmt.Errorf("no completed recovery work for30s (phase %d completed %d)", w.phase, w.completed) + } + // Phase-only completion is not a counter. Once replay/fence was seen, + // its exit must itself be observed inside the last completed-work window. + // A late attach sample cannot prove when that exit occurred, even when + // PRIMARY is already logged or a general LastProgress timestamp moved. + if w.workActive && s.Phase != storage.RecoveryReplay && s.Phase != storage.RecoveryFence { + if now.Sub(w.last) >= 30*time.Second { + return "unknown", nil + } + w.workActive = false + } + if adopted && s.ProcessID != "" { + return "primary", nil + } + return "waiting", nil +} diff --git a/seaweed-block/cmd/blockvolume/recovery_primary_wait_test.go b/seaweed-block/cmd/blockvolume/recovery_primary_wait_test.go new file mode 100644 index 0000000000..a49206b68f --- /dev/null +++ b/seaweed-block/cmd/blockvolume/recovery_primary_wait_test.go @@ -0,0 +1,165 @@ +package main_test + +import ( + "fmt" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/storage" + "testing" + "time" +) + +func TestRecoveryPrimaryWaitUsesProgressNotTotalTime(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + for i := 1; i <= 6; i++ { + now := start.Add(time.Duration(i) * 20 * time.Second) + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: uint64(i) * 4 << 20, FenceBytes: uint64(i) * 4 << 20, CounterProgressAt: now} + if got, err := w.observe(now, s, false, true); got != "waiting" || err != nil { + t.Fatalf("progress %d: %s %v", i, got, err) + } + } + if got, err := w.observe(start.Add(121*time.Second), volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: 24 << 20}, true, true); got != "primary" || err != nil { + t.Fatalf("%s %v", got, err) + } +} + +func TestRecoveryPrimaryWaitRejectsRepeatedSamplesAndStall(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: 4 << 20, FenceBytes: 4 << 20, CounterProgressAt: start} + w.observe(start, s, false, true) + if _, err := w.observe(start.Add(30*time.Second), s, false, true); err == nil { + t.Fatal("identical counter renewed") + } + w = newRecoveryPrimaryWait(start) + s.Stalled = true + if _, err := w.observe(start, s, true, true); err == nil { + t.Fatal("stalled sample passed as primary") + } +} + +func TestRecoveryPrimaryWaitAuthorityPauseAndCeilingUnknown(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + s := volume.RecoveryProgressStatus{ProcessID: "p1", AwaitingAuthority: true} + if got, err := w.observe(start.Add(time.Minute), s, false, true); got != "waiting" || err != nil { + t.Fatalf("pause: %s %v", got, err) + } + s.AwaitingAuthority = false + if got, err := w.observe(start.Add(2*time.Minute), s, false, true); got != "waiting" || err != nil { + t.Fatalf("grant: %s %v", got, err) + } + if got, err := w.observe(start.Add(15*time.Minute), s, true, true); got != "unknown" || err != nil { + t.Fatalf("ceiling became pass: %s %v", got, err) + } +} + +func TestRecoveryPrimaryWaitLateProgressCannotHideSilence(t *testing.T) { + start := time.Unix(1000, 0) + for _, pause := range []bool{false, true} { + w := newRecoveryPrimaryWait(start) + first := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: 1, FenceBytes: 1, CounterProgressAt: start} + w.observe(start, first, false, true) + late := first + late.Completed = 2 + late.FenceBytes = 2 + late.CounterProgressAt = start.Add(31 * time.Second) + if pause { + late = first + late.AwaitingAuthority = true + late.AuthorityWaitSince = start.Add(31 * time.Second) + } + if _, err := w.observe(start.Add(31*time.Second), late, true, true); err == nil { + t.Fatalf("late pause=%t hid silence", pause) + } + } +} +func TestRecoveryPrimaryWaitUnavailableSamplePreservesPause(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + s := volume.RecoveryProgressStatus{ProcessID: "p1", AwaitingAuthority: true, AuthorityWaitSince: start} + w.observe(start, s, false, true) + if state, err := w.observe(start.Add(29*time.Second), volume.RecoveryProgressStatus{}, false, false); state != "waiting" || err != nil { + t.Fatalf("missing: %s %v", state, err) + } + if !w.awaiting || w.process != "p1" { + t.Fatal("missing sample changed known state") + } + if state, err := w.observe(start.Add(30*time.Second), volume.RecoveryProgressStatus{}, true, false); state != "unknown" || err != nil { + t.Fatalf("missing observation passed: %s %v", state, err) + } +} + +func TestRecoveryPrimaryWaitPhaseChangeIsNotProgress(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryReplay, ReplayRecords: 7, Completed: 7, CounterProgressAt: start} + w.observe(start, s, false, true) + s.Phase = storage.RecoveryFence + s.Completed = 1 + s.CounterProgressAt = start.Add(29 * time.Second) + if _, err := w.observe(start.Add(30*time.Second), s, true, true); err == nil { + t.Fatal("phase-only change hid no-progress window") + } +} + +func TestRecoveryPrimaryWaitDoesNotCountPreReplayWork(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + w.observe(start, volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryCreate}, false, true) + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryReplay, ReplayRecords: 1, CounterProgressAt: start.Add(40 * time.Second)} + if got, err := w.observe(start.Add(40*time.Second), s, false, true); got != "waiting" || err != nil { + t.Fatalf("pre-replay time counted: %s %v", got, err) + } + s.Phase = storage.RecoveryFence + s.LastProgress = start.Add(69 * time.Second) + if _, err := w.observe(start.Add(70*time.Second), s, true, true); err == nil { + t.Fatal("phase-only timestamp hid counter silence") + } +} + +func TestRecoveryPrimaryWaitExitNeedsTimelyWitness(t *testing.T) { + for _, phase := range []storage.RecoveryPhase{storage.RecoveryReplay, storage.RecoveryFence} { + for _, adopted := range []bool{false, true} { + t.Run(fmt.Sprintf("phase%d/primary%t", phase, adopted), func(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: phase, ReplayRecords: 1, CounterProgressAt: start} + if got, err := w.observe(start, s, false, true); got != "waiting" || err != nil { + t.Fatalf("setup: %s %v", got, err) + } + s.Phase = storage.RecoveryAttach + s.LastProgress = start.Add(31 * time.Second) + if got, err := w.observe(start.Add(31*time.Second), s, adopted, true); got != "unknown" || err != nil { + t.Fatalf("unproved exit became %s %v", got, err) + } + }) + } + } + // A witnessed timely exit ends only the replay/fence window; a later + // PRIMARY may follow other bounded work without inventing more counters. + t.Run("timely-exit", func(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, FenceBytes: 1, CounterProgressAt: start} + w.observe(start, s, false, true) + s.Phase = storage.RecoveryAttach + if got, err := w.observe(start.Add(29*time.Second), s, false, true); got != "waiting" || err != nil { + t.Fatalf("timely exit: %s %v", got, err) + } + if got, err := w.observe(start.Add(time.Minute), s, true, true); got != "primary" || err != nil { + t.Fatalf("witnessed exit: %s %v", got, err) + } + }) +} + +func TestRecoveryPrimaryWaitMissingCounterTimeIsUnknown(t *testing.T) { + start := time.Unix(1000, 0) + for _, adopted := range []bool{false, true} { + w := newRecoveryPrimaryWait(start) + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, FenceBytes: 1} + if got, err := w.observe(start.Add(31*time.Second), s, adopted, true); got != "unknown" || err != nil { + t.Fatalf("adopted=%t: missing timestamp became %s %v", adopted, got, err) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/replication_ingress.go b/seaweed-block/cmd/blockvolume/replication_ingress.go new file mode 100644 index 0000000000..45790fcf45 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/replication_ingress.go @@ -0,0 +1,247 @@ +package main + +import ( + "context" + "fmt" + "net" + "sync" + + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/recovery" + "github.com/seaweedfs/seaweed-block/core/replication" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +// replicationIngress owns both inbound lanes. Lock order: Host.selfFenceMu -> +// mu -> listener role gate. Stop never calls Host. No socket is created until +// an assignment permits a replica role, and each listener is fenced before Serve. +type replicationIngress struct { + mu sync.Mutex + addr, volumeID, floorPath string + store storage.LogicalStorage + applyGate *replication.ReplicaApplyGate + dualLane bool + // rf1Only, when set, refuses every role with replica slots with this reason + // (walstore-chunk). The host latches the error: no role is adopted, not Healthy. + rf1Only string + listener *transport.ReplicaListener + // epochs is the volume's epoch table, kept across roles; epochsErr a load + // failure, which refuses every role. + epochs *transport.EpochTable + epochsErr error + dual net.Listener + cancel context.CancelFunc + closed bool +} + +// newReplicationIngress is the volume's ingress from its flags; an RF1-only +// volume (walstore-chunk) refuses every role with replica slots. +func newReplicationIngress(f flags, store storage.LogicalStorage) *replicationIngress { + r := &replicationIngress{addr: f.dataAddr, store: store, volumeID: f.volumeID, + floorPath: replicaFloorPath(f), dualLane: f.recoveryMode == "dual-lane"} + r.rf1Only = rf1Only(f) + r.epochs, r.epochsErr = transport.LoadEpochTable(epochTablePath(f), f.volumeID) + if r.epochsErr == nil { + // Rows above the recovered store's next LSN name a lost tail. + r.epochsErr = r.epochs.TrimAbove(store.NextLSN()) + } + return r +} + +// EpochFloor is the volume's durable epoch floor (the highest epoch it took a +// role at), read from the floor record. +func (r *replicationIngress) EpochFloor() (uint64, error) { + if r.floorPath == "" { + return 0, fmt.Errorf("volume %s keeps no floor record", r.volumeID) + } + return transport.LoadFloorRecord(r.floorPath, r.volumeID) +} + +// EpochTable is the volume's epoch table (nil when it failed to load). +func (r *replicationIngress) EpochTable() *transport.EpochTable { return r.epochs } + +// notePrimaryEpoch makes the primary's row (epoch, the store's next LSN) +// durable before the role is adopted: the frontend is still gated, so the +// first write at this epoch takes exactly that LSN and no entry of the epoch +// can be durable before its row. NextLSN does not sync, so adoption never +// waits on an in-flight store effect. +func (r *replicationIngress) notePrimaryEpoch(epoch uint64) error { + if r.epochsErr != nil { + return fmt.Errorf("volume %s epoch table: %w", r.volumeID, r.epochsErr) + } + if r.epochs.Invalid() { + // Promoted (forced) over a store whose history is unknown: the table + // becomes exactly this epoch from the next LSN, so every survivor + // that rejoins holds an epoch this table never had and is rebuilt. + if err := r.epochs.Replace([]transport.EpochRow{{Epoch: epoch, FirstLSN: r.store.NextLSN()}}); err != nil { + return fmt.Errorf("volume %s epoch table: %w", r.volumeID, err) + } + return nil + } + if err := r.epochs.Note(epoch, r.store.NextLSN()); err != nil { + return fmt.Errorf("volume %s epoch table: %w", r.volumeID, err) + } + return nil +} + +// rf1Only is the single-replica rule of this volume, "" when replication is +// allowed. The host refuses assignments with replica slots (installed at +// construction, before any fact is applied or replayed); the ingress gate +// refuses the same roles again. +func rf1Only(f flags) string { + if f.durableImpl == "walstore-chunk" { + return chunkRF1Reason + } + return "" +} + +func (r *replicationIngress) FenceAsPrimary(epoch uint64) error { + return r.FenceAsPrimaryWithPeers(epoch, true) +} +func (r *replicationIngress) FenceAsPrimaryWithPeers(epoch uint64, hasPeers bool) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return fmt.Errorf("replication ingress closed") + } + if r.epochsErr != nil { + return fmt.Errorf("volume %s epoch table: %w", r.volumeID, r.epochsErr) + } + // The primary's row is noted after the fence has drained every inbound + // apply (so the local sync cannot wait on one) and before the role call + // returns: no write at this epoch is accepted before the row is durable. + if !hasPeers { + if r.listener != nil { + if err := r.listener.FenceAsPrimary(epoch); err != nil { + return err + } + } + r.stopLocked(true) + return r.notePrimaryEpoch(epoch) + } + if r.rf1Only != "" { + return fmt.Errorf("volume %s refuses a primary role with replica peers at epoch %d: %s", r.volumeID, epoch, r.rf1Only) + } + if err := r.roleLocked(epoch, true); err != nil { + return err + } + return r.notePrimaryEpoch(epoch) +} +func (r *replicationIngress) AdmitAsReplica(epoch uint64) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return fmt.Errorf("replication ingress closed: %w", volume.ErrRoleRefused) + } + if r.rf1Only != "" { + return fmt.Errorf("volume %s refuses a replica role at epoch %d: %s: %w", r.volumeID, epoch, r.rf1Only, volume.ErrRoleRefused) + } + if r.epochsErr != nil { + return fmt.Errorf("volume %s epoch table: %w", r.volumeID, r.epochsErr) + } + return r.roleLocked(epoch, false) +} + +// FenceFloor is a fencing round's promise on this replica: the listener +// makes epoch its durable floor (refusing every frame and ACK below it) +// before the round is answered. Without a listener (no replica role yet) +// there is nothing to fence and no promise to give. +func (r *replicationIngress) FenceFloor(epoch uint64) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed || r.listener == nil { + return fmt.Errorf("volume %s has no replica listener to fence at epoch %d", r.volumeID, epoch) + } + return r.listener.FenceFloor(epoch) +} + +// DurableFloor is the listener's durable floor (0 without a listener). +func (r *replicationIngress) DurableFloor() uint64 { + r.mu.Lock() + defer r.mu.Unlock() + if r.listener == nil { + return 0 + } + return r.listener.DurableFloor() +} + +func (r *replicationIngress) roleLocked(epoch uint64, primary bool) error { + listener := r.listener + fresh := listener == nil + if fresh { + // One version map per replica store, surviving listener role transitions. + if r.applyGate == nil { + r.applyGate = replication.NewReplicaApplyGate(r.store) + } + var err error + listener, err = transport.NewReplicaListenerWithFloorAndApplyHook(r.addr, r.store, r.volumeID, r.floorPath, r.applyGate) + if err != nil { + return err + } + listener.SetEpochTable(r.epochs) + } + var err error + if primary { + err = listener.FenceAsPrimary(epoch) + } else { + err = listener.AdmitAsReplica(epoch) + } + if err != nil { + if fresh { + listener.Stop() + } + return err + } + if !fresh { + return nil + } + var dl net.Listener + if r.dualLane { + var addr string + addr, err = deriveDualLaneAddr(r.addr) + if err == nil { + dl, err = net.Listen("tcp", addr) + } + if err != nil { + listener.Stop() + return err + } + } + r.listener, r.dual = listener, dl + listener.Serve() + if dl != nil { + ctx, cancel := context.WithCancel(context.Background()) + r.cancel = cancel + bridge := recovery.NewReplicaBridgeWithGate(r.store, listener) + go bridge.AcceptDualLaneLoop(ctx, dl) + } + return nil +} +func (r *replicationIngress) stopLocked(withdrawn bool) { + if r.cancel != nil { + r.cancel() + r.cancel = nil + } + if r.dual != nil { + _ = r.dual.Close() + r.dual = nil + } + if r.listener != nil { + if withdrawn { + // FenceAsPrimary already drained admitted mutations. The role has + // been revoked, so disconnect idle peers instead of waiting for + // them to close a connection to an endpoint they no longer own. + r.listener.StopHard() + } else { + r.listener.Stop() + } + r.listener = nil + } +} +func (r *replicationIngress) Stop() { + r.mu.Lock() + defer r.mu.Unlock() + r.closed = true + r.stopLocked(false) +} diff --git a/seaweed-block/cmd/blockvolume/replication_ingress_apply_test.go b/seaweed-block/cmd/blockvolume/replication_ingress_apply_test.go new file mode 100644 index 0000000000..f9745cf0d0 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/replication_ingress_apply_test.go @@ -0,0 +1,59 @@ +package main + +import ( + "bytes" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +func TestReplicationIngressSharesApplyVersionsAcrossSessions(t *testing.T) { + store := storage.NewBlockStore(64, 4096) + store.AdvanceFrontier(119) // the replica holds 1..119 (a rebuilt base): 120 is its next LSN + r := newReplicationIngress(flags{dataAddr: "127.0.0.1:0", volumeID: "vol1"}, store) + if err := r.AdmitAsReplica(1); err != nil { + t.Fatal(err) + } + t.Cleanup(r.Stop) + // This replica's history is epoch 1: a live entry of an epoch the table + // has no row for is accepted only at the store's next LSN. + if err := r.EpochTable().Replace([]transport.EpochRow{{Epoch: 1, FirstLSN: 1}}); err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{0xBB}, 4096) + ship := func(session, lsn uint64, data []byte, recovery bool) { + c, err := net.DialTimeout("tcp", r.listener.Addr(), 2*time.Second) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if err := c.SetDeadline(time.Now().Add(3 * time.Second)); err != nil { + t.Fatal(err) + } + lineage := transport.RecoveryLineage{SessionID: session, Epoch: 1, EndpointVersion: 1, TargetLSN: 120} + send := func(kind byte, data []byte) { + if err := transport.WriteMsg(c, kind, data); err != nil { + t.Fatal(err) + } + } + if recovery { + end, _ := store.Sync() // the catch-up starts after the replica's durable end + send(transport.MsgRecoveryLaneStart, transport.EncodeRecoveryLaneStart(lineage, end)) + } + send(transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: lineage, LBA: 5, Data: data, LSN: lsn})) + send(transport.MsgBarrierReq, transport.EncodeLineage(lineage)) + kind, _, err := transport.ReadMsg(c) + if err != nil || kind != transport.MsgBarrierResp { + t.Fatalf("barrier: kind=%d err=%v", kind, err) + } + } + ship(1, 120, want, false) + ship(2, 95, bytes.Repeat([]byte{0xAA}, 4096), true) + got, err := store.Read(5) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("production ingress allowed cross-session byte regression: err=%v", err) + } +} diff --git a/seaweed-block/cmd/blockvolume/replication_ingress_binary_test.go b/seaweed-block/cmd/blockvolume/replication_ingress_binary_test.go new file mode 100644 index 0000000000..6dadcde110 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/replication_ingress_binary_test.go @@ -0,0 +1,366 @@ +//go:build subprocess && !windows + +package main_test + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "errors" + "io" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/recovery" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" + "google.golang.org/grpc" +) + +// Controlled master stream exercises the real binary's normal assignment path. +// It does not model the master's placement or epoch-minting policy. +type ingressAssignments struct { + control.UnimplementedAssignmentServiceServer + control.UnimplementedObservationServiceServer + facts chan *control.AssignmentFact +} + +func (m *ingressAssignments) ReportHeartbeat(context.Context, *control.HeartbeatReport) (*control.HeartbeatAck, error) { + return &control.HeartbeatAck{}, nil +} +func (m *ingressAssignments) SubscribeAssignments(_ *control.SubscribeRequest, s control.AssignmentService_SubscribeAssignmentsServer) error { + for { + select { + case <-s.Context().Done(): + return s.Context().Err() + case f := <-m.facts: + if err := s.Send(f); err != nil { + return err + } + } + } +} +func ingressPortPair(t *testing.T) (string, string) { + t.Helper() + for i := 0; i < 100; i++ { + a, e := net.Listen("tcp", "127.0.0.1:0") + if e != nil { + t.Fatal(e) + } + port := a.Addr().(*net.TCPAddr).Port + b, e := net.ListenTCP("tcp", &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: port + 1}) + if e == nil { + x, y := a.Addr().String(), b.Addr().String() + a.Close() + b.Close() + return x, y + } + a.Close() + } + t.Fatal("no adjacent free ports") + return "", "" +} +func ingressWait(t *testing.T, what string, fn func() bool) { + t.Helper() + end := time.Now().Add(10 * time.Second) + for !fn() { + if time.Now().After(end) { + t.Fatal(what) + } + time.Sleep(20 * time.Millisecond) + } +} +func ingressRefused(t *testing.T, addr string) { + t.Helper() + c, e := net.DialTimeout("tcp", addr, 300*time.Millisecond) + if c != nil { + _ = c.SetDeadline(time.Now().Add(300 * time.Millisecond)) + _ = transport.WriteMsg(c, transport.MsgProbeReq, transport.EncodeProbeReq(transport.ProbeRequest{Lineage: transport.RecoveryLineage{Epoch: 999, SessionID: 1, EndpointVersion: 1, FrontierHint: 1}})) + c.Close() + } + if !errors.Is(e, syscall.ECONNREFUSED) { + t.Fatalf("replication connection to %s: want connection refused, got %v", addr, e) + } +} +func TestBinaryReplicationIngressFollowsAssignedSlots(t *testing.T) { + exe := filepath.Join(t.TempDir(), "blockvolume") + cmd := exec.Command("go", "build", "-race", "-p", "4", "-o", exe, ".") + if b, e := cmd.CombinedOutput(); e != nil { + t.Fatalf("build: %v %s", e, b) + } + for _, mode := range []string{"legacy", "dual-lane"} { + t.Run(mode, func(t *testing.T) { + m := &ingressAssignments{facts: make(chan *control.AssignmentFact, 4)} + ln, e := net.Listen("tcp", "127.0.0.1:0") + if e != nil { + t.Fatal(e) + } + server := grpc.NewServer() + control.RegisterAssignmentServiceServer(server, m) + control.RegisterObservationServiceServer(server, m) + go server.Serve(ln) + t.Cleanup(server.Stop) + data, dual := ingressPortPair(t) + status := pickAddr(t) + ctrl := pickAddr(t) + root := t.TempDir() + logPath := filepath.Join(t.TempDir(), "volume.log") + log, e := os.Create(logPath) + if e != nil { + t.Fatal(e) + } + child := exec.Command(exe, "--master", ln.Addr().String(), "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", data, "--ctrl-addr", ctrl, "--status-addr", status, "--t1-readiness", "--durable-root", root, "--volume-lock-dir-test-only", t.TempDir(), "--durable-impl", "walstore", "--durable-blocks", "64", "--heartbeat-interval", "50ms", "--recovery-mode", mode) + stripSystemdForTestLockDir(child) + child.Stdout, child.Stderr = log, log + if e = child.Start(); e != nil { + t.Fatal(e) + } + done := make(chan error, 1) + go func() { done <- child.Wait() }() + exited := false + t.Cleanup(func() { + if !exited { + child.Process.Signal(syscall.SIGTERM) + select { + case <-done: + case <-time.After(5 * time.Second): + child.Process.Kill() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("child reap timeout") + } + } + } + log.Close() + if t.Failed() { + b, _ := os.ReadFile(logPath) + t.Logf("binary log: %s", b) + } + }) + client := &http.Client{Timeout: 300 * time.Millisecond} + epoch := func(want float64) bool { + resp, e := client.Get("http://" + status + "/status?volume=v1") + if e != nil { + return false + } + defer resp.Body.Close() + var p map[string]any + if json.NewDecoder(resp.Body).Decode(&p) != nil { + return false + } + if want == 0 { + return true + } + return p["Epoch"] == want + } + ingressWait(t, "binary status not ready", func() bool { return epoch(0) }) + // No assignment: do not open an unauthorised replication socket. + ingressRefused(t, data) + ingressRefused(t, dual) + fact := func(e uint64, peers []*control.ReplicaDescriptor) *control.AssignmentFact { + return &control.AssignmentFact{ServerId: "s1", VolumeId: "v1", ReplicaId: "r1", Epoch: e, EndpointVersion: e, DataAddr: data, CtrlAddr: ctrl, PeerSetGeneration: e, Peers: peers} + } + m.facts <- fact(1, nil) + ingressWait(t, "RF1 assignment not applied", func() bool { return epoch(1) }) + // An attempted higher-epoch frame cannot even establish a connection. + ingressRefused(t, data) + ingressRefused(t, dual) + // RF can grow only through the authoritative assignment stream. + peer := &control.ReplicaDescriptor{ReplicaId: "r2", Epoch: 2, EndpointVersion: 2, DataAddr: pickAddr(t), CtrlAddr: pickAddr(t)} + m.facts <- fact(2, []*control.ReplicaDescriptor{peer}) + ingressWait(t, "RF2 assignment not applied", func() bool { return epoch(2) }) + for _, addr := range []string{data, dual} { + if addr == dual && mode != "dual-lane" { + ingressRefused(t, addr) + continue + } + c, e := net.DialTimeout("tcp", addr, time.Second) + if e != nil { + t.Fatalf("RF2 listener %s: %v", addr, e) + } + c.Close() + } + // A withdrawn role must close existing idle connections as well as + // the listening socket, without waiting for the peer to disconnect. + held, e := net.DialTimeout("tcp", data, time.Second) + if e != nil { + t.Fatal(e) + } + defer held.Close() + m.facts <- fact(3, nil) + ingressWait(t, "RF1 shrink not applied", func() bool { return epoch(3) }) + _ = held.SetReadDeadline(time.Now().Add(time.Second)) + var one [1]byte + if _, err := held.Read(one[:]); err == nil { + t.Fatal("withdrawn connection still usable") + } else if n, ok := err.(net.Error); ok && n.Timeout() { + t.Fatal("withdrawn connection not closed") + } + ingressRefused(t, data) + ingressRefused(t, dual) + // A supporting slot also opens both configured lanes. Removal from + // the authoritative set closes them, even without a primary role. + supporting := fact(4, []*control.ReplicaDescriptor{{ReplicaId: "r1", Epoch: 4, EndpointVersion: 4, DataAddr: data, CtrlAddr: ctrl}}) + supporting.ReplicaId = "r2" + m.facts <- supporting + ingressWait(t, "supporting assignment not applied", func() bool { return epoch(4) }) + for _, addr := range []string{data, dual} { + if addr == dual && mode != "dual-lane" { + continue + } + c, e := net.DialTimeout("tcp", addr, time.Second) + if e != nil { + t.Fatalf("supporting listener %s: %v", addr, e) + } + c.Close() + } + want := ingressProtocolPositive(t, data, dual, mode) + excluded := fact(5, nil) + excluded.ReplicaId = "r2" + m.facts <- excluded + ingressWait(t, "excluded slot still listens", func() bool { + c, e := net.DialTimeout("tcp", data, 200*time.Millisecond) + if c != nil { + c.Close() + } + return errors.Is(e, syscall.ECONNREFUSED) + }) + ingressRefused(t, dual) + // Reopen through the public recovery API only after the binary has + // fully stopped. Exact bytes must survive the wire barrier and close. + _ = child.Process.Signal(syscall.SIGTERM) + select { + case err := <-done: + exited = true + if err != nil { + t.Fatal(err) + } + case <-time.After(8 * time.Second): + t.Fatal("binary close did not settle") + } + store, err := storage.OpenWALStore(filepath.Join(root, "v1.bin")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + if _, err = store.Recover(); err != nil { + t.Fatal(err) + } + for lba, payload := range want { + got, err := store.Read(lba) + if err != nil || !bytes.Equal(got, payload) { + t.Fatalf("recovered LBA%d bytes differ: %v", lba, err) + } + } + t.Logf("%s supporting protocol/barrier and exact recovered bytes PASS", mode) + }) + } +} + +func ingressProtocolPositive(t *testing.T, data, dual, mode string) map[uint32][]byte { + t.Helper() + a := bytes.Repeat([]byte{0xA7}, 4096) + want := map[uint32][]byte{0: a, 1: make([]byte, 4096), 2: make([]byte, 4096)} + c, err := net.DialTimeout("tcp", data, time.Second) + if err != nil { + t.Fatal(err) + } + defer c.Close() + _ = c.SetDeadline(time.Now().Add(5 * time.Second)) + lineage := transport.RecoveryLineage{Epoch: 4, SessionID: 1, EndpointVersion: 4, FrontierHint: 1} + if err = transport.WriteMsg(c, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: lineage, LBA: 0, LSN: 1, Data: a})); err != nil { + t.Fatal(err) + } + if err = transport.WriteMsg(c, transport.MsgBarrierReq, transport.EncodeLineage(lineage)); err != nil { + t.Fatal(err) + } + kind, payload, err := transport.ReadMsg(c) + if err != nil || kind != transport.MsgBarrierResp { + t.Fatalf("legacy barrier kind=%d err=%v", kind, err) + } + ack, err := transport.DecodeBarrierResp(payload) + if err != nil || !ack.Lineage.Equivalent(lineage) || ack.AchievedLSN != 1 { + t.Fatalf("legacy barrier %+v %v", ack, err) + } + if mode != "dual-lane" { + return want + } + d, err := net.DialTimeout("tcp", dual, time.Second) + if err != nil { + t.Fatal(err) + } + defer d.Close() + _ = d.SetDeadline(time.Now().Add(5 * time.Second)) + start := make([]byte, 36) + binary.BigEndian.PutUint64(start, 2) + binary.BigEndian.PutUint64(start[8:], 1) + binary.BigEndian.PutUint64(start[16:], 2) + binary.BigEndian.PutUint32(start[24:], 64) + binary.BigEndian.PutUint64(start[28:], 4) + ingressDualWrite(t, d, 1, start) + want[1] = bytes.Repeat([]byte{0xB8}, 4096) + want[2] = bytes.Repeat([]byte{0xC9}, 4096) + for lba := uint32(0); lba < 64; lba++ { + block := make([]byte, 4096) + if lba == 0 { + copy(block, a) + } + if lba == 1 { + copy(block, want[1]) + } + p := make([]byte, 4+4096) + binary.BigEndian.PutUint32(p, lba) + copy(p[4:], block) + ingressDualWrite(t, d, 2, p) + } + ingressDualWrite(t, d, 3, nil) + if err = recovery.WriteWALEntryFrame(d, recovery.WALKindSessionLive, 2, 2, want[2]); err != nil { + t.Fatal(err) + } + ingressDualWrite(t, d, 5, nil) + for i := 0; i < 4; i++ { + var hdr [5]byte + if _, err = io.ReadFull(d, hdr[:]); err != nil { + t.Fatal(err) + } + n := binary.BigEndian.Uint32(hdr[1:]) + if n > 1024 { + t.Fatal("oversize recovery response") + } + p := make([]byte, n) + if _, err = io.ReadFull(d, p); err != nil { + t.Fatal(err) + } + if hdr[0] == 7 { + if len(p) != 20 || binary.BigEndian.Uint64(p) != 2 { + t.Fatal("invalid base batch ack") + } + continue + } + if hdr[0] != 6 || len(p) != 8 || binary.BigEndian.Uint64(p) != 2 { + t.Fatalf("invalid recovery completion %d %x", hdr[0], p) + } + return want + } + t.Fatal("no recovery completion") + return nil +} +func ingressDualWrite(t *testing.T, c net.Conn, kind byte, p []byte) { + t.Helper() + b := make([]byte, 5+len(p)) + b[0] = kind + binary.BigEndian.PutUint32(b[1:], uint32(len(p))) + copy(b[5:], p) + if _, err := c.Write(b); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/cmd/blockvolume/replication_ingress_epoch_test.go b/seaweed-block/cmd/blockvolume/replication_ingress_epoch_test.go new file mode 100644 index 0000000000..f1b0eeeb35 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/replication_ingress_epoch_test.go @@ -0,0 +1,50 @@ +package main + +import ( + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +// Role adoption's table step, on the real ingress: a durable table is +// reloaded (trimmed above the recovered next LSN), a primary role notes its +// epoch at the next LSN, and a promotion over a table a recovery left +// invalid makes it exactly [(epoch, next LSN)]. +func TestIngressPrimaryAdoptionTableStep(t *testing.T) { + root := t.TempDir() + f := flags{dataAddr: "127.0.0.1:0", volumeID: "vol1", durableRoot: root} + store := storage.NewBlockStore(16, 4096) + for i := 0; i < 4; i++ { + if _, err := store.Write(uint32(i), make([]byte, 4096)); err != nil { + t.Fatal(err) + } + } + tb, err := transport.LoadEpochTable(epochTablePath(f), f.volumeID) + if err != nil { + t.Fatal(err) + } + _ = tb.Replace([]transport.EpochRow{{Epoch: 1, FirstLSN: 1}, {Epoch: 2, FirstLSN: 9}}) // 9: above the store's next LSN (5) + + r := newReplicationIngress(f, store) + t.Cleanup(r.Stop) + if rows := r.EpochTable().Rows(); len(rows) != 1 { + t.Fatalf("rows after the load trim %v; want [(1,1)] (the row at 9 names a lost tail)", rows) + } + if err := r.FenceAsPrimaryWithPeers(2, false); err != nil { + t.Fatal(err) + } + if rows := r.EpochTable().Rows(); len(rows) != 2 || rows[1] != (transport.EpochRow{Epoch: 2, FirstLSN: 5}) { + t.Fatalf("rows after adoption at epoch 2 %v; want [(1,1) (2,5)]", rows) + } + + if _, err := r.EpochTable().Invalidate(); err != nil { // a recovery left it without a history + t.Fatal(err) + } + if err := r.FenceAsPrimaryWithPeers(3, false); err != nil { + t.Fatalf("a forced promotion over an invalid table was refused: %v", err) + } + if rows := r.EpochTable().Rows(); len(rows) != 1 || rows[0] != (transport.EpochRow{Epoch: 3, FirstLSN: 5}) || r.EpochTable().Invalid() { + t.Fatalf("rows after a promotion over an invalid table %v (invalid %t); want exactly [(3,5)]", rows, r.EpochTable().Invalid()) + } +} diff --git a/seaweed-block/cmd/blockvolume/replication_ingress_withdrawal_test.go b/seaweed-block/cmd/blockvolume/replication_ingress_withdrawal_test.go new file mode 100644 index 0000000000..10d2ebeff1 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/replication_ingress_withdrawal_test.go @@ -0,0 +1,499 @@ +package main + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "log" + "net" + "os" + "os/exec" + "runtime" + "strings" + "sync" + "sync/atomic" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +// The storage wrapper parks an actual wire-dispatched effect AFTER admission. +// It embeds the real storage implementation; no listener/gate is mocked. +type ingressParkedStore struct { + storage.LogicalStorage + operation string + entered, resume, finished chan struct{} + once, release sync.Once + active atomic.Int32 + closed atomic.Bool +} + +func (s *ingressParkedStore) effect(op string) func() { + if s.closed.Load() { + panic("receiver used released store") + } + s.active.Add(1) + parked := false + if op == s.operation { + s.once.Do(func() { parked = true; close(s.entered); <-s.resume }) + } + return func() { + s.active.Add(-1) + if parked { + close(s.finished) + } + } +} +func (s *ingressParkedStore) ApplyEntry(lba uint32, p []byte, lsn uint64) error { + done := s.effect("apply") + defer done() + return s.LogicalStorage.ApplyEntry(lba, p, lsn) +} +func (s *ingressParkedStore) WriteExtentDirect(lba uint32, p []byte) error { + done := s.effect("base") + defer done() + return s.LogicalStorage.WriteExtentDirect(lba, p) +} +func (s *ingressParkedStore) Sync() (uint64, error) { + done := s.effect("sync") + defer done() + return s.LogicalStorage.Sync() +} +func (s *ingressParkedStore) unblock() { s.release.Do(func() { close(s.resume) }) } +func (s *ingressParkedStore) Close() error { + if s.active.Load() != 0 { + return fmt.Errorf("store still has %d active effects", s.active.Load()) + } + s.closed.Store(true) + return s.LogicalStorage.Close() +} + +// The inherited dual bridge does not expose a join handle. Its caller logs +// AFTER Serve returns; observe that exact connection's exit before releasing +// our store. This is an observed test-owner join, not a production guarantee. +type ingressExitWitness struct { + io.Writer + peer string + once sync.Once + done chan struct{} +} + +func (w *ingressExitWitness) Write(p []byte) (int, error) { + n, e := w.Writer.Write(p) + if strings.Contains(string(p), "replica Serve exit remote="+w.peer+" ") { + w.once.Do(func() { close(w.done) }) + } + return n, e +} +func ingressAwait(t *testing.T, what string, c <-chan struct{}) { + t.Helper() + select { + case <-c: + case <-time.After(4 * time.Second): + t.Fatal(what) + } +} +func ingressPair(t *testing.T) (string, string) { + t.Helper() + for i := 0; i < 100; i++ { + a, e := net.Listen("tcp", "127.0.0.1:0") + if e != nil { + t.Fatal(e) + } + x := a.Addr().String() + y, e := deriveDualLaneAddr(x) + if e != nil { + a.Close() + continue + } + b, e := net.Listen("tcp", y) + a.Close() + if e == nil { + b.Close() + return x, y + } + } + t.Fatal("no available port pair") + return "", "" +} +func ingressFrame(t *testing.T, c net.Conn, k byte, p []byte) { + t.Helper() + b := make([]byte, 5+len(p)) + b[0] = k + binary.BigEndian.PutUint32(b[1:], uint32(len(p))) + copy(b[5:], p) + if _, e := c.Write(b); e != nil { + t.Fatal(e) + } +} +func ingressStart(t *testing.T, c net.Conn) { + t.Helper() + p := make([]byte, 36) + binary.BigEndian.PutUint64(p, 1) + binary.BigEndian.PutUint64(p[8:], 1) + binary.BigEndian.PutUint64(p[16:], 1) + binary.BigEndian.PutUint32(p[24:], 4) + binary.BigEndian.PutUint64(p[28:], 1) + ingressFrame(t, c, 1, p) +} +func ingressBase(t *testing.T, c net.Conn, p []byte) { + t.Helper() + b := make([]byte, 4+len(p)) + copy(b[4:], p) + ingressFrame(t, c, 2, b) +} +func ingressWireClosed(t *testing.T, c net.Conn) { + t.Helper() + _ = c.SetReadDeadline(time.Now().Add(2 * time.Second)) + var b [1]byte + _, err := c.Read(b[:]) + if err == nil { + t.Fatal("unexpected successful wire outcome after withdrawal") + } + if n, ok := err.(net.Error); ok && n.Timeout() { + t.Fatal("wire did not settle") + } + t.Logf("explicit wire failure after withdrawal: %v", err) +} +func ingressClosedPort(t *testing.T, addr string) { + t.Helper() + if err := ingressPortReleased(addr); err != nil { + t.Fatal(err) + } +} + +// ingressPortReleased returns nil once nothing listens on addr any more. +// A connect that succeeds is always a failure. A refused connect is the +// fast path. Some network stacks do not refuse promptly (a filtered or +// forwarded loopback can drop or delay the SYN, so the dial times out +// instead), so any other dial failure is accepted only if addr can be bound +// again, which proves the withdrawn listener released it. +func ingressPortReleased(addr string) error { + c, e := net.DialTimeout("tcp", addr, time.Second) + if e == nil { + c.Close() + return fmt.Errorf("withdrawn endpoint %s accepted a connection", addr) + } + if errors.Is(e, syscall.ECONNREFUSED) { + return nil + } + ln, le := net.Listen("tcp", addr) + if le != nil { + return fmt.Errorf("withdrawn endpoint %s: dial failed without refusal (%v) and the address is still bound (%v)", addr, e, le) + } + _ = ln.Close() + return nil +} + +// Each acquired resource is attached to this owner before the next fallible +// operation. Cleanup unblocks first, joins all started callers, then releases +// storage and restores the logger. Unknown settlement retains both resources. +type ingressTestOwner struct { + t *testing.T + store *ingressParkedStore + ingress *replicationIngress + conn net.Conn + witness *ingressExitWitness + addr, dual, lane string + withdrawalDone chan struct{} + withdrawalErr error + workerID string + cleanupOnce sync.Once + cleanupErr error +} + +func newIngressTestOwner(t *testing.T, operation, lane string) *ingressTestOwner { + t.Helper() + s := &ingressParkedStore{LogicalStorage: storage.NewBlockStore(4, 4096), operation: operation, entered: make(chan struct{}), resume: make(chan struct{}), finished: make(chan struct{})} + o := &ingressTestOwner{t: t, store: s, lane: lane} + t.Cleanup(func() { + if err := o.cleanup(); err != nil { + t.Error(err) + } + }) + o.addr, o.dual = ingressPair(t) + o.ingress = &replicationIngress{addr: o.addr, store: s, dualLane: true} + if err := o.ingress.AdmitAsReplica(1); err != nil { + t.Fatal(err) + } + return o +} +func (o *ingressTestOwner) dial() { + target := o.addr + if o.lane == "dual" { + target = o.dual + } + c, err := net.DialTimeout("tcp", target, time.Second) + if err != nil { + o.t.Fatal(err) + } + o.conn = c // ownership recorded immediately, before deadlines or assertions + _ = c.SetDeadline(time.Now().Add(8 * time.Second)) + if o.lane == "dual" { + o.witness = &ingressExitWitness{Writer: log.Writer(), peer: c.LocalAddr().String(), done: make(chan struct{})} + log.SetOutput(o.witness) + } +} +func (o *ingressTestOwner) withdraw() { + o.withdrawalDone = make(chan struct{}) + id := make(chan string, 1) + go func() { + var b [128]byte + n := runtime.Stack(b[:], false) + id <- strings.Fields(string(b[:n]))[1] + o.withdrawalErr = o.ingress.FenceAsPrimaryWithPeers(2, false) + close(o.withdrawalDone) + }() + o.workerID = <-id +} +func (o *ingressTestOwner) waitWithdrawal() { + ingressAwait(o.t, "withdrawal did not settle", o.withdrawalDone) + if o.withdrawalErr != nil { + o.t.Fatal(o.withdrawalErr) + } +} +func (o *ingressTestOwner) cleanup() error { + o.cleanupOnce.Do(func() { + o.store.unblock() + if o.conn != nil { + _ = o.conn.Close() + } + await := func(c <-chan struct{}, what string) bool { + select { + case <-c: + return true + case <-time.After(4 * time.Second): + o.cleanupErr = fmt.Errorf("UNKNOWN cleanup: %s; store/logger retained", what) + return false + } + } + if o.withdrawalDone != nil && !await(o.withdrawalDone, "withdrawal worker") { + return + } + if o.ingress != nil { + stopped := make(chan struct{}) + go func() { o.ingress.Stop(); close(stopped) }() + if !await(stopped, "ingress Stop") { + return + } + } + if o.witness != nil && !await(o.witness.done, "dual Serve exit") { + return + } + if err := o.store.Close(); err != nil { + o.cleanupErr = err + return + } + if o.witness != nil { + log.SetOutput(o.witness.Writer) + } + if os.Getenv("INGRESS_FAILURE_CASE") != "" { + if o.store.active.Load() != 0 || !o.store.closed.Load() { + o.cleanupErr = fmt.Errorf("cleanup did not release settled store") + return + } + for _, addr := range []string{o.addr, o.dual} { + if e := ingressPortReleased(addr); e != nil { + o.cleanupErr = fmt.Errorf("cleanup port remains open: %w", e) + return + } + } + if o.witness != nil && log.Writer() != o.witness.Writer { + o.cleanupErr = fmt.Errorf("logger not restored") + return + } + fmt.Println("CLEANUP_SETTLED store_closed=true active=0 logger_restored=true ports_closed=true") + } + }) + return o.cleanupErr +} +func (o *ingressTestOwner) parked(payload []byte) { + if o.lane == "legacy" { + l := transport.RecoveryLineage{Epoch: 1, SessionID: 1, EndpointVersion: 1, FrontierHint: 1} + if err := transport.WriteMsg(o.conn, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: l, LBA: 0, LSN: 1, Data: payload})); err != nil { + o.t.Fatal(err) + } + } else { + ingressStart(o.t, o.conn) + ingressBase(o.t, o.conn, payload) + if o.store.operation == "sync" { + ingressFrame(o.t, o.conn, 3, nil) + } + } + ingressAwait(o.t, "storage operation was not admitted", o.store.entered) +} + +// No public wait-arrival seam exists. Observe ONLY this caller's actual +// sync.Cond wait in the production fence, using runtime's diagnostic stack. +// A skip-drain mutant must return (and fail) before we ever release the effect; +// merely closing admission is no longer accepted as a wait witness. +func ingressRequireDrainWait(t *testing.T, o *ingressTestOwner) { + t.Helper() + end := time.Now().Add(4 * time.Second) + for { + select { + case <-o.withdrawalDone: + t.Fatalf("drain skipped: withdrawal returned while admitted effect is held (active=%d)", o.store.active.Load()) + default: + } + b := make([]byte, 1<<20) + n := runtime.Stack(b, true) + for _, stack := range strings.Split(string(b[:n]), "\n\n") { + if strings.HasPrefix(stack, "goroutine "+o.workerID+" ") && + ((strings.Contains(stack, "(*ReplicaListener).fenceAndDrain") && strings.Contains(stack, "sync.(*Cond).Wait")) || + (o.lane == "legacy" && strings.Contains(stack, "(*ReplicaListener).StopHard") && strings.Contains(stack, "sync.(*WaitGroup).Wait"))) { + t.Log("withdrawal caller reached production effect drain/join wait") + return + } + } + if time.Now().After(end) { + t.Fatal("no production drain-wait witness") + } + time.Sleep(time.Millisecond) + } +} +func TestReplicationIngressWithdrawalDrainsAdmittedEffects(t *testing.T) { + for _, lane := range []string{"legacy", "dual"} { + t.Run(lane, func(t *testing.T) { + op := "apply" + if lane == "dual" { + op = "base" + } + o := newIngressTestOwner(t, op, lane) + o.dial() + s, r, c := o.store, o.ingress, o.conn + payload := bytes.Repeat([]byte{0xD3}, 4096) + o.parked(payload) + listener := r.listener + later := bytes.Repeat([]byte{0xF5}, 4096) + if lane == "legacy" { + l := transport.RecoveryLineage{Epoch: 1, SessionID: 1, EndpointVersion: 1, FrontierHint: 1} + if err := transport.WriteMsg(c, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: l, LBA: 1, LSN: 2, Data: later})); err != nil { + t.Fatal(err) + } + } else { + p := make([]byte, 4+len(later)) + binary.BigEndian.PutUint32(p, 1) + copy(p[4:], later) + ingressFrame(t, c, 2, p) + } + o.withdraw() + ingressRequireDrainWait(t, o) + if release, err := listener.EnterDualLane(1); err == nil { + release() + t.Fatal("drain wait did not close admission") + } + if s.active.Load() != 1 { + t.Fatal("effect no longer parked") + } + s.unblock() + ingressAwait(t, "effect did not return", s.finished) + o.waitWithdrawal() + ingressWireClosed(t, c) + if o.witness != nil { + ingressAwait(t, "receiver did not exit", o.witness.done) + } + ingressClosedPort(t, o.addr) + ingressClosedPort(t, o.dual) + if release, e := listener.EnterDualLane(1); e == nil { + release() + t.Fatal("old gate accepted another frame") + } + got, err := s.Read(0) + if err != nil || !bytes.Equal(got, payload) { + t.Fatal("admitted bytes differ", err) + } + got, err = s.Read(1) + if err != nil || !bytes.Equal(got, make([]byte, 4096)) { + t.Fatal("queued mutation reached storage", err) + } + if err = o.cleanup(); err != nil { + t.Fatal(err) + } + t.Log("actual wait witnessed; exact effect drained; wire failed; callers settled before store/logger release") + }) + } +} + +// Inherited sendAck Sync remains outside counted effects. The owner still +// joins the observed caller before releasing store/logger, on every exit. +func TestReplicationIngressDualAckSyncNeedsOwnerSettlement(t *testing.T) { + o := newIngressTestOwner(t, "sync", "dual") + o.dial() + payload := bytes.Repeat([]byte{0xE4}, 4096) + o.parked(payload) + o.withdraw() + o.waitWithdrawal() + if o.store.active.Load() != 1 { + t.Fatal("Sync not held at withdrawal return") + } + select { + case <-o.witness.done: + t.Fatal("receiver exited with Sync held") + default: + } + ingressWireClosed(t, o.conn) + o.store.unblock() + ingressAwait(t, "Sync did not return", o.store.finished) + ingressAwait(t, "receiver did not settle", o.witness.done) + got, err := o.store.Read(0) + if err != nil || !bytes.Equal(got, payload) { + t.Fatal("base bytes differ", err) + } + if err = o.cleanup(); err != nil { + t.Fatal(err) + } + t.Log("INHERITED LIMIT: withdrawal returned with uncounted Sync live; owner joined before release") +} +func TestReplicationIngressCleanupFailureHelper(t *testing.T) { + stage := os.Getenv("INGRESS_FAILURE_CASE") + if stage == "" { + return + } + lane, op := "dual", "base" + if stage == "held-legacy" { + lane, op = "legacy", "apply" + } + if stage == "held-sync" { + op = "sync" + } + o := newIngressTestOwner(t, op, lane) + if stage == "pre-dial" { + t.Fatal("FORCED_FAILURE pre-dial") + } + o.dial() + o.parked(bytes.Repeat([]byte{0x67}, 4096)) + o.withdraw() + if op == "sync" { + o.waitWithdrawal() + } else { + ingressRequireDrainWait(t, o) + } + t.Fatal("FORCED_FAILURE " + stage) +} +func TestReplicationIngressCleanupOnForcedFailure(t *testing.T) { + for _, stage := range []string{"pre-dial", "held-legacy", "held-dual", "held-sync"} { + t.Run(stage, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestReplicationIngressCleanupFailureHelper$", "-test.v") + cmd.Env = append(os.Environ(), "INGRESS_FAILURE_CASE="+stage) + b, err := cmd.CombinedOutput() + var exit *exec.ExitError + if !errors.As(err, &exit) || exit.ExitCode() != 1 || ctx.Err() != nil { + t.Fatalf("forced failure status: %v %s", err, b) + } + out := string(b) + if !strings.Contains(out, "FORCED_FAILURE "+stage) || !strings.Contains(out, "CLEANUP_SETTLED store_closed=true active=0 logger_restored=true ports_closed=true") || strings.Contains(out, "UNKNOWN cleanup") { + t.Fatalf("unsafe failure cleanup: %s", b) + } + t.Logf("%s expected Fatal; owned cleanup settled before process exit:\n%s", stage, b) + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/retry_controller_cleanup_test.go b/seaweed-block/cmd/blockvolume/retry_controller_cleanup_test.go new file mode 100644 index 0000000000..12f765957f --- /dev/null +++ b/seaweed-block/cmd/blockvolume/retry_controller_cleanup_test.go @@ -0,0 +1,130 @@ +package main_test + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func retryControllerInstance(answer string) (int, error) { + var instance, cntlid int + if n, err := fmt.Sscanf(strings.TrimSpace(answer), "instance=%d,cntlid=%d", &instance, &cntlid); err != nil || n != 2 || instance < 0 || cntlid < 0 { + return 0, fmt.Errorf("invalid acquired controller identity %q", answer) + } + return instance, nil +} + +// path is the acquired fabrics instance, never a discovered/global controller. +// The caller retains the fabrics handle until this bounded check completes. +func disconnectRetryController(ctx context.Context, path, nqn string) error { + original, err := os.Stat(path) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return fmt.Errorf("stat acquired controller: %w", err) + } + identity, err := os.ReadFile(filepath.Join(path, "subsysnqn")) + if err != nil { + return fmt.Errorf("read owned identity: %w", err) + } + if strings.TrimSpace(string(identity)) != nqn { + return fmt.Errorf("acquired controller identity changed: %q", identity) + } + if err := os.WriteFile(filepath.Join(path, "delete_controller"), []byte("1"), 0200); err != nil { + return fmt.Errorf("request owned deletion: %w", err) + } + for { + current, err := os.Stat(path) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return fmt.Errorf("verify owned deletion: %w", err) + } + if !os.SameFile(original, current) { + return fmt.Errorf("controller path replaced while awaiting deletion") + } + select { + case <-ctx.Done(): + return fmt.Errorf("owned controller still present: %w", ctx.Err()) + case <-time.After(10 * time.Millisecond): + } + } +} + +func TestRetryControllerCleanupRefusesUnknownIdentity(t *testing.T) { + path := t.TempDir() + marker := filepath.Join(path, "delete_controller") + if err := os.WriteFile(marker, []byte("untouched"), 0600); err != nil { + t.Fatal(err) + } + for _, identity := range []string{"", "another-controller"} { + if identity != "" { + if err := os.WriteFile(filepath.Join(path, "subsysnqn"), []byte(identity), 0600); err != nil { + t.Fatal(err) + } + } + if err := disconnectRetryController(context.Background(), path, "own"); err == nil { + t.Fatal("unknown identity deletion accepted") + } + if got, err := os.ReadFile(marker); err != nil || string(got) != "untouched" { + t.Fatalf("unproved controller changed: %q %v", got, err) + } + } +} + +func TestRetryControllerCleanupAwaitsOwnedRemoval(t *testing.T) { + for _, remove := range []bool{false, true} { + t.Run(fmt.Sprint(remove), func(t *testing.T) { + path := filepath.Join(t.TempDir(), "controller") + if err := os.Mkdir(path, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(path, "subsysnqn"), []byte("own"), 0600); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + joined := make(chan struct{}) + if remove { + go func() { + defer close(joined) + for { + if _, err := os.Stat(filepath.Join(path, "delete_controller")); err == nil { + break + } + select { + case <-ctx.Done(): + return + case <-time.After(time.Millisecond): + } + } + _ = os.RemoveAll(path) + }() + } else { + close(joined) + } + err := disconnectRetryController(ctx, path, "own") + <-joined + if (err == nil) != remove { + t.Fatalf("remove=%t cleanup=%v", remove, err) + } + }) + } +} + +func TestRetryControllerAcquiredIdentity(t *testing.T) { + if got, err := retryControllerInstance("instance=12,cntlid=3\n"); err != nil || got != 12 { + t.Fatalf("identity %d %v", got, err) + } + for _, bad := range []string{"", "instance=-1,cntlid=-1", "instance=3", "garbage"} { + if _, err := retryControllerInstance(bad); err == nil { + t.Fatalf("accepted %q", bad) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/runtime_fence_exit_test.go b/seaweed-block/cmd/blockvolume/runtime_fence_exit_test.go new file mode 100644 index 0000000000..f0dec17775 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/runtime_fence_exit_test.go @@ -0,0 +1,86 @@ +package main + +import ( + "context" + "sync/atomic" + "testing" + "time" +) + +type runtimeFenceStub struct { + fenced atomic.Bool + updates chan struct{} +} + +func (s *runtimeFenceStub) ChunkRuntimeFenced(string) bool { return s.fenced.Load() } +func (s *runtimeFenceStub) ChunkRuntimeFenceUpdates() <-chan struct{} { return s.updates } + +// runtimeFenceWait bounds every receive and join in this test. +const runtimeFenceWait = 5 * time.Second + +// startRuntimeFenceWatch runs watchChunkRuntimeFence with a context it owns. +// Its cleanup, registered before the worker starts, cancels that context and +// joins the worker within runtimeFenceWait, so an earlier failed check never +// strands it. The returned channel closes when the worker returned. +func startRuntimeFenceWatch(t *testing.T, e *processExit, f flags, p chunkRuntimeFenceProvider) <-chan struct{} { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + t.Cleanup(func() { + cancel() + select { + case <-done: + case <-time.After(runtimeFenceWait): + t.Errorf("the runtime-fence watcher did not return within %s of its cancel", runtimeFenceWait) + } + }) + go func() { + defer close(done) + watchChunkRuntimeFence(ctx, e, f, p) + }() + return done +} + +// INV-FE-FENCE-EXIT-001: a runtime HEAD fence of a workspace chunk primary +// chooses the no-restart exit 78 head_fenced through the process owner's one +// chooser, and the watcher returns; nothing is chosen while not fenced, and a +// non-workspace volume never watches. +func TestRuntimeHeadFenceChoosesHeadFencedExit(t *testing.T) { + f := flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v1"} + e := newProcessExit(context.Background()) + stub := &runtimeFenceStub{updates: make(chan struct{}, 1)} + done := startRuntimeFenceWatch(t, e, f, stub) + select { + case out := <-e.decision: + t.Fatalf("an exit was chosen while not fenced: %+v", out) + case <-time.After(100 * time.Millisecond): + } + stub.fenced.Store(true) + stub.updates <- struct{}{} + select { + case out := <-e.decision: + if out != (workspaceExit{code: exitWorkspaceSuperseded, reason: "head_fenced"}) { + t.Fatalf("exit %+v, want 78 head_fenced", out) + } + case <-time.After(runtimeFenceWait): + t.Fatal("no exit chosen after the runtime fence") + } + select { + case <-done: + case <-time.After(runtimeFenceWait): + t.Fatal("the watcher chose the exit but did not return") + } + + plain := newProcessExit(context.Background()) + plainDone := startRuntimeFenceWatch(t, plain, flags{volumeID: "v1"}, stub) + select { + case <-plainDone: // not a workspace chunk primary: returns at once + case <-time.After(runtimeFenceWait): + t.Fatal("a non-workspace volume kept watching") + } + select { + case out := <-plain.decision: + t.Fatalf("a non-workspace volume chose %+v", out) + default: + } +} diff --git a/seaweed-block/cmd/blockvolume/single_filer_test.go b/seaweed-block/cmd/blockvolume/single_filer_test.go new file mode 100644 index 0000000000..ee9ca860d7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/single_filer_test.go @@ -0,0 +1,160 @@ +package main + +import ( + "context" + "errors" + "net" + "sync" + "testing" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb" +) + +type groupFiler struct { + filerpb.UnimplementedSeaweedFilerServer + master string + store *chunkstore.MemFiler +} + +func (f *groupFiler) GetFilerConfiguration(context.Context, *filerpb.GetFilerConfigurationRequest) (*filerpb.GetFilerConfigurationResponse, error) { + return &filerpb.GetFilerConfigurationResponse{Masters: []string{f.master}}, nil +} + +// Exercise the catalog startup probe through the real SWFS gRPC adapter, +// retaining exclusive-create and conditional-update semantics in the fake. +func (f *groupFiler) CreateEntry(ctx context.Context, r *filerpb.CreateEntryRequest) (*filerpb.CreateEntryResponse, error) { + err := f.store.CreateEntry(ctx, r.Directory, r.Entry, r.OExcl) + if errors.Is(err, chunkstore.ErrExists) { + return &filerpb.CreateEntryResponse{ErrorCode: filerpb.FilerError_ENTRY_ALREADY_EXISTS}, nil + } + return &filerpb.CreateEntryResponse{}, groupFilerError(err) +} +func (f *groupFiler) UpdateEntry(ctx context.Context, r *filerpb.UpdateEntryRequest) (*filerpb.UpdateEntryResponse, error) { + return &filerpb.UpdateEntryResponse{}, groupFilerError(f.store.UpdateEntry(ctx, r.Directory, r.Entry, r.ExpectedExtended)) +} +func (f *groupFiler) LookupDirectoryEntry(ctx context.Context, r *filerpb.LookupDirectoryEntryRequest) (*filerpb.LookupDirectoryEntryResponse, error) { + e, err := f.store.LookupEntry(ctx, r.Directory, r.Name) + return &filerpb.LookupDirectoryEntryResponse{Entry: e}, groupFilerError(err) +} +func (f *groupFiler) ListEntries(r *filerpb.ListEntriesRequest, stream grpc.ServerStreamingServer[filerpb.ListEntriesResponse]) error { + entries, err := f.store.ListEntries(stream.Context(), r.Directory, r.Prefix, r.StartFromFileName, r.Limit) + if err != nil { + return groupFilerError(err) + } + for _, e := range entries { + if err := stream.Send(&filerpb.ListEntriesResponse{Entry: e}); err != nil { + return err + } + } + return nil +} +func (f *groupFiler) DeleteEntry(ctx context.Context, r *filerpb.DeleteEntryRequest) (*filerpb.DeleteEntryResponse, error) { + if r.IsRecursive { + return nil, status.Error(codes.InvalidArgument, "recursive delete not supported by this fixture") + } + err := f.store.DeleteEntry(ctx, r.Directory, r.Name, r.ExpectedExtended) + // MemFiler does not materialize parent directories on child creation. + if errors.Is(err, chunkstore.ErrNotFound) { + err = nil + } + return &filerpb.DeleteEntryResponse{}, groupFilerError(err) +} +func groupFilerError(err error) error { + switch { + case err == nil: + return nil + case errors.Is(err, chunkstore.ErrPrecondition): + return status.Error(codes.FailedPrecondition, err.Error()) + case errors.Is(err, chunkstore.ErrNotFound): + return status.Error(codes.NotFound, err.Error()) + default: + return status.Error(codes.Internal, err.Error()) + } +} + +type groupMaster struct { + masterpb.UnimplementedSeaweedServer + filers []string + mu sync.Mutex + leader string +} + +func (m *groupMaster) GetMasterConfiguration(context.Context, *masterpb.GetMasterConfigurationRequest) (*masterpb.GetMasterConfigurationResponse, error) { + m.mu.Lock() + defer m.mu.Unlock() + return &masterpb.GetMasterConfigurationResponse{Leader: m.leader}, nil +} + +func (m *groupMaster) ListClusterNodes(context.Context, *masterpb.ListClusterNodesRequest) (*masterpb.ListClusterNodesResponse, error) { + r := &masterpb.ListClusterNodesResponse{} + for _, a := range m.filers { + r.ClusterNodes = append(r.ClusterNodes, &masterpb.ListClusterNodesResponse_ClusterNode{Address: a}) + } + return r, nil +} + +func serve(t *testing.T, register func(*grpc.Server)) string { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + register(srv) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + return lis.Addr().String() +} + +// blockvolume's chunk wiring runs the single-filer check at startup: the +// configured filer listed as the one filer passes; a group with a second +// filer is refused. +func TestChunkWiringRefusesAMultiFilerGroup(t *testing.T) { + for _, c := range []struct { + name string + other []string + ok bool + }{ + {"one filer", nil, true}, + {"two filers", []string{"10.0.0.2:8888"}, false}, + } { + t.Run(c.name, func(t *testing.T) { + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + filer := lis.Addr().String() + _, fport, _ := net.SplitHostPort(filer) + self := "127.0.0.1:8888." + fport // the filer as a master lists it + master := &groupMaster{filers: append([]string{self}, c.other...)} + m := serve(t, func(s *grpc.Server) { + masterpb.RegisterSeaweedServer(s, master) + }) + _, mport, _ := net.SplitHostPort(m) + master.mu.Lock() + master.leader = "127.0.0.1:9333." + mport + master.mu.Unlock() + srv := grpc.NewServer() + filerpb.RegisterSeaweedFilerServer(srv, &groupFiler{master: "127.0.0.1:9333." + mport, store: chunkstore.NewMemFiler()}) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + w, err := newChunkWiring(chunkFlags{filer: filer, path: defaultChunkPath}, nil) + if c.ok { + if err != nil { + t.Fatalf("one filer refused: %v", err) + } + _ = w.close() + return + } + if !errors.Is(err, chunkstore.ErrNotSingleFiler) { + t.Fatalf("two filers: %v; want chunkstore.ErrNotSingleFiler", err) + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/snapshot_filer_boundary_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_filer_boundary_integration_test.go new file mode 100644 index 0000000000..afa393b799 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_filer_boundary_integration_test.go @@ -0,0 +1,229 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "fmt" + "io" + "net" + "net/http" + "net/http/httputil" + "net/url" + "os" + "path" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +// snapshotFilerBoundary forwards the stock filer API unchanged. One applied +// write's reply is held until the test kills the holder. Thus the receipt +// proves an actual Begin, object create or Commit, independent of a delay. +// Assumptions: one snapshot at a time, capture timer/schedule disabled, no GC. +// Writers enumerated: UpdateEntry(HEAD Begin/Commit), CreateEntry(pool). +// All other writers/readers pass through; pre-restart HEAD uses the backend. +type snapshotFilerBoundary struct { + filerpb.UnimplementedSeaweedFilerServer + backend filerpb.SeaweedFilerClient + dir string + id layout.VolumeID + mu sync.Mutex + kind, name string + reached chan struct{} + release chan struct{} + // left is closed when the held call returns, by the test's release or + // by its caller giving up (its context done; leftByCaller says which). + left chan struct{} + leftByCaller bool + // heldCtx is the held call's own context: its caller giving up is read + // from it directly, not from the handler having run since. + heldCtx context.Context + hit bool +} + +func newSnapshotFilerBoundary(t *testing.T, cluster *w4WeedCluster) *snapshotFilerBoundary { + t.Helper() + conn, err := grpc.NewClient(cluster.filerGRPC, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + p := &snapshotFilerBoundary{backend: filerpb.NewSeaweedFilerClient(conn)} + _, gp, _ := net.SplitHostPort(cluster.filerGRPC) + listener, err := net.Listen("tcp", net.JoinHostPort(testListenHost(), gp)) + if err != nil { + t.Fatal(err) + } + backendURL, err := url.Parse("http://" + cluster.filerHTTP) + if err != nil { + t.Fatal(err) + } + _, hp, _ := net.SplitHostPort(cluster.filerHTTP) + httpListener, err := net.Listen("tcp", net.JoinHostPort(testListenHost(), hp)) + if err != nil { + t.Fatal(err) + } + httpServer := &http.Server{Handler: httputil.NewSingleHostReverseProxy(backendURL), ReadHeaderTimeout: 10 * time.Second} + httpDone := make(chan struct{}) + go func() { defer close(httpDone); _ = httpServer.Serve(httpListener) }() + server := grpc.NewServer() + filerpb.RegisterSeaweedFilerServer(server, p) + done := make(chan struct{}) + go func() { defer close(done); _ = server.Serve(listener) }() + t.Cleanup(func() { + p.unblock() + server.Stop() + _ = listener.Close() + <-done + _ = httpServer.Close() + <-httpDone + _ = conn.Close() + }) + cluster.filerGRPC = listener.Addr().String() + cluster.filerHTTP = httpListener.Addr().String() + return p +} + +func (p *snapshotFilerBoundary) arm(kind, name string) <-chan struct{} { + p.mu.Lock() + defer p.mu.Unlock() + p.kind, p.name = kind, name + p.reached = make(chan struct{}) + p.release = make(chan struct{}) + p.left = make(chan struct{}) + p.leftByCaller = false + p.heldCtx = nil + p.hit = false + return p.reached +} + +// stillHeld reports whether the held call is still waiting (its caller has +// not given up), with why it left otherwise. +func (p *snapshotFilerBoundary) stillHeld() (bool, string) { + p.mu.Lock() + left, ctx := p.left, p.heldCtx + p.mu.Unlock() + if left == nil || ctx == nil { + return false, "nothing was held" + } + // The call's own context first: its caller can give up before the + // handler is scheduled to notice, which would leave left open. + if err := ctx.Err(); err != nil { + return false, fmt.Sprintf("its caller gave up (%v)", err) + } + select { + case <-left: + return false, "it was released" + default: + return true, "" + } +} +func (p *snapshotFilerBoundary) unblock() { + p.mu.Lock() + defer p.mu.Unlock() + if p.release != nil { + close(p.release) + p.release = nil + } +} +func (p *snapshotFilerBoundary) after(ctx context.Context, dir string, entry *filerpb.Entry) { + p.mu.Lock() + if p.hit || p.reached == nil || entry == nil || os.Getenv("E1_TEST_SKIP_BOUNDARY") == "1" { + p.mu.Unlock() + return + } + match := p.kind == "OBJECT" && path.Dir(dir) == path.Join(p.dir, "pool") + if dir == p.dir && entry.Name == layout.HeadName { + h, err := chunkstore.DecodeLayoutHeadEntry(entry, p.id) + if err == nil { + _, named := h.Snapshots[p.name] + match = (p.kind == "BEGIN" && h.Activity.Kind == layout.ActSnap && !named) || (p.kind == "COMMIT" && named) + } + } + if !match { + p.mu.Unlock() + return + } + p.hit = true + p.heldCtx = ctx + close(p.reached) + release, left := p.release, p.left + p.mu.Unlock() + byCaller := false + select { + case <-release: + case <-ctx.Done(): + byCaller = true + } + p.mu.Lock() + p.leftByCaller = byCaller + p.mu.Unlock() + close(left) +} +func (p *snapshotFilerBoundary) head(t *testing.T) layout.Head { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + r, err := p.backend.LookupDirectoryEntry(ctx, &filerpb.LookupDirectoryEntryRequest{Directory: p.dir, Name: layout.HeadName}) + if err != nil { + t.Fatal(err) + } + h, err := chunkstore.DecodeLayoutHeadEntry(r.Entry, p.id) + if err != nil { + t.Fatal(err) + } + return h +} +func (p *snapshotFilerBoundary) LookupDirectoryEntry(ctx context.Context, r *filerpb.LookupDirectoryEntryRequest) (*filerpb.LookupDirectoryEntryResponse, error) { + return p.backend.LookupDirectoryEntry(ctx, r) +} +func (p *snapshotFilerBoundary) CreateEntry(ctx context.Context, r *filerpb.CreateEntryRequest) (*filerpb.CreateEntryResponse, error) { + out, err := p.backend.CreateEntry(ctx, r) + if err == nil && out.GetErrorCode() == filerpb.FilerError_OK && out.GetError() == "" { + p.after(ctx, r.Directory, r.Entry) + } + return out, err +} +func (p *snapshotFilerBoundary) UpdateEntry(ctx context.Context, r *filerpb.UpdateEntryRequest) (*filerpb.UpdateEntryResponse, error) { + out, err := p.backend.UpdateEntry(ctx, r) + if err == nil { + p.after(ctx, r.Directory, r.Entry) + } + return out, err +} +func (p *snapshotFilerBoundary) DeleteEntry(ctx context.Context, r *filerpb.DeleteEntryRequest) (*filerpb.DeleteEntryResponse, error) { + return p.backend.DeleteEntry(ctx, r) +} +func (p *snapshotFilerBoundary) AssignVolume(ctx context.Context, r *filerpb.AssignVolumeRequest) (*filerpb.AssignVolumeResponse, error) { + return p.backend.AssignVolume(ctx, r) +} +func (p *snapshotFilerBoundary) LookupVolume(ctx context.Context, r *filerpb.LookupVolumeRequest) (*filerpb.LookupVolumeResponse, error) { + return p.backend.LookupVolume(ctx, r) +} +func (p *snapshotFilerBoundary) GetFilerConfiguration(ctx context.Context, r *filerpb.GetFilerConfigurationRequest) (*filerpb.GetFilerConfigurationResponse, error) { + return p.backend.GetFilerConfiguration(ctx, r) +} +func (p *snapshotFilerBoundary) ListEntries(r *filerpb.ListEntriesRequest, s grpc.ServerStreamingServer[filerpb.ListEntriesResponse]) error { + stream, err := p.backend.ListEntries(s.Context(), r) + if err != nil { + return err + } + for { + v, err := stream.Recv() + if err == io.EOF { + return nil + } + if err != nil { + return err + } + if err = s.Send(v); err != nil { + return err + } + } +} diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go new file mode 100644 index 0000000000..5292143565 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go @@ -0,0 +1,255 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "fmt" + "math/rand" + "sync" + "testing" + "time" +) + +// awaitAbsent polls target's chunk status every 10 ms until ok holds for its +// count of chunks not yet local, and returns that count. A volume that was +// already fully local before ok held fails the test: the moment was missed. +func (env *handoffEnv) awaitAbsent(t *testing.T, target, what string, bound time.Duration, ok func(absent int) bool) int { + t.Helper() + b := env.hosts["n-"+target] + began := time.Now() + last := -1 + for time.Since(began) < bound { + absent := kzReadStats(t, b).AbsentChunks + if absent != last { + t.Logf("%s at +%v (waiting for %s): %d chunks absent", target, time.Since(began).Round(time.Millisecond), what, absent) + last = absent + } + if ok(absent) { + return absent + } + if absent == 0 { + t.Fatalf("%s hydrated before %s was seen (the restore is too small to catch it)", target, what) + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("%s: %s not seen within %v (last %d chunks absent)", target, what, bound, last) + return -1 +} + +// requireBlocksOf reads every block of img on the host and requires each to +// equal img (whole 4 KiB blocks compared byte for byte). +func (env *handoffEnv) requireBlocksOf(t *testing.T, hostID string, img map[uint64][]byte) { + t.Helper() + c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN) + defer c.close() + for lba, want := range img { + if got := c.read(t, lba, 4096); string(got) != string(want) { + t.Fatalf("%s: block %d differs from what was written", hostID, lba) + } + } +} + +// denseImage fills every block of the given chunks with incompressible +// bytes (seeded by tag and LBA), so that their chunks are full size in the +// store and a restore of them takes measurable time at the driver's rate. +func denseImage(tag string, chunks []uint64) map[uint64][]byte { + img := map[uint64][]byte{} + var seed int64 + for _, c := range tag { + seed = seed*31 + int64(c) + } + for _, c := range chunks { + for i := uint64(0); i < ladderChunkBlocks; i++ { + lba := c*ladderChunkBlocks + i + b := make([]byte, 4096) + rand.New(rand.NewSource(seed ^ int64(lba))).Read(b) + img[lba] = b + } + } + return img +} + +// subsetOf returns the blocks of img in the given chunks. +func subsetOf(img map[uint64][]byte, chunks []uint64) map[uint64][]byte { + in := map[uint64]bool{} + for _, c := range chunks { + in[c] = true + } + out := map[uint64][]byte{} + for lba, b := range img { + if in[lba/ladderChunkBlocks] { + out[lba] = b + } + } + return out +} + +// startTarget starts target's blockvolume and waits until it serves. +func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon { + t.Helper() + b := env.hosts["n-"+target] + d := env.h.start(t, name, env.h.volume, env.volArgsFor(b)...) + waitC3RecoveryPrimary(t, d, b.status, target) + poll(t, 60*time.Second, fmt.Sprintf("%s never reported its frontend ready", target), func() bool { + return volumeFrontendReady(b.status, target) + }) + return d +} + +// fillReader reads one block of each of its chunks, in order, on its own +// connection: v1 fills a restore target only on access, so this is the fill +// the test kills into. It stops at its first error (the kill, or a failure +// before it, which state reports) or at stop, which waits for it. Its stop +// also runs at the test's cleanup, so a failure before the explicit stop +// still ends and joins the reader. +type fillReader struct { + mu sync.Mutex + reads int64 + err error + finished bool + quit chan struct{} + done chan struct{} + close func() + once sync.Once +} + +func (env *handoffEnv) readConcurrently(t *testing.T, target string, chunks []uint64) *fillReader { + t.Helper() + c := dialNVMe(t, env.hosts["n-"+target].nvme, plannedHandoffNQN) + r := &fillReader{quit: make(chan struct{}), done: make(chan struct{}), close: c.close} + t.Cleanup(r.stop) + go func() { + defer close(r.done) + for _, ch := range chunks { + select { + case <-r.quit: + return + default: + } + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + _, err := c.tryRead(ch*ladderChunkBlocks, 4096) + r.mu.Lock() + if err != nil { + r.err = err + } else { + r.reads++ + } + r.mu.Unlock() + if err != nil { + return + } + } + r.mu.Lock() + r.finished = true + r.mu.Unlock() + }() + return r +} + +// progress is the reader's state against baseline absent chunks and absent now. +func (r *fillReader) progress(baseline, absent int) fillProgress { + r.mu.Lock() + defer r.mu.Unlock() + return fillProgress{baseline: baseline, absent: absent, reads: r.reads, readerErr: r.err, finished: r.finished} +} + +func (r *fillReader) stop() { + r.once.Do(func() { + close(r.quit) + r.close() + <-r.done + }) +} + +// awaitFill waits until fillWitness accepts the reader's progress on target +// (a fill observably running) and fails the test with the last reason when +// it does not within bound. +func (env *handoffEnv) awaitFill(t *testing.T, target string, r *fillReader, baseline int, bound time.Duration) fillProgress { + t.Helper() + var p fillProgress + var why error + for end := time.Now().Add(bound); ; time.Sleep(20 * time.Millisecond) { + p = r.progress(baseline, kzReadStats(t, env.hosts["n-"+target]).AbsentChunks) + if why = fillWitness(p); why == nil { + return p + } + if p.readerErr != nil || p.finished || time.Now().After(end) { + t.Fatalf("%s: no running fill to kill into within %v: %v (%+v)", target, bound, why, p) + } + } +} + +// TestSnapshotLadderC3KilledHydrating: a restore of a snapshot of 32 full +// chunks of incompressible data into v2 (128 MiB), its blockvolume killed +// (SIGKILL) while chunks are being made local. v1 fills a restore target only +// on access, so a reader drives the fill. +// +// 1. Killed with some chunks local and some not, then started again (fill +// progress not yet written at a checkpoint may be lost: those chunks +// are fetched again). Every other chunk is read back: each is the +// snapshot's (a partly filled chunk is never served). +// 2. The guest writes (acknowledged); killed again while a fill is running +// and restarted, every acknowledged write reads back. +// 3. The guest writes once more and every chunk is made local (no chunk +// absent). +// v2 holds the snapshot with every acknowledged write over it, read back +// in full, and the source's snapshot, restored again into v3, is +// unchanged (none of v2's writes in it). +func TestSnapshotLadderC3KilledHydrating(t *testing.T) { + env := startLadderEnv(t, "v2", "v3") + var chunks []uint64 + for c := uint64(0); c < 32; c++ { + chunks = append(chunks, c) + } + src := denseImage("c3ksrc", chunks) + env.writeImage(t, "s1", src) + env.snapshot(t, "s1", "v1", "base") + + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "base", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + target := env.startTarget(t, "v2", "blockvolume-v2") + + // (1) killed mid-fill + partly := func(absent int) bool { return absent > 0 && absent < len(chunks) } + reader := env.readConcurrently(t, "v2", chunks) + absent := env.awaitAbsent(t, "v2", "a partly filled volume", 120*time.Second, partly) + if p := reader.progress(len(chunks), absent); p.readerErr != nil { + t.Fatalf("the first fill's reader failed before the kill: %v", p.readerErr) + } + target.kill(t) + reader.stop() + t.Logf("killed with %d of %d chunks absent", absent, len(chunks)) + target = env.startTarget(t, "v2", "blockvolume-v2-after-fill-kill") + // Fill progress is written at the store's next checkpoint, so a kill + // may lose some or all of it (standalone-deployment.md, restore step 4): + // such chunks are absent again and are fetched again on their next read. + t.Logf("after the restart %d of %d chunks are absent", kzReadStats(t, env.hosts["n-v2"]).AbsentChunks, len(chunks)) + var even []uint64 + for c := uint64(0); c < 32; c += 2 { + even = append(even, c) + } + env.requireBlocksOf(t, "n-v2", subsetOf(src, even)) // no partly filled chunk is served + + // (2) written, then killed again while a fill is running + w1 := ladderImage("c3kw1", []uint64{3, 17, 50}, 3) + env.writeImage(t, "n-v2", w1) + var odd []uint64 + for c := uint64(1); c < 32; c += 2 { + odd = append(odd, c) + } + baseline := kzReadStats(t, env.hosts["n-v2"]).AbsentChunks + reader = env.readConcurrently(t, "v2", odd) + p := env.awaitFill(t, "v2", reader, baseline, 60*time.Second) + target.kill(t) + reader.stop() + t.Logf("killed again with a fill running: %d absent (%d when its reader started), %d reads done", p.absent, p.baseline, p.reads) + target = env.startTarget(t, "v2", "blockvolume-v2-after-write-kill") + env.requireBlocksOf(t, "n-v2", w1) // every acknowledged write survived the kill + + // (3) every chunk made local + w2 := ladderImage("c3kw2", []uint64{17, 44, 60}, 2) // not chunk 40: requireEdges keeps it untouched + env.writeImage(t, "n-v2", w2) + env.hydrate(t, "v2") + env.requireImage(t, "n-v2", mergeImages(src, w1, w2)) + env.restoreChecked(t, "base", "v3", src, w1, w2) +} diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go new file mode 100644 index 0000000000..b27db46d68 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_d_integration_test.go @@ -0,0 +1,205 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "path" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// Rung D of the snapshot ladder: deletes. D1-D3 are the logical delete: a +// deleted snapshot leaves every other snapshot restorable, whichever one is +// deleted (the newest, a middle one, one whose content recurs later). No +// collector runs in them (a delete only marks the snapshot and frees its +// name), so they prove nothing about reclamation. D4 runs the collector and +// measures what it reclaims. +// +// deleteSnapshot deletes vol's snapshot name and checks the answer names it. +func (env *handoffEnv) deleteSnapshot(t *testing.T, vol, name string) { + t.Helper() + out, _ := env.h.command(t, "ops", "chunk", "snapshot-delete", "--master", env.h.masterAddr, "--volume", vol, "--name", name, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + var body struct { + VolumeID string `json:"volumeID"` + Name string `json:"name"` + } + if err := json.Unmarshal([]byte(out), &body); err != nil || body.Name != name { + t.Fatalf("delete %s of %s: %v\n%s", name, vol, err, out) + } +} + +// holderDeleteSnapshot deletes vol's snapshot name through its holder's +// control route (POST /chunk/snapshot/delete on hostID's status listener), +// which runs the holder's cleaning pass right after the delete. It returns +// the HTTP status and body. +// +// A snapshot delete is one conditional update of HEAD. The holder's +// cleaning (kicked by the previous delete) also updates HEAD, so a delete +// that read HEAD just before can lose its update ("HEAD generation moved") +// and change nothing; ops chunk snapshot-delete reports that as a retryable +// conflict. Only that answer is retried, within 30 s; any other is returned. +func (env *handoffEnv) holderDeleteSnapshot(t *testing.T, hostID, vol, name string) (int, string) { + t.Helper() + body, _ := json.Marshal(map[string]string{"volumeID": vol, "name": name}) + c := &http.Client{Timeout: 2 * time.Minute} + for end := time.Now().Add(30 * time.Second); ; time.Sleep(200 * time.Millisecond) { + resp, err := c.Post("http://"+env.hosts[hostID].status+"/chunk/snapshot/delete", "application/json", strings.NewReader(string(body))) + if err != nil { + t.Fatal(err) + } + out, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + resp.Body.Close() + if resp.StatusCode == http.StatusOK || !strings.Contains(string(out), "HEAD generation moved") || time.Now().After(end) { + return resp.StatusCode, string(out) + } + t.Logf("holder delete of %s lost its HEAD update to a concurrent change; retrying: %s", name, out) + } +} + +// poolObjects counts the chunk objects in vol's pool (every shard +// directory): what the volume stores, whatever names it. +func (env *handoffEnv) poolObjects(t *testing.T, vol string) int { + t.Helper() + id, err := layout.ParseVolumeID(env.layoutID(vol)) + if err != nil { + t.Fatal(err) + } + pool := path.Join(env.chunkPath, layout.VolumeDir(vol, id), layout.PoolDir) + n := 0 + for shard := range env.filerNames(t, pool) { + n += len(env.filerNames(t, path.Join(pool, shard))) + } + return n +} + +// requireSnapshotNames checks vol's snapshot list is exactly names, in order. +func (env *handoffEnv) requireSnapshotNames(t *testing.T, vol string, names ...string) { + t.Helper() + list := env.snapshots(t, vol, "") + ok := len(list) == len(names) + for i := 0; ok && i < len(list); i++ { + ok = list[i].Name == names[i] + } + if !ok { + t.Fatalf("snapshots of %s: %+v; want exactly %v", vol, list, names) + } +} + +// restoreChecked restores snap of v1 into target until its status says +// independent and checks it equals img, with every block of later that img +// does not hold reading zero. +func (env *handoffEnv) restoreChecked(t *testing.T, snap, target string, img map[uint64][]byte, later ...map[uint64][]byte) { + t.Helper() + env.restoreInto(t, "v1", snap, target) + env.hydrate(t, target) + env.requireImage(t, "n-"+target, img, later...) +} + +// TestSnapshotLadderD1DeleteTheNewest: three snapshots over overlapping +// chunks; the newest is deleted; the other two restore as they were. +func TestSnapshotLadderD1DeleteTheNewest(t *testing.T) { + env := startLadderEnv(t, "v2", "v3") + img1 := ladderImage("d1one", []uint64{0, 4}, 4) + img2 := ladderImage("d1two", []uint64{4, 8}, 3) + img3 := ladderImage("d1three", []uint64{0, 8}, 2) + for i, img := range []map[uint64][]byte{img1, img2, img3} { + env.writeImage(t, "s1", img) + env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1)) + } + env.deleteSnapshot(t, "v1", "s3") + env.requireSnapshotNames(t, "v1", "s1", "s2") + env.restoreChecked(t, "s1", "v2", img1, img2, img3) + env.restoreChecked(t, "s2", "v3", mergeImages(img1, img2), img3) +} + +// TestSnapshotLadderD2DeleteAMiddleOne: four snapshots, each sharing chunks +// with its neighbours; the second is deleted; the first, the third and the +// fourth restore as they were. No collector runs: whether the deleted one's +// chunks that a neighbour still uses would survive collection is not tested +// here. +func TestSnapshotLadderD2DeleteAMiddleOne(t *testing.T) { + env := startLadderEnv(t, "v2", "v3", "v4") + img1 := ladderImage("d2one", []uint64{0, 2}, 4) + img2 := ladderImage("d2two", []uint64{2, 5}, 3) // chunk 2 shared with s1, chunk 5 kept by s3 + img3 := ladderImage("d2three", []uint64{0, 9}, 2) + img4 := ladderImage("d2four", []uint64{9, 12}, 2) + for i, img := range []map[uint64][]byte{img1, img2, img3, img4} { + env.writeImage(t, "s1", img) + env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1)) + } + env.deleteSnapshot(t, "v1", "s2") + env.requireSnapshotNames(t, "v1", "s1", "s3", "s4") + env.restoreChecked(t, "s1", "v2", img1, img2, img3, img4) + env.restoreChecked(t, "s3", "v3", mergeImages(img1, img2, img3), img4) + env.restoreChecked(t, "s4", "v4", mergeImages(img1, img2, img3, img4)) +} + +// TestSnapshotLadderD3DeleteWhenContentRecurs: the A, B, A volume of A4 +// (one block holds A, then B, then A again, a snapshot after each), then the +// live block is overwritten with C; the first snapshot is deleted; the +// third, whose content equals the first's, and the second restore as they +// were, not as HEAD is now. No collector runs here: this is the logical +// delete and restore, not the reclamation of a recurring chunk. +func TestSnapshotLadderD3DeleteWhenContentRecurs(t *testing.T) { + env := startLadderEnv(t, "v2", "v3") + a, b, c := pattern("ladder-d3-blk-A!"), pattern("ladder-d3-blk-B!"), pattern("ladder-d3-blk-C!") + for i, content := range [][]byte{a, b, a} { + env.writeBlock(t, "s1", 7, content) + env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1)) + } + env.writeBlock(t, "s1", 7, c) // HEAD now differs from every snapshot + env.deleteSnapshot(t, "v1", "s1") + env.requireSnapshotNames(t, "v1", "s2", "s3") + env.restoreChecked(t, "s3", "v2", map[uint64][]byte{7: a}) + env.restoreChecked(t, "s2", "v3", map[uint64][]byte{7: b}) +} + +// TestSnapshotLadderD4DeleteAllButOneThenCollect: three snapshots, each +// overwriting the same four chunks; the third and then the second are +// deleted through the holder, whose cleaning pass runs right after each +// delete. The third's chunks are still HEAD's, so deleting it frees nothing; +// the second's four chunks are named by nothing after its delete, and the +// cleaning removes exactly those from the pool. No data is lost: HEAD reads +// the newest content and the remaining snapshot restores as it was. +func TestSnapshotLadderD4DeleteAllButOneThenCollect(t *testing.T) { + env := startLadderEnv(t, "v2") + chunks := []uint64{0, 1, 2, 3} + imgs := []map[uint64][]byte{ladderImage("d4one", chunks, 4), ladderImage("d4two", chunks, 4), ladderImage("d4three", chunks, 4)} + for i, img := range imgs { + env.writeImage(t, "s1", img) + env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1)) + } + stored := env.poolObjects(t, "v1") + t.Logf("after three snapshots the pool holds %d chunk objects", stored) + + collect := func(name string, freed int) { + t.Helper() + if code, out := env.holderDeleteSnapshot(t, "s1", "v1", name); code != http.StatusOK { + t.Fatalf("holder delete of %s: status %d: %s", name, code, out) + } + want := stored - freed + end := time.Now().Add(60 * time.Second) + got := env.poolObjects(t, "v1") + for got != want && time.Now().Before(end) { + time.Sleep(500 * time.Millisecond) + got = env.poolObjects(t, "v1") + } + if got != want { + t.Fatalf("after deleting %s the pool holds %d chunk objects; want %d (%d freed)", name, got, want, freed) + } + stored = got + } + collect("s3", 0) // its chunks are HEAD's + collect("s2", len(chunks)) // named by nothing now + env.requireSnapshotNames(t, "v1", "s1") + env.requireImage(t, "s1", imgs[2]) + env.restoreChecked(t, "s1", "v2", imgs[0], imgs[1], imgs[2]) +} diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go new file mode 100644 index 0000000000..a816c0db81 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_e_integration_test.go @@ -0,0 +1,213 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "path" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// Rung E: kill the real holder at applied Begin, object and Commit writes. +// The filer's reply is held until SIGKILL, and HEAD is observed before restart. +// Per-write kernel controls remain TestSnapshotSession_InterruptAtEveryStep. + +// filerNames lists the entry names (unescaped) of a filer directory, read +// straight from the filer (not through the product); a missing directory +// lists as empty. +func (env *handoffEnv) filerNames(t *testing.T, dir string) map[string]bool { + t.Helper() + c := &http.Client{Timeout: 10 * time.Second} + names := map[string]bool{} + for last := ""; ; { + req, _ := http.NewRequest("GET", "http://"+env.cluster.filerHTTP+dir+"/?limit=1000&lastFileName="+url.QueryEscape(last), nil) + req.Header.Set("Accept", "application/json") + resp, err := c.Do(req) + if err != nil { + t.Fatal(err) + } + var page struct { + Entries []struct { + FullPath string `json:"FullPath"` + } `json:"Entries"` + LastFileName string `json:"LastFileName"` + ShouldDisplayLoadMore bool `json:"ShouldDisplayLoadMore"` + } + err = json.NewDecoder(resp.Body).Decode(&page) + resp.Body.Close() + if resp.StatusCode == http.StatusNotFound { + return names + } + if err != nil || resp.StatusCode != http.StatusOK { + t.Fatalf("filer listing of %s: status %d %v", dir, resp.StatusCode, err) + } + for _, e := range page.Entries { + name, err := url.PathUnescape(path.Base(e.FullPath)) + if err != nil { + t.Fatalf("filer entry %q: %v", e.FullPath, err) + } + names[name] = true + } + if !page.ShouldDisplayLoadMore || page.LastFileName == "" || page.LastFileName == last { + return names + } + last = page.LastFileName + } +} + +// TestSnapshotLadderE1CrashDuringASnapshot retains the data/replay/restore +// oracle, but reaches each crash boundary causally through the stock filer. +// A missed boundary is inconclusive, never a successful BEFORE-only campaign. +func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) { + boundaries := []string{"BEGIN", "OBJECT", "COMMIT"} + var targets []string + for i := 0; i <= len(boundaries); i++ { + targets = append(targets, fmt.Sprintf("v%d", i+2)) + } + if testListenHost() != "127.0.0.1" { + t.Fatal("causal filer fixture requires loopback") + } + var boundary *snapshotFilerBoundary + cluster := startWorkspaceWeedWith(t, t.TempDir(), w4WeedOpts{VolumeSizeLimitMB: 256, VolumeMax: 32, + FilerBind: "127.0.0.2", FilerFront: func(c *w4WeedCluster) { boundary = newSnapshotFilerBoundary(t, c) }}) + env := startHandoffEnvOnCluster(t, 1, targets, procedureTLSConfig(), false, cluster) + id, err := layout.ParseVolumeID(env.layoutID("v1")) + if err != nil { + t.Fatal(err) + } + boundary.id = id + boundary.dir = path.Join(env.chunkPath, layout.VolumeDir("v1", id)) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + holder := env.start(t, "blockvolume-v1", "s1") + e := env.adopt(t, holder, "s1") + marker := pattern("ladder-e1-marker") + env.writeBlock(t, "s1", 0, marker) + + type result struct { + out, errOut string + code int + err error + } + var images []map[uint64][]byte // what each round's snapshot must hold + cum := map[uint64][]byte{0: marker} + steps := map[string]int{} + for k, kind := range boundaries { + img := ladderImage(fmt.Sprintf("e1r%d", k), []uint64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, 3) + env.writeImage(t, "s1", img) + cum = mergeImages(cum, img) + name, req := fmt.Sprintf("e1-%d", k), fmt.Sprintf("r-e1-%d", k) + + reached := boundary.arm(kind, name) + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) + done := make(chan result, 1) + go func() { + out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status, + "--name", name, "--request-id", req) + done <- result{out, errOut, code, err} + }() + select { + case <-reached: + case <-time.After(30 * time.Second): + cancel() + boundary.unblock() + <-done + t.Fatalf("inconclusive: snapshot never reached applied %s boundary", kind) + } + holder.kill(t) + killed := time.Now() + // Restart can abort the old session, so read the real backend first. + crashed := boundary.head(t) + _, published := crashed.Snapshots[name] + if kind == "COMMIT" && !published || kind != "COMMIT" && (published || crashed.Activity.Kind != layout.ActSnap) { + t.Fatalf("boundary %s disagrees with pre-restart HEAD: %+v", kind, crashed) + } + boundary.unblock() + var r result + select { + case r = <-done: + case <-time.After(60 * time.Second): + cancel() + select { // join the worker before failing + case <-done: + case <-time.After(10 * time.Second): + t.Error("the snapshot worker did not finish within 10 s of its cancellation") + } + t.Fatalf("round %d: the snapshot command did not return within 60 s of the holder's kill", k) + } + cancel() + answered := r.err == nil && r.code == 0 + + // Restarted within the lease, as the unit's RestartSec does: the same + // epoch, serving the blocks written before the kill. + holder = env.start(t, fmt.Sprintf("blockvolume-v1-r%d", k), "s1") + if got := env.adopt(t, holder, "s1"); got != e { + t.Fatalf("round %d: the restarted holder adopted epoch %d; want %d (restarted %v after the kill: within the lease?)", k, got, e, time.Since(killed).Round(time.Millisecond)) + } + adopted := time.Since(killed) + poll(t, 60*time.Second, fmt.Sprintf("round %d: the restarted holder never reported its frontend ready", k), func() bool { + return env.frontendReadyAt("s1") + }) + env.requireImage(t, "s1", cum) + + pre := env.snapshots(t, "v1", name) + step := kind + steps[step]++ + if published != (len(pre) == 1) { + t.Fatalf("round %d: pre-restart HEAD published=%v but restart lists %+v", k, published, pre) + } + t.Logf("round %d: applied %s, pre-restart HEAD gen=%d activity=%s published=%v; exit %d err %v; adopted %v after kill", + k, step, crashed.Gen, crashed.Activity.Kind, published, r.code, r.err, adopted.Round(time.Millisecond)) + switch { + case len(pre) > 1: + t.Fatalf("round %d: %s listed %d times: %+v", k, name, len(pre), pre) + case answered && len(pre) == 0: + t.Fatalf("round %d: %s answered success before the kill but is not listed: %s", k, name, r.out) + } + // 16 bytes: pattern repeats it to exactly one block. + post := map[uint64][]byte{uint64(50+k) * ladderChunkBlocks: pattern(fmt.Sprintf("e1-post-%02d-blk!!", k))} + env.writeImage(t, "s1", post) + + out, _ := env.h.command(t, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status, + "--name", name, "--request-id", req) + var info snapshotInfo + if err := json.Unmarshal([]byte(out), &info); err != nil || info.Name != name { + t.Fatalf("round %d: retry of %s: %v %s", k, name, err, out) + } + l := env.snapshots(t, "v1", name) + if len(l) != 1 || l[0].Root == "" { + t.Fatalf("round %d: after the retry %s is listed as %+v; its retry answered %+v", k, name, l, info) + } + if len(pre) == 1 && l[0].Root != pre[0].Root { + t.Fatalf("round %d: %s was listed as %+v before the retry and as %+v after it: a listed snapshot was taken again", k, name, pre[0], l[0]) + } + if len(pre) == 1 { + images = append(images, cum) // a replay: the post-restart block is not in it + } else { + images = append(images, mergeImages(cum, post)) // cut anew after the restart + } + cum = mergeImages(cum, post) + } + t.Logf("kill steps: %v; per-write cases pinned by TestSnapshotSession_InterruptAtEveryStep", steps) + if steps["BEGIN"] != 1 || steps["OBJECT"] != 1 || steps["COMMIT"] != 1 { + t.Fatalf("inconclusive: no kill landed inside a snapshot (steps %v)", steps) + } + + next := ladderImage("e1next", []uint64{30, 31}, 3) + env.writeImage(t, "s1", next) + env.snapshot(t, "s1", "v1", "e1-next") + final := mergeImages(cum, next) + + for k := range boundaries { + later := []map[uint64][]byte{final} + env.restoreChecked(t, fmt.Sprintf("e1-%d", k), targets[k], images[k], later...) + } + env.restoreChecked(t, "e1-next", targets[len(boundaries)], final) + t.Logf("final restore oracle reached: %d crash snapshots plus next snapshot read back", len(boundaries)) +} diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_health_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_health_integration_test.go new file mode 100644 index 0000000000..344d49fc7f --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_health_integration_test.go @@ -0,0 +1,148 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "fmt" + "os" + "strings" + "sync" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" +) + +// Rung F1's heartbeat-ordering watch: with N processes under +// one server id, a volume's slot at the master can expire when its +// heartbeats are dropped. The watch polls the master's view of every source +// volume's replica each second and records each span where the master does +// not observe it (a slot expiry), and what the volume shows meanwhile: an +// epoch change or its frontend leaving ready. At the end it counts the +// master's per-slot superseded lines for the volume ('blockmaster: +// heartbeat superseded ... volume= ...'; 0 where the master does not log +// them). + +// f1Health is one source volume's record over the whole run. +type f1Health struct { + Volume string `json:"volume"` + Replica string `json:"replica"` + Polls int `json:"polls"` + PollErrors int `json:"poll_errors"` + SlotExpiries int `json:"slot_expiries"` + SlotUnobservedMs float64 `json:"slot_unobserved_ms"` + EpochChanges int `json:"epoch_changes"` + FrontendNotReady int `json:"frontend_not_ready_polls"` + DuringExpiry []string `json:"during_expiry,omitempty"` + SupersededLogLines int `json:"master_superseded_lines"` +} + +type f1Watch struct { + stop chan struct{} + done chan struct{} + mu sync.Mutex + vols map[string]*f1Health +} + +// f1StartWatch starts polling the master for every source volume. +func f1StartWatch(env *handoffEnv, vols []f1Volume) *f1Watch { + w := &f1Watch{stop: make(chan struct{}), done: make(chan struct{}), vols: map[string]*f1Health{}} + for _, v := range vols { + w.vols[v.id] = &f1Health{Volume: v.id, Replica: env.hosts[v.node].replica} + } + go func() { + defer close(w.done) + conn, err := link.Dial(env.h.masterAddr) + if err != nil { + return + } + defer conn.Close() + cl := control.NewClusterEvidenceServiceClient(conn) + type state struct { + unobservedSince time.Time + epoch uint64 + } + st := map[string]*state{} + t := time.NewTicker(time.Second) + defer t.Stop() + for { + select { + case <-w.stop: + return + case <-t.C: + } + for _, v := range vols { + h, s := w.vols[v.id], st[v.id] + if s == nil { + s = &state{} + st[v.id] = s + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + ev, err := cl.GetVolumeStatus(ctx, &control.GetVolumeStatusRequest{VolumeId: v.id}) + cancel() + w.mu.Lock() + h.Polls++ + if err != nil { + h.PollErrors++ + w.mu.Unlock() + continue + } + observed := false + for _, r := range ev.GetReplicas() { + if r.GetReplicaId() == h.Replica && r.GetObserved() { + observed = true + } + } + now := time.Now() + switch { + case !observed && s.unobservedSince.IsZero(): + s.unobservedSince = now + h.SlotExpiries++ + case observed && !s.unobservedSince.IsZero(): + h.SlotUnobservedMs += ms(now.Sub(s.unobservedSince)) + s.unobservedSince = time.Time{} + } + if e := ev.GetEpoch(); s.epoch != 0 && e != s.epoch { + h.EpochChanges++ + if !s.unobservedSince.IsZero() { + h.DuringExpiry = append(h.DuringExpiry, fmt.Sprintf("epoch %d -> %d", s.epoch, e)) + } + } + s.epoch = ev.GetEpoch() + w.mu.Unlock() + ready := volumeFrontendReady(env.hosts[v.node].status, v.id) + w.mu.Lock() + if !ready { + h.FrontendNotReady++ + if !s.unobservedSince.IsZero() { + h.DuringExpiry = append(h.DuringExpiry, "frontend not ready at "+now.UTC().Format(time.RFC3339)) + } + } + w.mu.Unlock() + } + } + }() + return w +} + +// finish stops the watch and counts the master's superseded lines per +// volume from its log. +func (w *f1Watch) finish(masterLog string) []f1Health { + close(w.stop) + <-w.done + b, _ := os.ReadFile(masterLog) + lines := strings.Split(string(b), "\n") + w.mu.Lock() + defer w.mu.Unlock() + var out []f1Health + for _, h := range w.vols { + for _, l := range lines { + if strings.Contains(l, "heartbeat superseded") && strings.Contains(l, " volume="+h.Volume+" ") { + h.SupersededLogLines++ + } + } + out = append(out, *h) + } + return out +} diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go new file mode 100644 index 0000000000..a42d3f0dba --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go @@ -0,0 +1,826 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "math" + "net/http" + "net/url" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/hostlimit" +) + +// Snapshot ladder rung F1: N volumes on one host, +// every volume snapshotted at the same instant, round after round, under +// write load. It must hold: every snapshot restores exactly; no write fails; +// the host limiter paces the cuts and none starves (every snapshot commits +// within ceil(N/slots)+1 times the slowest single cut). It measures, per +// volume and round: the snapshot's cut (total and guest barrier pause), the +// client write latency inside and outside snapshot windows, request to +// commit time, host-slot waits, restore time, chunks and bytes uploaded, +// filer entries per snapshot, and blockvolume RSS. The JSON report goes to +// F1_REPORT. +// +// A large test: it runs only with F1_RUN=1, on a host booked for it, never in +// CI. Knobs: F1_VOLUMES (10), F1_ROUNDS (3), F1_WRITE_SECONDS (120), +// F1_CONTROL_PAUSE_SECONDS (a negative control: stop the last volume's +// process that long after the rounds; the rung must then fail), +// F1_LOAD_SPAN (8192 blocks per volume per round, written evenly across the +// write period, so writes run before, during and after the snapshots), +// F1_HOST_LIMIT_DIR (a local, non-temporary directory; required for the +// limiter checks, a smoke may leave it unset), F1_HOST_LIMIT_SLOTS +// (the limiter's normal slots; default hostlimit's), F1_REPORT, +// F1_NVME_RETRIES (5: the load writers retry a refused command as the Linux +// NVMe host does, see retryLikeHost; 0 turns the retries off). +// +// Each volume has two regions. The ledger region is written and flushed +// before a round's snapshot, so the snapshot must hold it exactly. The load +// region is written in LBA order during the snapshot, so the snapshot must +// hold a prefix of it (A3's one-point-in-time check). + +type f1Config struct { + Volumes, Rounds int + WriteSeconds int + HostLimitDir string + SlotRetryBound time.Duration + Slots int + Report string + LedgerBlocksPerRnd int + LoadSpan int + ControlPauseSecs int + NVMeRetries int +} + +func f1ConfigFromEnv(t *testing.T) f1Config { + t.Helper() + if os.Getenv("F1_RUN") != "1" { + t.Skip("rung F1 is a large test: set F1_RUN=1 on a booked host") + } + num := func(k string, def int) int { + if v := os.Getenv(k); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 1 { + t.Fatalf("%s=%q: want a positive integer", k, v) + } + return n + } + return def + } + retry := 60 // the snapshot command's default --timeout; 0 = no retry (the negative control) + if v := os.Getenv("F1_SLOT_RETRY_SECONDS"); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 0 { + t.Fatalf("F1_SLOT_RETRY_SECONDS=%q: want a whole number of seconds, 0 or more", v) + } + retry = n + } + c := f1Config{Volumes: num("F1_VOLUMES", 10), Rounds: num("F1_ROUNDS", 3), WriteSeconds: num("F1_WRITE_SECONDS", 120), + HostLimitDir: os.Getenv("F1_HOST_LIMIT_DIR"), Slots: num("F1_HOST_LIMIT_SLOTS", hostlimit.DefaultConfig("").NormalSlots), + Report: os.Getenv("F1_REPORT"), LedgerBlocksPerRnd: 64, LoadSpan: num("F1_LOAD_SPAN", 8192), SlotRetryBound: time.Duration(retry) * time.Second, + NVMeRetries: num("F1_NVME_RETRIES", nvmeHostMaxRetries)} + if v := os.Getenv("F1_CONTROL_PAUSE_SECONDS"); v != "" { + c.ControlPauseSecs = num("F1_CONTROL_PAUSE_SECONDS", 0) + } + if c.Rounds*(c.LedgerBlocksPerRnd+c.LoadSpan) > ladderUntouched { + t.Fatalf("F1_ROUNDS=%d does not fit below the untouched chunk", c.Rounds) + } + return c +} + +// f1Volume is one source volume: its id, host record and daemon. +type f1Volume struct { + id, node string + d *daemon +} + +// f1Sample is one client write. +type f1Sample struct { + start time.Time + d time.Duration +} + +// f1Round is one volume's measurements in one round. +type f1Round struct { + Volume string `json:"volume"` + Round int `json:"round"` + // BusyRefusals counts the load writer's commands refused with a + // retryable status (and retried); MaxConsecutiveBusy is the longest run + // of such refusals of one command. + BusyRefusals int `json:"busy_refusals"` + MaxConsecutiveBusy int `json:"max_consecutive_busy"` + SnapshotMs float64 `json:"snapshot_request_to_commit_ms"` + CutTotalMs float64 `json:"cut_total_ms"` + BarrierPauseMs float64 `json:"cut_barrier_pause_ms"` + UploadedChunks int `json:"uploaded_chunks"` + UploadedBytes int64 `json:"uploaded_bytes"` + HostSlotWaits uint64 `json:"host_slot_waits"` + SlotRetries int `json:"snapshot_slot_refusals_retried"` + SlotWaitMs float64 `json:"snapshot_slot_wait_ms"` + RestoreMs float64 `json:"restore_ms"` + // RestoreExact is true or false for a snapshot that ran, "not_run" for + // one that was never admitted. + RestoreExact any `json:"restore_exact"` + LoadPrefix int `json:"load_prefix_blocks"` + WritesIn int `json:"writes_in_window"` + WritesOut int `json:"writes_outside_window"` + WriteP50InMs float64 `json:"write_p50_in_ms"` + WriteP99InMs float64 `json:"write_p99_in_ms"` + WriteMaxInMs float64 `json:"write_max_in_ms"` + WriteP50OutMs float64 `json:"write_p50_out_ms"` + WriteP99OutMs float64 `json:"write_p99_out_ms"` + WriteMaxOutMs float64 `json:"write_max_out_ms"` + RSSKiB int64 `json:"blockvolume_rss_kib"` + FilerEntriesNew int `json:"filer_entries_added_by_round"` + FilerPerSnap float64 `json:"filer_entries_per_snapshot"` +} + +type f1Report struct { + Config f1Config `json:"config"` + Limiter string `json:"limiter"` + StartedAt time.Time `json:"started_at"` + Rounds []f1Round `json:"rounds"` + Health []f1Health `json:"heartbeat_health"` + CommitBound float64 `json:"commit_bound_ms"` + WriteErrors int `json:"write_errors"` + Verdict string `json:"verdict"` + Failures []string `json:"failures,omitempty"` +} + +func TestSnapshotLadderF1VolumesOneHost(t *testing.T) { + cfg := f1ConfigFromEnv(t) + rep := &f1Report{Config: cfg, StartedAt: time.Now().UTC(), Limiter: "off"} + env, master := f1StartEnv(t, cfg) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + if cfg.HostLimitDir != "" { + env.volExtra = append(env.volExtra, "--host-limit-dir", cfg.HostLimitDir, "--host-limit-normal-slots", strconv.Itoa(cfg.Slots)) + rep.Limiter = fmt.Sprintf("%s, %d normal slots", cfg.HostLimitDir, cfg.Slots) + } + vols := f1StartSources(t, env, cfg.Volumes) + defer f1WriteReport(t, cfg, rep) + watch := f1StartWatch(env, vols) + + for round := 1; round <= cfg.Rounds; round++ { + before := f1FilerEntries(t, env) + rounds := f1RunRound(t, env, cfg, vols, round, rep) + added := f1FilerEntries(t, env) - before + for i := range rounds { + rounds[i].FilerEntriesNew = added + rounds[i].FilerPerSnap = float64(added) / float64(len(rounds)) + } + rep.Rounds = append(rep.Rounds, rounds...) + } + if cfg.ControlPauseSecs > 0 { + // Negative control: the last volume's blockvolume is stopped + // (SIGSTOP) past the master's freshness window, so its heartbeats + // stop; the watch must record a slot expiry and the rung must fail. + last := vols[len(vols)-1] + if err := last.d.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatalf("control: SIGSTOP %s: %v", last.id, err) + } + time.Sleep(time.Duration(cfg.ControlPauseSecs) * time.Second) + if err := last.d.proc.Signal(syscall.SIGCONT); err != nil { + t.Fatalf("control: SIGCONT %s: %v", last.id, err) + } + time.Sleep(3 * time.Second) + } + rep.Health = watch.finish(master.log) + f1Judge(t, cfg, rep) +} + +func f1RestoreTarget(vol, round int) string { return fmt.Sprintf("v%dr%d", vol, round) } + +// f1StartEnv is the procedure harness laid out as one host: ONE server id, s1, and one blockvolume process per +// volume, each with its own replica id and its own data/ctrl/status/NVMe +// ports. Source v is replica r; the restore target of v in round k +// is replica r on the same server. The node record carries the first +// source's pair, as the deployment page writes one node. +func f1StartEnv(t *testing.T, cfg f1Config) (*handoffEnv, *daemon) { + t.Helper() + h := newPlannedHandoffHarness(t) + env := &handoffEnv{h: h, cluster: startWorkspaceWeed(t), chunkPath: fmt.Sprintf("/f1-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}} + must, _ := fatalOn(t) + add := func(key, vol string, replica int) { + b := bvHost{id: key, server: "s1", replica: fmt.Sprintf("r%d", replica), volume: vol, root: filepath.Join(h.dir, "vol-"+key), + data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t)} + if key == "v1" { + b.data, b.ctrl, b.status, b.nvme = h.dataAddr, h.ctrlAddr, h.statusAddr, h.nvmeAddr + } + env.hosts[key] = b + } + for i := 1; i <= cfg.Volumes; i++ { + add(fmt.Sprintf("v%d", i), fmt.Sprintf("v%d", i), i) + } + targets := map[string]bool{} + for r := 1; r <= cfg.Rounds; r++ { + for i := 1; i <= cfg.Volumes; i++ { + v := f1RestoreTarget(i, r) + add(v, v, i+cfg.Volumes*r) + targets[v] = true + } + } + var vols strings.Builder + keys := make([]string, 0, len(env.hosts)) + for k := range env.hosts { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + b := env.hosts[k] + size := " size_bytes: 268435456\n" + if targets[k] { + size = "" // a restore target: placement only, its restore creates it + } + fmt.Fprintf(&vols, " - id: %s\n%s replication_factor: 1\n placements:\n - server_id: s1\n replica_id: %s\n", b.volume, size, b.replica) + } + spec := filepath.Join(h.dir, "cluster-spec.yaml") + must(os.WriteFile(spec, []byte(fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n%s", h.dataAddr, h.ctrlAddr, vols.String())), 0o644)) + mstate := filepath.Join(h.dir, "master") + env.masterArgs = []string{"--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"), + "--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr, + "--workspace-rpc", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath} + master := h.start(t, "blockmaster", h.master, env.masterArgs...) + master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + env.masterProcess = master + return env, master +} + +// f1Up starts the blockvolume of key and waits for its volume to be primary +// and its frontend ready. +// +// A harness-chosen port can be taken between handoffAddress's free check and +// the holder's bind. When the holder exits before adopting with "address +// already in use", its four ports are drawn again and it starts once more +// (startWithBindRetry). v1's ports are the harness's own and named in the +// cluster spec, so v1 is not retried. +func f1Up(t *testing.T, env *handoffEnv, key string) *daemon { + t.Helper() + var d *daemon + start := func(attempt int) error { + b := env.hosts[key] + name := "blockvolume-" + key + if attempt > 1 { + name = fmt.Sprintf("%s-attempt%d", name, attempt) // its own log: the first attempt's stays whole + } + d = env.h.start(t, name, env.h.volume, env.volArgsFor(b)...) + return f1WaitAdopted(d, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at %s@", b.volume, b.replica), + []string{b.data, b.ctrl, b.status, b.nvme}) + } + fresh := func() { + b := env.hosts[key] + b.data, b.ctrl, b.status, b.nvme = handoffAddress(t), handoffAddress(t), handoffAddress(t), handoffAddress(t) + env.hosts[key] = b + } + var first, err error + if key == "v1" { + err = start(1) + } else { + first, err = startWithBindRetry(start, fresh) + } + if first != nil { + t.Logf("%s: started again on new ports after its first attempt lost a drawn port: %v", key, first) + } + if err != nil { + t.Fatal(err) + } + b := env.hosts[key] + poll(t, 60*time.Second, key+" never reported its frontend ready", func() bool { return volumeFrontendReady(b.status, b.volume) }) + return d +} + +// f1WaitAdopted waits until d logs s. A holder that exits first because the +// bind of one of drawn (this attempt's own addresses) found it in use +// answers errBindTaken (wrapped, naming the address and the log's end); +// any other exit or the bound answers an error naming it. +func f1WaitAdopted(d *daemon, timeout time.Duration, s string, drawn []string) error { + end := time.Now().Add(timeout) + for { + if d.line(s) != "" { + return nil + } + select { + case <-d.done: + if d.line(s) != "" { + return nil + } + if data, err := os.ReadFile(d.log); err == nil { + if addr, ok := bindTakenOn(string(data), drawn); ok { + return fmt.Errorf("%s exited (%v) before logging %q: %w (%s; log %s); its log ends:\n%s", d.name, d.err, s, errBindTaken, addr, d.log, d.tail(40)) + } + } + return fmt.Errorf("%s exited (%v) before logging %q; its log ends:\n%s", d.name, d.err, s, d.tail(40)) + default: + } + if time.Now().After(end) { + return fmt.Errorf("%s did not log %q within %s; its log ends:\n%s", d.name, s, timeout, d.tail(40)) + } + time.Sleep(100 * time.Millisecond) + } +} + +// f1StartSources starts the N source volumes. +func f1StartSources(t *testing.T, env *handoffEnv, n int) []f1Volume { + t.Helper() + var vols []f1Volume + for i := 1; i <= n; i++ { + v := fmt.Sprintf("v%d", i) + vols = append(vols, f1Volume{id: v, node: v, d: f1Up(t, env, v)}) + } + return vols +} + +// f1Restore restores snapshot snap of src into target (a new volume on the +// same server), which fetches its chunks on access; the target's blockvolume +// is stopped once verified (f1RunRound), so restores do not pile up processes. +func f1Restore(t *testing.T, env *handoffEnv, src, snap, target string) *daemon { + t.Helper() + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", src, "--snapshot", snap, "--target", target, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + d := f1Up(t, env, target) + return d +} + +// f1CommandDeadline bounds one load write (and its flush): a write held +// longer than this by a cut fails the rung. +const f1CommandDeadline = 30 * time.Second + +// A snapshot refused because every host slot is held is resent with its +// request id every f1SlotRetryPause, for at most cfg.SlotRetryBound from its +// first request (the snapshot command's operation bound, its default +// --timeout of 60 s; F1_SLOT_RETRY_SECONDS=0 turns the retry off, the +// negative control). Its request-to-commit time includes the waits; the +// write window starts at the admitted attempt. +const f1SlotRetryPause = 250 * time.Millisecond + +// f1SlotRefusal reports whether a failed snapshot's error body is a +// retryable refusal for a busy host slot. +func f1SlotRefusal(stdout string) bool { + var body struct { + Code string `json:"code"` + Message string `json:"message"` + Retryable bool `json:"retryable"` + } + if json.Unmarshal([]byte(strings.TrimSpace(stdout)), &body) != nil || !body.Retryable { + return false + } + return body.Code == "host_slot_busy" || body.Code == "capture_refused" && strings.Contains(body.Message, "hostlimit: no background slot") +} + +// f1Block is one deterministic 4096-byte block (pattern needs a length that +// divides 4096; these labels do not, so the block is filled explicitly). +func f1Block(vol string, round int, kind string, lba uint64) []byte { + s := fmt.Sprintf("%s r%d %s %08d|", vol, round, kind, lba) + b := make([]byte, 4096) + for i := range b { + b[i] = s[i%len(s)] + } + return b +} + +func f1LedgerBase(cfg f1Config, round int) uint64 { + return uint64((round - 1) * (cfg.LedgerBlocksPerRnd + cfg.LoadSpan)) +} + +// f1RunRound: write and flush each volume's ledger region, start the load +// writers, snapshot every volume at the same instant, stop the load, then +// restore and verify every snapshot. +func f1RunRound(t *testing.T, env *handoffEnv, cfg f1Config, vols []f1Volume, round int, rep *f1Report) []f1Round { + t.Helper() + for _, v := range vols { + c := dialNVMe(t, env.hosts[v.node].nvme, plannedHandoffNQN) + base := f1LedgerBase(cfg, round) + for i := 0; i < cfg.LedgerBlocksPerRnd; i++ { + c.write(t, base+uint64(i), f1Block(v.id, round, "ledger", base+uint64(i))) + } + c.flush(t) + c.close() + } + type writer struct { + mu sync.Mutex + samples []f1Sample + written int + err error + busy int // commands refused with a retryable status, retried + maxBusyRun int // the longest run of refusals of one command + } + stop := make(chan struct{}) + ws := make([]*writer, len(vols)) + var wg sync.WaitGroup + for i, v := range vols { + ws[i] = &writer{} + c := dialNVMe(t, env.hosts[v.node].nvme, plannedHandoffNQN) + wg.Add(1) + go func(w *writer, c *nvmeInitiator, vol string) { + defer wg.Done() + defer c.close() + first := f1LedgerBase(cfg, round) + uint64(cfg.LedgerBlocksPerRnd) + // Paced so the span covers the whole write period. + every := time.Duration(cfg.WriteSeconds) * time.Second / time.Duration(cfg.LoadSpan) + begin := time.Now() + for n := 0; n < cfg.LoadSpan; n++ { + if wait := time.Until(begin.Add(time.Duration(n) * every)); wait > 0 { + select { + case <-stop: + return + case <-time.After(wait): + } + } + select { + case <-stop: + return + default: + } + lba := first + uint64(n) + s := time.Now() + // Per attempt: dialNVMe's deadline is 60 s from the dial, + // shorter than the write period. + refused, err := retryLikeHost(cfg.NVMeRetries, func() error { + _ = c.io.SetDeadline(time.Now().Add(f1CommandDeadline)) + return c.tryWrite(lba, f1Block(vol, round, "load", lba)) + }) + flushRefused := 0 + if err == nil && n%16 == 15 { + flushRefused, err = retryLikeHost(cfg.NVMeRetries, func() error { + _ = c.io.SetDeadline(time.Now().Add(f1CommandDeadline)) + return c.tryFlush() + }) + } + w.mu.Lock() + w.busy += refused + flushRefused + w.maxBusyRun = max(w.maxBusyRun, refused, flushRefused) + w.samples = append(w.samples, f1Sample{start: s, d: time.Since(s)}) + if err != nil { + w.err = err + } else { + w.written = n + 1 + } + w.mu.Unlock() + if err != nil { + return + } + } + }(ws[i], c, v.id) + } + time.Sleep(time.Duration(cfg.WriteSeconds) * time.Second / 2) // load before the snapshots + + type snapRes struct { + start, end time.Time + admitted time.Time // the start of the attempt that was not refused + out, err string + code int + retries int + } + res := make([]snapRes, len(vols)) + var sg sync.WaitGroup + gate := make(chan struct{}) + for i, v := range vols { + sg.Add(1) + go func(i int, v f1Volume) { + defer sg.Done() + <-gate + res[i].start = time.Now() + // A refusal for a busy host slot is retryable by contract: resend + // it with the same request id, as an operator would, within a bound. + request := fmt.Sprintf("f1-r%d-%s", round, v.id) + for { + res[i].admitted = time.Now() + res[i].out, res[i].err, res[i].code = env.h.run(t, "ops", "chunk", "snapshot", "--volume", v.id, "--status-addr", env.hosts[v.node].status, + "--name", fmt.Sprintf("f1-r%d", round), "--request-id", request) + if res[i].code == 0 || !f1SlotRefusal(res[i].out) || time.Since(res[i].start) > cfg.SlotRetryBound { + break + } + res[i].retries++ + time.Sleep(f1SlotRetryPause) + } + res[i].end = time.Now() + }(i, v) + } + close(gate) + sg.Wait() + time.Sleep(time.Duration(cfg.WriteSeconds) * time.Second / 2) // load after the snapshots + close(stop) + wg.Wait() + + out := make([]f1Round, len(vols)) + for i, v := range vols { + r := f1Round{Volume: v.id, Round: round, RestoreExact: "not_run", SlotRetries: res[i].retries} + w := ws[i] + r.BusyRefusals, r.MaxConsecutiveBusy = w.busy, w.maxBusyRun + if w.err != nil { + rep.WriteErrors++ + rep.Failures = append(rep.Failures, fmt.Sprintf("%s round %d: write error: %v", v.id, round, w.err)) + } + if res[i].code != 0 && f1SlotRefusal(res[i].out) { + rep.Failures = append(rep.Failures, fmt.Sprintf("%s round %d: snapshot not admitted within %v (%d slot refusals retried): %s", v.id, round, cfg.SlotRetryBound, res[i].retries, strings.Join(strings.Fields(res[i].out), " "))) + out[i] = r + continue + } + if res[i].code != 0 { + rep.Failures = append(rep.Failures, fmt.Sprintf("%s round %d: snapshot exit %d: %s %s", v.id, round, res[i].code, res[i].out, res[i].err)) + out[i] = r + continue + } + r.SnapshotMs = ms(res[i].end.Sub(res[i].start)) + r.SlotWaitMs = ms(res[i].admitted.Sub(res[i].start)) + f1Latencies(&r, w.samples, res[i].admitted, res[i].end) + if r.WritesIn == 0 { + rep.Failures = append(rep.Failures, fmt.Sprintf("%s round %d: no load write was issued inside the snapshot window", v.id, round)) + } + f1CutStats(t, env, v, &r) + r.RSSKiB = f1RSS(v.d) + target := f1RestoreTarget(i+1, round) + rs := time.Now() + rd := f1Restore(t, env, v.id, fmt.Sprintf("f1-r%d", round), target) + r.RestoreMs = ms(time.Since(rs)) + exact, prefix := f1Verify(t, env, cfg, v.id, target, round, w.written) + r.RestoreExact, r.LoadPrefix = exact, prefix + rd.term(t, 60*time.Second) + if !exact { + rep.Failures = append(rep.Failures, fmt.Sprintf("%s round %d: the restored snapshot is not the volume at its point", v.id, round)) + } + out[i] = r + } + return out +} + +// f1Verify reads the restored snapshot: every ledger block of rounds 1..round +// exact; each round's load region a prefix, at most what was written. +func f1Verify(t *testing.T, env *handoffEnv, cfg f1Config, vol, target string, round, written int) (bool, int) { + t.Helper() + c := dialNVMe(t, env.hosts[target].nvme, plannedHandoffNQN) + defer c.close() + zero := make([]byte, 4096) + prefix := 0 + for r := 1; r <= round; r++ { + base := f1LedgerBase(cfg, r) + for i := 0; i < cfg.LedgerBlocksPerRnd; i++ { + if !bytes.Equal(c.read(t, base+uint64(i), 4096), f1Block(vol, r, "ledger", base+uint64(i))) { + return false, 0 + } + } + first := base + uint64(cfg.LedgerBlocksPerRnd) + ended, k := false, 0 + for n := 0; n < cfg.LoadSpan; n++ { + got := c.read(t, first+uint64(n), 4096) + switch { + case !ended && bytes.Equal(got, f1Block(vol, r, "load", first+uint64(n))): + k++ + case bytes.Equal(got, zero) && r == round: + ended = true + case r < round && n >= k && bytes.Equal(got, zero): + ended = true + default: + return false, 0 + } + } + if r == round { + prefix = k + if k > written { + return false, k + } + } + } + return true, prefix +} + +// f1Latencies splits the client write latencies at the snapshot window. +func f1Latencies(r *f1Round, samples []f1Sample, from, to time.Time) { + var in, out []time.Duration + for _, s := range samples { + if !s.start.Before(from) && !s.start.After(to) { + in = append(in, s.d) + } else { + out = append(out, s.d) + } + } + r.WritesIn, r.WritesOut = len(in), len(out) + r.WriteP50InMs, r.WriteP99InMs, r.WriteMaxInMs = pct(in, 50), pct(in, 99), pct(in, 100) + r.WriteP50OutMs, r.WriteP99OutMs, r.WriteMaxOutMs = pct(out, 50), pct(out, 99), pct(out, 100) +} + +func pct(d []time.Duration, p float64) float64 { + if len(d) == 0 { + return 0 + } + s := append([]time.Duration(nil), d...) + sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) + i := int(math.Ceil(p/100*float64(len(s)))) - 1 + if i < 0 { + i = 0 + } + return ms(s[i]) +} + +func ms(d time.Duration) float64 { return float64(d) / float64(time.Millisecond) } + +// f1CutStats reads the volume's last cut (the snapshot's) from its durable +// status. +func f1CutStats(t *testing.T, env *handoffEnv, v f1Volume, r *f1Round) { + t.Helper() + c := &http.Client{Timeout: 5 * time.Second} + resp, err := c.Get("http://" + env.hosts[v.node].status + "/status/durable?volume=" + v.id) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var st struct { + Volumes []struct { + VolumeID string + Chunk *struct { + HostSlotWaits uint64 + Stats struct { + LastCut *struct { + TotalNs, BarrierPauseNs int64 + UploadedChunks int + UploadedBytes int64 + } + } + } + } + } + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) + if err := json.Unmarshal(body, &st); err != nil { + t.Fatalf("durable status of %s: %v", v.id, err) + } + for _, s := range st.Volumes { + if s.VolumeID != v.id || s.Chunk == nil || s.Chunk.Stats.LastCut == nil { + continue + } + l := s.Chunk.Stats.LastCut + r.CutTotalMs, r.BarrierPauseMs = float64(l.TotalNs)/1e6, float64(l.BarrierPauseNs)/1e6 + r.UploadedChunks, r.UploadedBytes, r.HostSlotWaits = l.UploadedChunks, l.UploadedBytes, s.Chunk.HostSlotWaits + return + } + t.Fatalf("durable status of %s has no last cut: %s", v.id, body) +} + +// f1RSS is the blockvolume's resident set (KiB), 0 where /proc is absent. +func f1RSS(d *daemon) int64 { + b, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", d.proc.Pid)) + if err != nil { + return 0 + } + for _, l := range strings.Split(string(b), "\n") { + if strings.HasPrefix(l, "VmRSS:") { + f := strings.Fields(l) + if len(f) >= 2 { + n, _ := strconv.ParseInt(f[1], 10, 64) + return n + } + } + } + return 0 +} + +// f1FilerEntries counts the filer entries (files and directories) under the +// chunk path, by the filer's JSON listing. +func f1FilerEntries(t *testing.T, env *handoffEnv) int { + t.Helper() + c := &http.Client{Timeout: 30 * time.Second} + var walk func(dir string) int + walk = func(dir string) int { + n, last := 0, "" + for { + u := "http://" + env.cluster.filerHTTP + dir + "/?limit=1000&lastFileName=" + url.QueryEscape(last) + req, _ := http.NewRequest(http.MethodGet, u, nil) + req.Header.Set("Accept", "application/json") + resp, err := c.Do(req) + if err != nil { + t.Fatalf("filer list %s: %v", dir, err) + } + var page struct { + Entries []struct { + FullPath string + Mode uint32 + } + ShouldDisplayLoadMore bool + LastFileName string + } + err = json.NewDecoder(resp.Body).Decode(&page) + resp.Body.Close() + if err != nil { + t.Fatalf("filer list %s: %v", dir, err) + } + for _, e := range page.Entries { + n++ + if e.Mode&uint32(os.ModeDir) != 0 { + n += walk(e.FullPath) + } + } + if !page.ShouldDisplayLoadMore || page.LastFileName == "" { + return n + } + last = page.LastFileName + } + } + return walk(env.chunkPath) +} + +// f1Judge applies the pass rule: no failure recorded, and every snapshot +// committed within ceil(N/slots)+1 times the slowest single cut (N+1 when +// the limiter is off). +func f1Judge(t *testing.T, cfg f1Config, rep *f1Report) { + t.Helper() + worst, longest := 0.0, 0.0 + for _, r := range rep.Rounds { + worst = math.Max(worst, r.CutTotalMs) + longest = math.Max(longest, r.SnapshotMs) + } + waves := float64(cfg.Volumes + 1) + if cfg.HostLimitDir != "" { + waves = math.Ceil(float64(cfg.Volumes)/float64(cfg.Slots)) + 1 + } + rep.CommitBound = waves * worst + for _, h := range rep.Health { + if h.SlotExpiries > 0 { + rep.Failures = append(rep.Failures, fmt.Sprintf("%s: the master lost its slot %d time(s) for %.0f ms in total (during: %v)", h.Volume, h.SlotExpiries, h.SlotUnobservedMs, h.DuringExpiry)) + } + } + if longest > rep.CommitBound { + rep.Failures = append(rep.Failures, fmt.Sprintf("a snapshot took %.0f ms, above the bound %.0f ms (%.0f waves x the slowest cut %.0f ms): a volume starved", longest, rep.CommitBound, waves, worst)) + } + rep.Verdict = "PASS" + if len(rep.Failures) > 0 { + rep.Verdict = "FAIL" + t.Errorf("rung F1: %s", strings.Join(rep.Failures, "; ")) + } +} + +func f1WriteReport(t *testing.T, cfg f1Config, rep *f1Report) { + b, err := json.MarshalIndent(rep, "", " ") + if err != nil { + t.Errorf("report: %v", err) + return + } + t.Logf("rung F1 report: %s", b) + if cfg.Report != "" { + if err := os.WriteFile(cfg.Report, b, 0o644); err != nil { + t.Errorf("write %s: %v", cfg.Report, err) + } + } +} + +// tryWrite and tryFlush are write and flush returning the error (the load +// writers run off the test goroutine, where t.Fatal is not allowed). +func (c *nvmeInitiator) tryWrite(lba uint64, data []byte) error { + cmd := c.ioCmd(0x01, lba, len(data)/4096) + if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil { + return fmt.Errorf("nvme Write: %w", err) + } + ch, err := c.r.Dequeue() + if err != nil || ch.Type != 0x9 { + if err != nil { + return fmt.Errorf("nvme Write: want R2T: %w", err) + } + return fmt.Errorf("nvme Write: want R2T, got type %v", ch) + } + var r2t nvme.R2THeader + if err := c.r.Receive(&r2t); err != nil { + return fmt.Errorf("nvme R2T: %w", err) + } + h2c := nvme.H2CDataHeader{CCCID: cmd.CID, TAG: r2t.TAG, DATAL: uint32(len(data))} + if err := c.w.SendWithData(0x6, 0, &h2c, 16, data); err != nil { + return fmt.Errorf("nvme H2CData: %w", err) + } + return c.tryStatus("Write") +} + +func (c *nvmeInitiator) tryFlush() error { + cmd := c.ioCmd(0x00, 0, 0) + if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil { + return fmt.Errorf("nvme Flush: %w", err) + } + return c.tryStatus("Flush") +} + +func (c *nvmeInitiator) tryStatus(op string) error { + ch, err := c.r.Dequeue() + if err != nil || ch.Type != 0x5 { + if err != nil { + // %w: a deadline on the queue stays a net timeout for errors.As. + return fmt.Errorf("nvme %s response: %w", op, err) + } + return fmt.Errorf("nvme %s response: type %v", op, ch) + } + var resp nvme.CapsuleResponse + if err := c.r.Receive(&resp); err != nil { + return fmt.Errorf("nvme %s response body: %w", op, err) + } + if resp.Status != 0 { + return &nvmeStatusError{op: op, status: resp.Status} + } + return nil +} diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go new file mode 100644 index 0000000000..4ba29203d6 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_integration_test.go @@ -0,0 +1,689 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os/exec" + "strings" + "testing" + "time" +) + +// The snapshot test ladder, rungs A (one volume): each rung adds one thing. +// It tests what a snapshot contains through the product's own read path for +// a snapshot, a restore into a new volume, so the same tests hold on any +// chunk format. Volumes are 65536 blocks of 4096 bytes in chunks of 1024 +// blocks (chunk c holds LBAs c*1024 .. c*1024+1023). +// +// The restore that reads a snapshot also exercises the restore's hydration, +// which belongs to rung C. That is sound for rung A only while no snapshot is +// deleted and no collector runs: an A test must never delete a snapshot or +// run GC (those are rung D). +// +// The automatic capture timer is off and the scheduled snapshot is off, +// pinned explicitly, so every cut in a test is one the test made: A2 counts +// the chunks its own snapshot uploaded. + +const ( + ladderChunkBlocks = 1024 + ladderLastBlock = 65535 + ladderUntouched = 40 * ladderChunkBlocks // a chunk no test writes +) + +// startLadderEnv is the procedure harness with restore targets and the +// timer and the schedule pinned off. +func startLadderEnv(t *testing.T, targets ...string) *handoffEnv { + t.Helper() + env := startHandoffEnvWith(t, 1, targets) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + src := env.start(t, "blockvolume-v1", "s1") + env.adopt(t, src, "s1") + return env +} + +// TestSnapshotLadderA1OneBlockOneSnapshot: write one block, take a snapshot, +// and read the snapshot back block by block: it holds that block and zeros +// around it, in an untouched chunk and at the volume's last block, as the +// volume did at the snapshot. +func TestSnapshotLadderA1OneBlockOneSnapshot(t *testing.T) { + env := startLadderEnv(t, "v2") + block := pattern("ladder-a1-block!") + env.writeBlock(t, "s1", 5, block) + + env.snapshot(t, "s1", "v1", "a1") + env.restoreInto(t, "v1", "a1", "v2") + want := map[uint64][]byte{5: block} + env.requireBlocks(t, "n-v2", 0, 16, want) + env.requireEdges(t, "n-v2") + env.requireBlocks(t, "s1", 0, 16, want) // the source is unchanged +} + +// TestSnapshotLadderA2IncrementalSnapshot: write, snapshot, write a few +// blocks in two chunks, snapshot again. Snapshot 2 holds the volume at its +// point, snapshot 1 is unchanged (read after snapshot 2), and the second +// snapshot uploaded only the two chunks that changed (a test-only property: +// no model states it). +func TestSnapshotLadderA2IncrementalSnapshot(t *testing.T) { + env := startLadderEnv(t, "v2", "v3") + a, b, c := pattern("ladder-a2-blk-A!"), pattern("ladder-a2-blk-B!"), pattern("ladder-a2-blk-C!") + + env.writeBlock(t, "s1", 0, a) + env.snapshot(t, "s1", "v1", "s1") + if n := env.lastCutUploads(t, "s1", "v1"); n != 1 { + t.Fatalf("the first snapshot uploaded %d chunks; want 1 (chunk 0)", n) + } + env.writeBlock(t, "s1", 1, c) // chunk 0 again + env.writeBlock(t, "s1", 2*ladderChunkBlocks, b) // chunk 2 + env.snapshot(t, "s1", "v1", "s2") + if n := env.lastCutUploads(t, "s1", "v1"); n != 2 { + t.Fatalf("the incremental snapshot uploaded %d chunks; want 2 (chunks 0 and 2, the ones that changed)", n) + } + + env.restoreInto(t, "v1", "s1", "v2") + env.requireBlocks(t, "n-v2", 0, 4, map[uint64][]byte{0: a}) + env.requireBlocks(t, "n-v2", 2*ladderChunkBlocks, 2, nil) + env.requireEdges(t, "n-v2") + env.restoreInto(t, "v1", "s2", "v3") + env.requireBlocks(t, "n-v3", 0, 4, map[uint64][]byte{0: a, 1: c}) + env.requireBlocks(t, "n-v3", 2*ladderChunkBlocks, 2, map[uint64][]byte{2 * ladderChunkBlocks: b}) + env.requireEdges(t, "n-v3") +} + +// TestSnapshotLadderA3WritesDuringASnapshot: blocks are written one after +// another while a snapshot runs (between its start and its commit), three +// times, each starting the snapshot after a different number of writes; +// then a last snapshot is taken. Each snapshot taken during the writes is +// one point in time: of those writes it holds a prefix (every write up to +// some point, none after). The last snapshot holds them all. A run where +// every snapshot landed before or after all of its writes proves nothing +// about the middle and fails as inconclusive. +func TestSnapshotLadderA3WritesDuringASnapshot(t *testing.T) { + const n = 400 + starts := []int{0, 40, 120} // writes issued before each snapshot starts + env := startLadderEnv(t, "v2", "v3", "v4", "v5") + blockAt := func(lba uint64) []byte { return pattern(fmt.Sprintf("a3-lba-%08d!", lba)[:16]) } + inconclusive := true + all := map[uint64][]byte{} + for rep, startAfter := range starts { + first := uint64(100 + rep*1000) + name := fmt.Sprintf("during-%d", rep+1) + env.writeDuringSnapshot(t, name, first, n, startAfter, blockAt) + for i := uint64(0); i < n; i++ { + all[first+i] = blockAt(first + i) + } + target := fmt.Sprintf("v%d", rep+2) + env.restoreInto(t, "v1", name, target) + k := env.prefixLength(t, "n-"+target, first, n, blockAt) + t.Logf("snapshot %s (started after %d writes) holds the first %d of %d writes", name, startAfter, k, n) + if k > 0 && k < n { + inconclusive = false + } + } + if inconclusive { + t.Fatal("inconclusive: every snapshot landed before or after all of its writes") + } + env.snapshot(t, "s1", "v1", "after") + env.restoreInto(t, "v1", "after", "v5") + for rep := range starts { + first := uint64(100 + rep*1000) + env.requireBlocks(t, "n-v5", first, n, all) + } +} + +// TestSnapshotLadderA4ContentReturnsToAnOldValue: one block holds A, then B, +// then A again, with a snapshot after each; all three read back as they +// were. +func TestSnapshotLadderA4ContentReturnsToAnOldValue(t *testing.T) { + env := startLadderEnv(t, "v2", "v3", "v4") + a, b := pattern("ladder-a4-blk-A!"), pattern("ladder-a4-blk-B!") + for i, content := range [][]byte{a, b, a} { + env.writeBlock(t, "s1", 7, content) + env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1)) + } + for i, content := range [][]byte{a, b, a} { + target := fmt.Sprintf("v%d", i+2) + env.restoreInto(t, "v1", fmt.Sprintf("s%d", i+1), target) + env.requireBlocks(t, "n-"+target, 6, 3, map[uint64][]byte{7: content}) + env.requireEdges(t, "n-"+target) + } +} + +// writeDuringSnapshot writes n blocks from first one after another on v1 +// and starts snapshot name after startAfter of them, so that the snapshot +// runs while the rest are written. It fails the test if the snapshot fails. +func (env *handoffEnv) writeDuringSnapshot(t *testing.T, name string, first uint64, n, startAfter int, blockAt func(uint64) []byte) { + t.Helper() + type result struct { + out, errOut string + code int + } + done := make(chan result, 1) + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + defer c.close() + for i := 0; i < n; i++ { + if i == startAfter { + go func() { + o, e, code := env.h.run(t, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status, "--name", name) + done <- result{o, e, code} + }() + } + lba := first + uint64(i) + c.write(t, lba, blockAt(lba)) + } + c.flush(t) + r := <-done + if r.code != 0 { + t.Fatalf("snapshot %s during the writes: exit %d\n%s\n%s", name, r.code, r.out, r.errOut) + } +} + +// snapshotInfo is what a snapshot's answer and its list entry say about it. +type snapshotInfo struct { + Name string `json:"name"` + HeadGen uint64 `json:"headGen"` + CutLSN uint64 `json:"cutLSN"` + State string `json:"state"` + ChunkCount int `json:"chunkCount"` +} + +// snapshot takes the named snapshot of vol on its host, checks the answer +// names it, and returns the answer. +func (env *handoffEnv) snapshot(t *testing.T, hostID, vol, name string) snapshotInfo { + t.Helper() + out, _ := env.h.command(t, "ops", "chunk", "snapshot", "--volume", vol, "--status-addr", env.hosts[hostID].status, "--name", name) + var info snapshotInfo + if err := json.Unmarshal([]byte(out), &info); err != nil || info.Name != name { + t.Fatalf("snapshot %s of %s: %v\n%s", name, vol, err, out) + } + return info +} + +// snapshotEntry is one entry of `sw-block ops chunk snapshots`: a published +// snapshot, its root and the restore targets that depend on it. +type snapshotEntry struct { + Name string `json:"name"` + Root string `json:"root"` + Dependents []string `json:"dependents"` +} + +// listSnapshots lists vol's snapshots (with a name prefix when given) under +// ctx, without failing the test. +func (env *handoffEnv) listSnapshots(ctx context.Context, vol, prefix string) ([]snapshotEntry, error) { + args := []string{"ops", "chunk", "snapshots", "--master", env.h.masterAddr, "--volume", vol, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath} + if prefix != "" { + args = append(args, "--prefix", prefix) + } + out, errOut, code, err := runCLI(ctx, env.h, args...) + if err != nil { + return nil, err + } + var list []snapshotEntry + if code != 0 || json.Unmarshal([]byte(out), &list) != nil { + return nil, fmt.Errorf("snapshots of %s: exit %d: %s %s", vol, code, out, errOut) + } + return list, nil +} + +// snapshots lists vol's snapshots (with a name prefix when given). +func (env *handoffEnv) snapshots(t *testing.T, vol, prefix string) []snapshotEntry { + t.Helper() + args := []string{"ops", "chunk", "snapshots", "--master", env.h.masterAddr, "--volume", vol, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath} + if prefix != "" { + args = append(args, "--prefix", prefix) + } + out, _ := env.h.command(t, args...) + var list []snapshotEntry + if err := json.Unmarshal([]byte(out), &list); err != nil { + t.Fatalf("snapshots of %s: %v\n%s", vol, err, out) + } + return list +} + +// restoreAttached creates target from snapshot snap of src and starts its +// blockvolume, but not the restore driver: target serves and stays +// dependent on its source (not independent). +func (env *handoffEnv) restoreAttached(t *testing.T, src, snap, target string) { + t.Helper() + b := env.hosts["n-"+target] + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", src, "--snapshot", snap, "--target", target, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + d := env.h.start(t, "blockvolume-"+target, env.h.volume, env.volArgsFor(b)...) + waitC3RecoveryPrimary(t, d, b.status, target) + poll(t, 60*time.Second, fmt.Sprintf("%s never reported its frontend ready", target), func() bool { + return volumeFrontendReady(b.status, target) + }) +} + +// TestSnapshotLadderB1SnapshotQuery: three snapshots with writes between +// them. The list is exactly the published snapshots, in name order, each +// with its own root; a prefix shows one. A snapshot being taken appears in +// the list only once published, and then stays with the same root; the test +// fails as inconclusive unless at least one listing ran while the snapshot +// was in flight and did not show it. A snapshot of a restore target that is +// not fully local is taken, and a restore from it is refused: it names the +// source's chunks. +func TestSnapshotLadderB1SnapshotQuery(t *testing.T) { + env := startLadderEnv(t, "v2", "v3") + var made []snapshotInfo + for i, w := range []struct { + lba uint64 + text string + }{{0, "ladder-b1-blk-A!"}, {2 * ladderChunkBlocks, "ladder-b1-blk-B!"}, {1, "ladder-b1-blk-C!"}} { + env.writeBlock(t, "s1", w.lba, pattern(w.text)) + made = append(made, env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1))) + } + list := env.snapshots(t, "v1", "") + if len(list) != len(made) { + t.Fatalf("list has %d snapshots; want exactly the %d published: %+v", len(list), len(made), list) + } + roots := map[string]bool{} + for i, got := range list { + if got.Name != made[i].Name || got.Root == "" || roots[got.Root] { + t.Fatalf("list entry %d %+v; want %s with a root of its own (list %+v)", i, got, made[i].Name, list) + } + roots[got.Root] = true + } + if one := env.snapshots(t, "v1", "s2"); len(one) != 1 || one[0].Name != "s2" || one[0].Root != list[1].Root { + t.Fatalf("show s2: %+v; want %+v", one, list[1]) + } + + // A snapshot being taken: listed only committed, and then it stays. The + // write before it is acknowledged first, so its cut is past s3's; a + // second write follows its start, and may land before or after its cut + // (the test claims nothing about it). + env.writeBlock(t, "s1", 3, pattern("ladder-b1-blk-D!")) + type result struct { + out, errOut string + code int + err error + } + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second) + done := make(chan result, 1) + joined := false + t.Cleanup(func() { // before the daemons stop: cancel and join the worker + cancel() + if !joined { + select { + case <-done: + case <-time.After(10 * time.Second): // runCLI's 5 s WaitDelay, with a margin + t.Error("snapshot s4 worker did not finish within 10 s of its cancellation: its completion is unresolved") + } + } + }) + go func() { + out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status, "--name", "s4") + done <- result{out, errOut, code, err} + }() + env.writeBlock(t, "s1", 4, pattern("ladder-b1-blk-E!")) + var observed []snapshotEntry + var r result + inFlightUnlisted := 0 // listings begun before s4 answered that did not show it + // The observation bound: every list probe runs within what is left of it, + // and a probe that returns after it fails the test. + deadline := time.Now().Add(160 * time.Second) + obs, obsCancel := context.WithDeadline(context.Background(), deadline) + defer obsCancel() + for running := true; running; { + select { + case r = <-done: + joined, running = true, false + default: + } + if running && time.Now().After(deadline) { + t.Fatal("snapshot s4 did not return within its bound") + } + list, err := env.listSnapshots(obs, "v1", "s4") + if err != nil || time.Now().After(deadline) { + t.Fatalf("listing s4 within the observation bound: %v", err) + } + var s4 *snapshotEntry + for _, e := range list { + e := e + s4 = &e + } + if running && s4 == nil { + inFlightUnlisted++ + } + switch { + case s4 == nil && len(observed) > 0: + t.Fatal("s4 was listed, then disappeared") + case s4 != nil && (s4.Root == "" || roots[s4.Root]): + t.Fatalf("s4 listed without a root of its own: %+v", *s4) + case s4 != nil: + observed = append(observed, *s4) + } + } + if r.err != nil || r.code != 0 { + t.Fatalf("snapshot s4: exit %d %v\n%s\n%s", r.code, r.err, r.out, r.errOut) + } + if inFlightUnlisted == 0 { + t.Fatalf("inconclusive: no listing ran while s4 was in flight and unlisted (%d listings saw it committed)", len(observed)) + } + t.Logf("s4: %d listings while in flight did not show it; %d showed it published", inFlightUnlisted, len(observed)) + var created snapshotInfo + if err := json.Unmarshal([]byte(r.out), &created); err != nil || created.Name != "s4" { + t.Fatalf("snapshot s4 answer: %v\n%s", err, r.out) + } + final := env.snapshots(t, "v1", "s4") + if len(final) != 1 { + t.Fatalf("s4 not listed after its snapshot returned: %+v", final) + } + for _, o := range observed { + if o.Root != final[0].Root { + t.Fatalf("s4 listed as %+v while in flight, then as %+v: a listed snapshot changed", o, final[0]) + } + } + + // A snapshot of a restore target that is not fully local is taken, and + // names the source's chunks, so a restore from it is refused. + env.restoreAttached(t, "v1", "s1", "v2") + if st := kzReadStats(t, env.hosts["n-v2"]); st.AbsentChunks == 0 { + t.Fatalf("setup: v2 holds every chunk already; want a restore target not fully local") + } + env.snapshot(t, "n-v2", "v2", "x") + if l := env.snapshots(t, "v2", ""); len(l) != 1 || l[0].Name != "x" { + t.Fatalf("v2's snapshot x is not listed: %+v", l) + } + out, errOut, code := env.h.run(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v2", "--snapshot", "x", "--target", "v3", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + if code == 0 || !strings.Contains(out, `"code":"restore_source_not_own"`) || !strings.Contains(out, "names another volume's chunks") { + t.Fatalf("restore from a restore target's snapshot: exit %d, want restore_source_not_own naming another volume's chunks\n%s\n%s", code, out, errOut) + } +} + +// lastCutUploads is the number of chunks the last cut of vol uploaded, from +// its host's durable status. +func (env *handoffEnv) lastCutUploads(t *testing.T, hostID, vol string) int { + t.Helper() + c := &http.Client{Timeout: 5 * time.Second} + resp, err := c.Get("http://" + env.hosts[hostID].status + "/status/durable?volume=" + vol) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + n, err := lastCutUploadedChunks(body, vol) + if err != nil { + t.Fatal(err) + } + return n +} + +// restoreInto restores snapshot snap of src into the new volume target, as +// the deployment page says: create it, start its blockvolume, start the +// restore driver there; it serves at once. +func (env *handoffEnv) restoreInto(t *testing.T, src, snap, target string) { + t.Helper() + b := env.hosts["n-"+target] + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", src, "--snapshot", snap, "--target", target, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + d := env.h.start(t, "blockvolume-"+target, env.h.volume, env.volArgsFor(b)...) + waitC3RecoveryPrimary(t, d, b.status, target) + poll(t, 60*time.Second, fmt.Sprintf("%s never reported its frontend ready", target), func() bool { + return volumeFrontendReady(b.status, target) + }) +} + +// requireEdges reads, through the host, a block in a chunk no test writes and +// the volume's last block: both must be zero (a manifest that silently +// drops trailing or untouched chunks would otherwise go unseen). +func (env *handoffEnv) requireEdges(t *testing.T, hostID string) { + t.Helper() + env.requireBlocks(t, hostID, ladderUntouched, 1, nil) + env.requireBlocks(t, hostID, ladderLastBlock, 1, nil) +} + +// requireBlocks reads n blocks from lba on the host and requires each to be +// want[lba] (zeros where want has none). +func (env *handoffEnv) requireBlocks(t *testing.T, hostID string, lba uint64, n int, want map[uint64][]byte) { + t.Helper() + zero := make([]byte, 4096) + c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN) + defer c.close() + var bad []string + for i := uint64(0); i < uint64(n); i++ { + exp, ok := want[lba+i] + if !ok { + exp = zero + } + if got := c.read(t, lba+i, 4096); !bytes.Equal(got, exp) { + bad = append(bad, fmt.Sprint(lba+i)) + } + } + if len(bad) > 0 { + t.Fatalf("%s: blocks %s differ from the snapshot's point", hostID, strings.Join(bad, ",")) + } +} + +// prefixLength reads n blocks from first on the host and returns k such +// that blocks first .. first+k-1 hold blockAt and the rest are zero; any +// other picture (a later write present while an earlier one is missing, a +// torn block) fails the test: the snapshot was not one point in time. +func (env *handoffEnv) prefixLength(t *testing.T, hostID string, first uint64, n int, blockAt func(uint64) []byte) int { + t.Helper() + zero := make([]byte, 4096) + c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN) + defer c.close() + k, ended := 0, false + for i := 0; i < n; i++ { + lba := first + uint64(i) + got := c.read(t, lba, 4096) + switch { + case !ended && bytes.Equal(got, blockAt(lba)): + k++ + case bytes.Equal(got, zero): + ended = true + default: + t.Fatalf("%s: block %d after the snapshot's prefix of %d holds data: not one point in time", hostID, lba, k) + } + } + return k +} + +func volumeFrontendReady(statusAddr, vol string) bool { + c := &http.Client{Timeout: 2 * time.Second} + resp, err := c.Get("http://" + statusAddr + "/status?volume=" + vol) + if err != nil { + return false + } + defer resp.Body.Close() + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + return frontendReady(b) +} + +// hydrate makes every chunk of target local and checks that none is left +// absent. v1 has no background fill: a restore target fetches a chunk from +// its source's snapshot only when the guest touches it, so this reads one +// block of every chunk (which brings the whole chunk local), then waits for +// the chunk status to show no chunk absent. A restored volume keeps its +// references to the source's snapshot; hydration only makes it read locally. +func (env *handoffEnv) hydrate(t *testing.T, target string) { + t.Helper() + b := env.hosts["n-"+target] + c := dialNVMe(t, b.nvme, plannedHandoffNQN) + // A read fetches its chunk only when the block read is not local: a + // block the guest wrote is served locally and fills nothing. So read + // each chunk's last block, which no ladder image writes (ladderImage + // writes offsets 0, 37, 74, ... in a chunk). + for lba := uint64(ladderChunkBlocks - 1); lba <= ladderLastBlock; lba += ladderChunkBlocks { + _ = c.io.SetDeadline(time.Now().Add(60 * time.Second)) + c.read(t, lba, 4096) + } + c.close() + const bound = 60 * time.Second + end := time.Now().Add(bound) + last := -1 + for time.Now().Before(end) { + if last = kzReadStats(t, b).AbsentChunks; last == 0 { + return + } + time.Sleep(200 * time.Millisecond) + } + t.Fatalf("%s: every chunk was read, yet %d are still absent after %v", target, last, bound) +} + +// runCLI runs sw-block under ctx and returns its output and exit status. It +// never fails the test, so a worker goroutine may call it; a failure to run +// or a cancelled context comes back as err. +func runCLI(ctx context.Context, h *plannedHandoffHarness, args ...string) (string, string, int, error) { + cmd := exec.CommandContext(ctx, h.cli, args...) + cmd.Dir = h.dir + cmd.WaitDelay = 5 * time.Second + var stdout, stderr strings.Builder + cmd.Stdout, cmd.Stderr = &stdout, &stderr + err := cmd.Run() + h.logCommand(args, stdout.String(), stderr.String(), err) + var exit *exec.ExitError + switch { + case err == nil: + return stdout.String(), stderr.String(), 0, nil + case errors.As(err, &exit) && ctx.Err() == nil: + return stdout.String(), stderr.String(), exit.ExitCode(), nil + } + return stdout.String(), stderr.String(), -1, fmt.Errorf("sw-block %q: %w", args, err) +} + +// ladderImage is a written picture of a volume: blocks in several chunks. +func ladderImage(tag string, chunks []uint64, perChunk int) map[uint64][]byte { + img := map[uint64][]byte{} + for _, c := range chunks { + for i := 0; i < perChunk; i++ { + lba := c*ladderChunkBlocks + uint64(i)*37 + img[lba] = pattern(fmt.Sprintf("%-8s%08d", tag, lba)[:16]) + } + } + return img +} + +func (env *handoffEnv) writeImage(t *testing.T, hostID string, img map[uint64][]byte) { + t.Helper() + c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN) + defer c.close() + for lba, b := range img { + c.write(t, lba, b) + } + c.flush(t) +} + +// requireImage reads every block of img on the host and the zeros next to +// each written run, and the edge blocks. Every block of later (writes made +// after the snapshot that img pictures) that img does not hold must read +// zero: data written after the snapshot must not leak into its restore. +func (env *handoffEnv) requireImage(t *testing.T, hostID string, img map[uint64][]byte, later ...map[uint64][]byte) { + t.Helper() + zero := make([]byte, 4096) + c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN) + defer c.close() + for lba, want := range img { + if got := c.read(t, lba, 4096); !bytes.Equal(got, want) { + t.Fatalf("%s: block %d differs from the snapshot", hostID, lba) + } + if _, written := img[lba+1]; !written && lba+1 <= ladderLastBlock { + if got := c.read(t, lba+1, 4096); !bytes.Equal(got, zero) { + t.Fatalf("%s: block %d should be zero", hostID, lba+1) + } + } + } + for _, l := range later { + for lba := range l { + if _, held := img[lba]; held { + continue // an overwrite: img's value was checked above + } + if got := c.read(t, lba, 4096); !bytes.Equal(got, zero) { + t.Fatalf("%s: block %d was written after the snapshot and should read zero", hostID, lba) + } + } + } + c.close() + env.requireEdges(t, hostID) +} + +func mergeImages(imgs ...map[uint64][]byte) map[uint64][]byte { + out := map[uint64][]byte{} + for _, img := range imgs { + for k, v := range img { + out[k] = v + } + } + return out +} + +// TestSnapshotLadderC1FullRestore: blocks in five chunks are written and a +// snapshot taken, then some of them overwritten and new chunks written; the +// snapshot's restore into a new volume, once its status says independent, +// equals the snapshot block by block, without the later writes. +func TestSnapshotLadderC1FullRestore(t *testing.T) { + env := startLadderEnv(t, "v2") + img := ladderImage("c1", []uint64{0, 1, 7, 20, 63}, 8) + env.writeImage(t, "s1", img) + env.snapshot(t, "s1", "v1", "full") + later := mergeImages(ladderImage("c1later", []uint64{1, 20}, 8), ladderImage("c1new", []uint64{9, 33}, 3)) + env.writeImage(t, "s1", later) + env.restoreInto(t, "v1", "full", "v2") + env.hydrate(t, "v2") + env.requireImage(t, "n-v2", img, later) +} + +// TestSnapshotLadderC2IncrementalRestore: three snapshots, each after more +// writes; the restores of the second and the third, each to independence, +// equal those snapshots (the earlier writes and theirs, nothing later). +func TestSnapshotLadderC2IncrementalRestore(t *testing.T) { + env := startLadderEnv(t, "v2", "v3") + img1 := ladderImage("c2one", []uint64{0, 5}, 4) + img2 := ladderImage("c2two", []uint64{5, 9}, 3) // overwrites some of chunk 5 + img3 := ladderImage("c2three", []uint64{0, 30}, 2) + env.writeImage(t, "s1", img1) + env.snapshot(t, "s1", "v1", "s1") + env.writeImage(t, "s1", img2) + env.snapshot(t, "s1", "v1", "s2") + env.writeImage(t, "s1", img3) + env.snapshot(t, "s1", "v1", "s3") + + env.restoreInto(t, "v1", "s2", "v2") + env.hydrate(t, "v2") + env.requireImage(t, "n-v2", mergeImages(img1, img2), img3) // nothing written after s2, chunk 30 included + env.restoreInto(t, "v1", "s3", "v3") + env.hydrate(t, "v3") + env.requireImage(t, "n-v3", mergeImages(img1, img2, img3)) +} + +// TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt: a restored volume, +// once every chunk is local, is written and snapshotted itself, then +// written again. Its snapshot still names the source's chunks for the +// chunks it did not write (filling makes bytes local; it does not take the +// source's chunks over), so a restore from it is refused, naming another +// volume's chunks. The restored volume reads its own image, and the +// source's snapshot, also written past, still restores unchanged. +func TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt(t *testing.T) { + env := startLadderEnv(t, "v2", "v3", "v4") + src := ladderImage("c3src", []uint64{0, 3}, 4) + env.writeImage(t, "s1", src) + env.snapshot(t, "s1", "v1", "base") + srcLater := ladderImage("c3srclater", []uint64{3, 15}, 2) + env.writeImage(t, "s1", srcLater) + + env.restoreInto(t, "v1", "base", "v2") + env.hydrate(t, "v2") + own := ladderImage("c3own", []uint64{3, 11}, 3) + env.writeImage(t, "n-v2", own) + env.snapshot(t, "n-v2", "v2", "mine") + ownLater := ladderImage("c3ownlater", []uint64{0, 11, 25}, 2) + env.writeImage(t, "n-v2", ownLater) + + out, errOut, code := env.h.run(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v2", "--snapshot", "mine", "--target", "v3", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + if code == 0 || !strings.Contains(out, `"code":"restore_source_not_own"`) || !strings.Contains(out, "names another volume's chunks") { + t.Fatalf("restore from the restored volume's snapshot: exit %d, want restore_source_not_own naming another volume's chunks\n%s\n%s", code, out, errOut) + } + env.requireImage(t, "n-v2", mergeImages(src, own, ownLater), srcLater) + env.restoreInto(t, "v1", "base", "v4") // the source's snapshot is unchanged + env.hydrate(t, "v4") + env.requireImage(t, "n-v4", src, srcLater, own, ownLater) +} diff --git a/seaweed-block/cmd/blockvolume/snapshot_operation_crash_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_operation_crash_integration_test.go new file mode 100644 index 0000000000..91a7bbbbc0 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_operation_crash_integration_test.go @@ -0,0 +1,269 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os/exec" + "path" + "reflect" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +type snapshotOperationAnswer struct { + Handle string `json:"handle"` + ID string `json:"operation_id"` + State string `json:"state"` + Result json.RawMessage `json:"result"` +} + +type snapshotOperationAdmission struct { + answer snapshotOperationAnswer + location string + err error +} + +func snapshotOperationPost(ctx context.Context, addr, id string) snapshotOperationAdmission { + body, err := json.Marshal(map[string]any{"volumeID": "v1", "name": "daily", "requestID": id, "timeoutMs": 30000}) + if err != nil { + return snapshotOperationAdmission{err: err} + } + req, err := http.NewRequestWithContext(ctx, "POST", "http://"+addr+"/chunk/snapshot", bytes.NewReader(body)) + if err != nil { + return snapshotOperationAdmission{err: err} + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Prefer", "respond-async") + resp, err := http.DefaultClient.Do(req) + if err != nil { + return snapshotOperationAdmission{err: err} + } + defer resp.Body.Close() + var a snapshotOperationAnswer + err = json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&a) + if resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusOK { + err = fmt.Errorf("admission status=%d, want 202: %w", resp.StatusCode, err) + } + return snapshotOperationAdmission{a, resp.Header.Get("Location"), err} +} + +func snapshotOperationWasKilled(err error) bool { + var exit *exec.ExitError + if !errors.As(err, &exit) { + return false + } + ws, ok := exit.Sys().(syscall.WaitStatus) + return ok && ws.Signaled() && ws.Signal() == syscall.SIGKILL +} + +// Hold an applied Begin (before publication), or the applied snapshot Commit +// (before its reply can allow receipt settlement), and kill the actual holder. +// Admission must already have returned a durable operation handle. A missed +// admission/boundary is a failure, never credited as a crash campaign. +func TestSnapshotOperationIntentAndPublicationCrashBoundaries(t *testing.T) { + for _, kind := range []string{"BEGIN", "COMMIT"} { + t.Run(kind, func(t *testing.T) { + if testListenHost() != "127.0.0.1" { + t.Fatal("causal filer fixture requires loopback") + } + var boundary *snapshotFilerBoundary + cluster := startWorkspaceWeedWith(t, t.TempDir(), w4WeedOpts{VolumeSizeLimitMB: 256, VolumeMax: 32, FilerBind: "127.0.0.2", FilerFront: func(c *w4WeedCluster) { boundary = newSnapshotFilerBoundary(t, c) }}) + env := startHandoffEnvOnCluster(t, 1, nil, procedureTLSConfig(), false, cluster) + id, err := layout.ParseVolumeID(env.layoutID("v1")) + if err != nil { + t.Fatal(err) + } + boundary.id = id + boundary.dir = path.Join(env.chunkPath, layout.VolumeDir("v1", id)) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + holder := env.start(t, "snapshot-operation-holder", "s1") + epoch := env.adopt(t, holder, "s1") + env.writeBlock(t, "s1", 0, pattern("op-image-A!!!!!!")) + requestID := "crash-original-operation" + reached := boundary.arm(kind, "daily") + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second) + done := make(chan snapshotOperationAdmission, 1) + go func() { done <- snapshotOperationPost(ctx, env.hosts["s1"].status, requestID) }() + // Cleanup always releases the remote boundary, cancels and joins the + // request before the fixture closes its filer and holder processes. + joined := false + defer func() { + boundary.unblock() + cancel() + if !joined { + <-done + } + }() + var admitted snapshotOperationAdmission + select { + case <-reached: + case admitted = <-done: + joined = true + if admitted.err != nil { + t.Fatalf("admission failed before crash boundary %s: %+v", kind, admitted) + } + // Asynchronous admission may return before the worker reaches + // its filer write. Still require that actual held boundary before + // killing; an accepted answer alone is never a crash witness. + select { + case <-reached: + case <-time.After(30 * time.Second): + t.Fatal("accepted operation did not reach the actual filer boundary") + } + case <-time.After(30 * time.Second): + t.Fatal("snapshot did not reach the actual filer boundary") + } + if !joined { + select { + case admitted = <-done: + joined = true + case <-time.After(2 * time.Second): + t.Fatal("no asynchronous durable-intent admission before the held write; no kill credited") + } + } + if admitted.err != nil || admitted.answer.ID != requestID || admitted.location == "" || (admitted.answer.State != "accepted" && admitted.answer.State != "running") { + t.Fatalf("durable intent admission required before kill: %+v", admitted) + } + issued, err := url.Parse(admitted.location) + if err != nil || admitted.answer.Handle != admitted.location || issued.Query().Get("instance") == "" || issued.Query().Get("sequence") == "" || issued.Query().Get("volume_id") != id.String() { + t.Fatalf("kill requires a volume-bound issued incarnation, not only a display ID: %+v err=%v", admitted, err) + } + if held, why := boundary.stillHeld(); !held { + t.Fatalf("boundary escaped before kill: %s", why) + } + holder.kill(t) + if !snapshotOperationWasKilled(holder.err) { + t.Fatalf("not a SIGKILL receipt: %v", holder.err) + } + crashed := boundary.head(t) + _, published := crashed.Snapshots["daily"] + if published != (kind == "COMMIT") { + t.Fatalf("publication boundary mismatch: %+v", crashed) + } + boundary.unblock() + holder = env.start(t, "snapshot-operation-restarted", "s1") + if got := env.adopt(t, holder, "s1"); got != epoch { + t.Fatalf("restart changed epoch %d -> %d", epoch, got) + } + poll(t, 60*time.Second, "restarted holder did not become ready", func() bool { return env.frontendReadyAt("s1") }) + if got := env.readBlock(t, "s1", 0); !bytes.Equal(got, pattern("op-image-A!!!!!!")) { + t.Fatal("restart lost acknowledged image A") + } + before := boundary.head(t) + base, err := url.Parse("http://" + env.hosts["s1"].status) + if err != nil { + t.Fatal(err) + } + loc, err := url.Parse(admitted.location) + if err != nil { + t.Fatal(err) + } + statusURL := base.ResolveReference(loc).String() + // Read the original handle BEFORE a retry can admit another intent. + client := &http.Client{Timeout: 2 * time.Second} + resp, err := client.Get(statusURL) + if err != nil { + t.Fatal(err) + } + var recovered snapshotOperationAnswer + decodeErr := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&recovered) + _ = resp.Body.Close() + if resp.StatusCode != 200 || decodeErr != nil || recovered.ID != requestID || recovered.Handle != admitted.location || + (recovered.State != "accepted" && recovered.State != "running" && recovered.State != "stalled" && recovered.State != "succeeded") { + t.Fatalf("original durable intent missing after kill, before retry: status=%d answer=%+v err=%v", resp.StatusCode, recovered, decodeErr) + } + retryCtx, retryCancel := context.WithTimeout(context.Background(), 10*time.Second) + retry := snapshotOperationPost(retryCtx, env.hosts["s1"].status, requestID) + retryCancel() + if retry.err != nil || retry.answer.ID != requestID || retry.location != admitted.location || retry.answer.Handle != admitted.location { + t.Fatalf("same-id restart admission: %+v", retry) + } + var terminal snapshotOperationAnswer + poll(t, 30*time.Second, "restarted operation did not settle", func() bool { + resp, err := client.Get(statusURL) + if err != nil { + return false + } + defer resp.Body.Close() + if err = json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&terminal); err != nil { + return false + } + return resp.StatusCode == 200 && terminal.ID == requestID && terminal.Handle == admitted.location && terminal.State == "succeeded" + }) + after := boundary.head(t) + snap, ok := after.Snapshots["daily"] + if !ok { + t.Fatal("restart lost the operation's snapshot") + } + if published { + if !reflect.DeepEqual(before, after) || !reflect.DeepEqual(crashed.Snapshots["daily"], snap) { + t.Fatalf("published operation cut again during settlement: before=%+v after=%+v", before, after) + } + } else if after.Current == nil || snap.Position == 0 || len(after.Snapshots) != 1 { + t.Fatalf("intent-before-publish must complete exactly one snapshot publication: before=%+v after=%+v", before, after) + } + var outcome struct { + Gen uint64 `json:"headGen"` + Position uint64 `json:"cutLSN"` + Created int64 `json:"createdNs"` + } + if err := json.Unmarshal(terminal.Result, &outcome); err != nil || outcome.Position != snap.Position || outcome.Created != snap.Meta.CreatedNs || outcome.Gen == 0 || published && outcome.Gen != crashed.Gen { + t.Fatalf("settled receipt lost its original outcome: result=%s snapshot=%+v err=%v", terminal.Result, snap, err) + } + statusResp, err := client.Get("http://" + env.hosts["s1"].status + "/status/durable?volume=v1") + if err != nil { + t.Fatal(err) + } + var counters struct { + ProcessID string + Volumes []struct { + VolumeID string + HeadWrites map[string]uint64 + } + } + decodeErr = json.NewDecoder(io.LimitReader(statusResp.Body, 1<<20)).Decode(&counters) + _ = statusResp.Body.Close() + if statusResp.StatusCode != 200 || decodeErr != nil || counters.ProcessID == "" || len(counters.Volumes) != 1 || counters.Volumes[0].VolumeID != "v1" || counters.Volumes[0].HeadWrites == nil { + t.Fatalf("missing typed restarted-process counters: %+v err=%v", counters, decodeErr) + } + wantCommits := uint64(1) + if published { + wantCommits = 0 + } + if got := counters.Volumes[0].HeadWrites["commit"]; got != wantCommits { + t.Fatalf("restart published %d cuts, want %d", got, wantCommits) + } + // Different live bytes make an erroneous second cut observable. The + // original handle must still return its first result without HEAD writes. + env.writeBlock(t, "s1", 0, pattern("op-image-B!!!!!!")) + out, _ := env.h.command(t, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status, "--name", "daily", "--request-id", requestID) + if !reflect.DeepEqual(after, boundary.head(t)) { + t.Fatalf("retained operation performed a second cut: %s", out) + } + }) + } +} + +func TestSnapshotOperationKillReceiptRejectsOrdinaryExit(t *testing.T) { + if snapshotOperationWasKilled(nil) || snapshotOperationWasKilled(errors.New("timeout")) { + t.Fatal("non-kill credited") + } + err := exec.Command("/bin/false").Run() + if err == nil { + t.Fatal("negative-control process did not fail") + } + if snapshotOperationWasKilled(err) { + t.Fatalf("ordinary failing exit credited as SIGKILL: %v", err) + } +} diff --git a/seaweed-block/cmd/blockvolume/snapshot_operation_shutdown.go b/seaweed-block/cmd/blockvolume/snapshot_operation_shutdown.go new file mode 100644 index 0000000000..a6f3653151 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_operation_shutdown.go @@ -0,0 +1,28 @@ +package main + +import ( + "context" + "fmt" + "time" +) + +type snapshotOperationStopper interface{ StopSnapshotOperations(context.Context) error } + +func stopSnapshotOperationsForShutdown(status snapshotOperationStopper) error { + if status == nil { + return nil + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + return status.StopSnapshotOperations(ctx) +} + +// A failed join must not release the storage files the worker still borrows. +// The caller carries this error into its drain verdict rather than ACKing a +// close that only requested cancellation. +func closeProviderAfterSnapshotOperations(status snapshotOperationStopper, closeProvider func() error) error { + if err := stopSnapshotOperationsForShutdown(status); err != nil { + return fmt.Errorf("stop snapshot operations: %w", err) + } + return closeProvider() +} diff --git a/seaweed-block/cmd/blockvolume/snapshot_operation_shutdown_test.go b/seaweed-block/cmd/blockvolume/snapshot_operation_shutdown_test.go new file mode 100644 index 0000000000..017945492a --- /dev/null +++ b/seaweed-block/cmd/blockvolume/snapshot_operation_shutdown_test.go @@ -0,0 +1,37 @@ +package main + +import ( + "context" + "errors" + "testing" +) + +type snapshotStopProbe struct { + err error + stopped *bool +} + +func (s snapshotStopProbe) StopSnapshotOperations(ctx context.Context) error { + *s.stopped = true + return s.err +} + +func TestSnapshotOperationShutdownJoinsBeforeStorageClose(t *testing.T) { + stopped, closed := false, false + err := closeProviderAfterSnapshotOperations(snapshotStopProbe{stopped: &stopped}, func() error { + if !stopped { + t.Error("storage closed before its snapshot borrower stopped") + } + closed = true + return nil + }) + if err != nil || !closed { + t.Fatalf("shutdown: closed=%v err=%v", closed, err) + } + stopped, closed = false, false + refusal := errors.New("snapshot worker did not join") + err = closeProviderAfterSnapshotOperations(snapshotStopProbe{stopped: &stopped, err: refusal}, func() error { closed = true; return nil }) + if !errors.Is(err, refusal) || closed { + t.Fatalf("unjoined borrower allowed storage close: closed=%v err=%v", closed, err) + } +} diff --git a/seaweed-block/cmd/blockvolume/start_any_test.go b/seaweed-block/cmd/blockvolume/start_any_test.go new file mode 100644 index 0000000000..a6d3255409 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/start_any_test.go @@ -0,0 +1,7 @@ +package main + +import "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + +// anyStart is a local root that can start from any HEAD: these tests do +// not model the local store. +func anyStart(layout.Head) error { return nil } diff --git a/seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go b/seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go new file mode 100644 index 0000000000..e7640e49c1 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/startup_nvme_integration_test.go @@ -0,0 +1,34 @@ +//go:build linux && subprocess && chunkstore_integration && systemd_integration + +package main_test + +import ( + "bytes" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" +) + +// This small initiator uses the same exported wire types and admin/IO queue +// handshake as core/frontend/nvme/client_support_test.go. It talks only to the +// real blockvolume in this harness; no kernel device or unrelated NQN is used. +// Calibration of the witness client only, not a systemd/re-grant proof. +func TestGAP1NVMeWitnessRoundTripsAcknowledgedBlock(t *testing.T) { + backend := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1}) + nqn := "nqn.2026-11.test:gap1-witness-calibration" + target := nvme.NewTarget(nvme.TargetConfig{Listen: "127.0.0.1:0", SubsysNQN: nqn, VolumeID: "v", Provider: testback.NewStaticProvider(backend), Handler: nvme.HandlerConfig{NSID: 1, BlockSize: 4096, VolumeSize: 64 * 4096}}) + addr, err := target.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = target.Close() }) + c := gap1ConnectNVMe(t, addr, nqn) + want := bytes.Repeat([]byte{0x6d}, 4096) + c.writeFlush(t, 8, want) + c.readExact(t, 8, want) + if backend.WriteCount() != 1 || backend.SyncCount() != 1 || backend.ReadCount() != 1 { + t.Fatalf("witness bypassed backend write/flush/read: %d/%d/%d", backend.WriteCount(), backend.SyncCount(), backend.ReadCount()) + } +} diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go new file mode 100644 index 0000000000..20939e7f47 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/startup_systemd_filer_down_integration_test.go @@ -0,0 +1,145 @@ +//go:build linux && subprocess && chunkstore_integration && systemd_integration + +package main_test + +import ( + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// The operator guide's procedure for a first start during a long filer +// outage, run as written under real systemd (root): the blockvolume unit, +// with the shipped restart policy and a short start limit, starts while the +// filer is down; each start fails at the startup filer check (exit 1, no +// store) until systemd stops retrying (its start limit). The filer comes +// back; `systemctl +// reset-failed ` and `systemctl start ` then serve the volume. +// +// A runtime unit file (/run/systemd/system) stands for the installed unit: +// a transient systemd-run unit would be removed by reset-failed. +func TestSystemdFirstStartDuringAFilerOutageThenResetFailedServes(t *testing.T) { + if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" { + t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof") + } + if os.Geteuid() != 0 { + t.Fatal("systemd qualification needs root") + } + env := startSourceWithSnapshot(t, "v2") + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + b := env.hosts["n-v2"] + + shipped := gap1ShippedPolicy(t) + unit := fmt.Sprintf("swb-c04-filer-outage-%d.service", os.Getpid()) + unitPath := filepath.Join("/run/systemd/system", unit) + // Under systemd blockvolume refuses the test-only lock directory: the + // unit uses the real one, as an installed unit does. + quoted := []string{fmt.Sprintf("%q", env.h.volume)} + args := env.volArgsFor(b) + for i := 0; i < len(args); i++ { + if args[i] == "--volume-lock-dir-test-only" { + i++ + continue + } + quoted = append(quoted, fmt.Sprintf("%q", args[i])) + } + // Create the lock directory and its parent only if missing, and remove + // only what this test created (child first); nothing pre-existing is + // touched. + const lockDir = "/run/sw-block/locks" + var created []string + for _, dir := range []string{filepath.Dir(lockDir), lockDir} { + if _, err := os.Stat(dir); os.IsNotExist(err) { + if err := os.Mkdir(dir, 0o755); err != nil { + t.Fatal(err) + } + created = append(created, dir) + } + } + t.Cleanup(func() { + for i := len(created) - 1; i >= 0; i-- { + _ = os.Remove(created[i]) + } + }) + spec := strings.Join([]string{ + "[Unit]", + "Description=sw-block test unit: first start during a filer outage", + "StartLimitIntervalSec=600", + "StartLimitBurst=2", + "[Service]", + "Type=exec", + "ExecStart=" + strings.Join(quoted, " "), + "Restart=on-failure", + "RestartSec=" + shipped["RestartSec"], + "RestartPreventExitStatus=" + shipped["RestartPreventExitStatus"], + "TimeoutStopSec=" + shipped["TimeoutStopSec"], + "", + }, "\n") + systemctl := func(args ...string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() + return string(out), err + } + t.Cleanup(func() { + gap1CleanupUnit(t, unit) + _ = os.Remove(unitPath) + _, _ = systemctl("daemon-reload") + }) + if err := os.WriteFile(unitPath, []byte(spec), 0o644); err != nil { + t.Fatal(err) + } + if out, err := systemctl("daemon-reload"); err != nil { + t.Fatalf("daemon-reload: %v %s", err, out) + } + + env.cluster.stopProc(t, "filer") + if out, err := systemctl("start", "--no-block", unit); err != nil { + t.Fatalf("start %s: %v %s", unit, err, out) + } + // systemd gives up when the start limit is hit: the unit stays failed + // after StartLimitBurst restarts, and the journal says "Start request + // repeated too quickly" (systemd 249 keeps Result=exit-code). + var state map[string]string + poll(t, 8*time.Minute, unit+" never stopped retrying with the filer down", func() bool { + s, err := gap1ReadUnit(unit) + state = s + return err == nil && s["ActiveState"] == "failed" && s["NRestarts"] == "2" + }) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + journal, _ := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager").CombinedOutput() + cancel() + entries, _ := os.ReadDir(b.root) + t.Logf("filer down: %s gave up: Result %s, NRestarts %s, ExecMainStatus %s, ActiveState %s; files under --durable-root %d", + unit, state["Result"], state["NRestarts"], state["ExecMainStatus"], state["ActiveState"], len(entries)) + if !strings.Contains(string(journal), "Start request repeated too quickly") || state["ExecMainStatus"] != "1" { + t.Fatalf("the unit did not stop on its start limit after failing at the startup filer check (status %s):\n%s", state["ExecMainStatus"], journal) + } + if len(entries) != 0 { + t.Fatalf("the failed starts created %d files under --durable-root", len(entries)) + } + + env.cluster.restartProc(t, "filer") + w4WaitTCP(t, env.cluster.filerGRPC, 30*time.Second) + // The guide, as written: reset-failed, then start. + if out, err := systemctl("reset-failed", unit); err != nil { + t.Fatalf("systemctl reset-failed %s: %v %s", unit, err, out) + } + if out, err := systemctl("start", unit); err != nil { + t.Fatalf("systemctl start %s: %v %s", unit, err, out) + } + poll(t, 2*time.Minute, "v2 never served after reset-failed and start", func() bool { + return volumeFrontendReady(b.status, "v2") + }) + head := env.headOf(t, "v2") + if strings.Contains(head, `"holder":""`) { + t.Fatalf("v2 serves but its HEAD is not claimed: %s", head) + } + t.Logf("after reset-failed + start: v2 serves; HEAD %s", head) +} diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go new file mode 100644 index 0000000000..21efc4aa30 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -0,0 +1,975 @@ +//go:build linux && subprocess && chunkstore_integration && systemd_integration + +package main_test + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/auth/authtest" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + hostvolume "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/grpc" +) + +// Real systemd owns every restart. No test goroutine relaunches the holder. +// The first assertion is RED on GAP-1: the expired startup stays alive. +func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { + if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" { + t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof") + } + if os.Geteuid() != 0 { + t.Fatal("systemd qualification needs root") + } + if os.Getenv("CHUNKSTORE_WEED") == "" { + t.Fatal("real CHUNKSTORE_WEED binary required") + } + probeCtx, probeCancel := context.WithTimeout(context.Background(), 5*time.Second) + defer probeCancel() + if out, err := exec.CommandContext(probeCtx, "systemctl", "show", "--property=Version").CombinedOutput(); err != nil { + t.Fatalf("real systemd unavailable: %v %s", err, out) + } + // Under systemd the test lock override is refused: the units use the + // real host lock directory, which the shipped tmpfiles.d entry makes. + if err := os.MkdirAll(durable.HostVolumeLockDir, 0o700); err != nil { + t.Fatalf("host volume lock directory: %v", err) + } + fixture := newGAP1Fixture(t) + root := fixture.root + bin := filepath.Join(root, "bin") + if err := os.Mkdir(bin, 0755); err != nil { + t.Fatal(err) + } + for _, name := range []string{"blockvolume", "blockmaster"} { + buildCtx, buildCancel := context.WithTimeout(context.Background(), 2*time.Minute) + cmd := exec.CommandContext(buildCtx, "go", "build", "-p", "4", "-o", filepath.Join(bin, name), "../"+name) + cmd.WaitDelay = time.Second // bound inherited child pipes after cancellation + out, err := cmd.CombinedOutput() + buildCancel() + if err != nil { + t.Fatalf("real binary build: %v %s", err, out) + } + } + cluster := startWorkspaceWeedAt(t, filepath.Join(root, "weed")) + gap1PreserveFailure(t, root, cluster.dir) + stem := fmt.Sprintf("gap1-%d", time.Now().UnixNano()) + gap1ProbeTerminalSuccess(t, fixture, stem+"-policy-probe") + volume := stem + base := "/" + stem + masterAddr := leaseBinaryAddress(t) + target, masterListen := gap1TargetAddresses(t, masterAddr) + dataAddr, ctrlAddr, statusAddr, nvmeAddr := leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t) + cfg := fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\n - server_id: s2\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n - id: %s\n size_bytes: 262144\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: r1\n source: existing_replica\n", dataAddr, ctrlAddr, target.dataAddr, target.ctrlAddr, volume) + spec := filepath.Join(root, "cluster.yaml") + if err := os.WriteFile(spec, []byte(cfg), 0600); err != nil { + t.Fatal(err) + } + // The master listens off loopback, so it runs with mutual TLS: the test + // is an admin, s1 and s2 are nodes (certificates in root/tls). + tlsDir := gap1WriteTLS(t, root, target) + fixture.start(t, stem+"-master", false, filepath.Join(bin, "blockmaster"), + "--listen", masterListen, "--tls-cert", filepath.Join(tlsDir, "master.crt"), "--tls-key", filepath.Join(tlsDir, "master.key"), + "--tls-client-ca", filepath.Join(tlsDir, "ca.crt"), "--role-file", filepath.Join(tlsDir, "roles"), "--audit-log", filepath.Join(tlsDir, "audit.log"), "--authority-store", filepath.Join(root, "auth"), "--lifecycle-store", filepath.Join(root, "life"), + "--cluster-spec", spec, "--lifecycle-product-loop-interval", "200ms", "--expected-slots-per-volume", "1", + "--workspace-rpc", + // A workspace master writes the layout VOLUME and unclaimed HEAD itself. + "--chunk-filer", cluster.filerGRPC, "--chunk-path", base) + w4WaitTCP(t, masterAddr, 20*time.Second) + admin, err := link.ClientCredentials(link.TLSFiles{Cert: filepath.Join(tlsDir, "admin.crt"), Key: filepath.Join(tlsDir, "admin.key"), CA: filepath.Join(tlsDir, "ca.crt")}, "") + if err != nil { + t.Fatal(err) + } + conn, err := grpc.NewClient(masterAddr, admin) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + ws := control.NewWorkspaceServiceClient(conn) + // The master mints the volume's layout identity; the holder and every + // HEAD read name it. + var layoutID layout.VolumeID + waitGAP1(t, "master never resolved the volume's layout identity", 20*time.Second, func() bool { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + id, e := lifecycleclient.ResolveVolume(ctx, control.NewLifecycleServiceClient(conn), volume) + layoutID = id + return e == nil + }) + args := []string{"--master", masterAddr, "--server-id", "s1", + "--master-tls-cert", filepath.Join(tlsDir, "s1.crt"), "--master-tls-key", filepath.Join(tlsDir, "s1.key"), "--master-ca", filepath.Join(tlsDir, "ca.crt"), + "--volume-id", volume, "--replica-id", "r1", "--layout-id", layoutID.String(), + "--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--heartbeat-interval", "200ms", "--t1-readiness", "--status-addr", statusAddr, + "--durable-root", filepath.Join(root, "store"), "--durable-impl", "walstore-chunk", "--durable-blocks", "64", + "--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease", + "--nvme-listen", nvmeAddr, "--nvme-subsysnqn", "nqn.2026-11.test:" + stem} + // Bootstrap is a different, non-restarting unit. Kill only this exact unit. + bootstrap := stem + "-bootstrap" + fixture.start(t, bootstrap, false, filepath.Join(bin, "blockvolume"), args...) + waitGAP1(t, "bootstrap did not attach under a real lease", 60*time.Second, func() bool { return gap1Operational(t, statusAddr, volume) }) + // Calibrate the readiness parser on the serving source's actual /status + // response before using it for the target's negative readiness assertion. + waitGAP1(t, "source readiness control never became true", 20*time.Second, func() bool { + status, body, err := gap1StatusAt(statusAddr, volume, "/status") + if err != nil || status != http.StatusOK { + return false + } + serving, err := gap1Readiness(status, body, volume) + if err != nil { + t.Fatal(err) + } + if serving { + t.Logf("captured real readiness control: status%d body%s", status, body) + } + return serving + }) + // Calibrate verdict parsing against actual binary responses BEFORE kill. + status, payload, err := gap1Status(statusAddr, volume) + t.Logf("captured real status200: status%d body%s", status, payload) + if err != nil || !gap1StatusOperational(status, payload, volume) { + t.Fatalf("real status200 parser control: %v", err) + } + missing, body404, err := gap1Status(statusAddr, volume+"-not-served") + t.Logf("captured real status404: status%d body%s", missing, body404) + if err != nil || missing != http.StatusNotFound || gap1StatusOperational(missing, body404, volume) { + t.Fatalf("real status404 parser control: %v", err) + } + want := bytes.Repeat([]byte{0x6d}, 4096) + client := gap1ConnectNVMe(t, nvmeAddr, "nqn.2026-11.test:"+stem) + client.writeFlush(t, 8, want) + t.Logf("acknowledged NVMe record: lba=8 bytes=%d sha256=%x", len(want), sha256.Sum256(want)) + client.readExact(t, 8, want) + client.close() + remote := cluster.remote(t, base, chunkstore.VolumeRef{Name: volume, ID: layoutID}) + before, err := gap1ReadHead(t, remote) + if err != nil || before.Gen == 0 { + t.Fatalf("bootstrap HEAD: %+v %v", before, err) + } + gap1Systemctl(t, "kill", "--signal=KILL", "--kill-who=main", bootstrap) + waitGAP1(t, "bootstrap still running", 10*time.Second, func() bool { return gap1Unit(t, bootstrap)["MainPID"] == "0" }) + // HEAD as the killed holder left it (no process can move it now). + ref := chunkstore.VolumeRef{Name: volume, ID: layoutID} + atKill := layoutHead(t, cluster, base, ref) + if atKill.Holder != "s1/r1" || atKill.ClaimID == "" || atKill.State != layout.StateLive { + t.Fatalf("HEAD at the kill: %+v; want live, held by s1/r1 under a claim", atKill) + } + // QueryWorkspace is read-only. These real binaries and this test share + // one WSL kernel wall clock. Use the reported MASTER expiry timestamp, + // not ValidForNs (which ends half a skew earlier and could renew live). + // No product barrier formula or fake master clock is introduced. + waitGAP1(t, "holder's reported validity never lapsed", 60*time.Second, func() bool { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + s, e := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: volume}) + if e != nil || s.GetLease() == nil { + return false + } + t.Logf("captured master lease: %s", s.String()) + return s.Lease.ValidForNs <= 0 && time.Now().UnixNano() >= s.Lease.ExpiresAtNs + }) + unit := stem + "-returning" + fixture.start(t, unit, true, filepath.Join(bin, "blockvolume"), args...) + first := gap1Unit(t, unit) + t.Logf("captured effective restart policy: %+v", first) + firstPID := first["MainPID"] + if firstPID == "0" { + t.Fatal("returning unit did not start a real process") + } + // The returning process waits in process for the master's barrier and + // serves after it, with no fence exit and no restart (the startup wait, + // #535): first it reports the barrier as its MasterWait, never serving. + var barrierMs int64 + waitGAP1(t, "returning unit never reported the master's barrier", 30*time.Second, func() bool { + if gap1Operational(t, statusAddr, volume) { + t.Fatal("the returning unit served before reporting a barrier wait: an expired lease was re-granted without the barrier") + } + if s := gap1Unit(t, unit); s["MainPID"] != firstPID { + t.Fatalf("the returning unit exited while waiting for the barrier: %+v", s) + } + if w := gap1MasterWait(t, statusAddr, volume); w.Reason == "barrier" && w.UntilMs > 0 { + barrierMs = w.UntilMs + t.Logf("captured master wait: reason=%s until=%d", w.Reason, w.UntilMs) + return true + } + return false + }) + // Then the same process serves: not before the barrier, and within the + // startup wait's bound (barrier + 30 s; the outer guard adds slack). + waitGAP1(t, "the returning unit never served after the barrier", 75*time.Second, func() bool { + s := gap1Unit(t, unit) + if s["MainPID"] != firstPID || s["NRestarts"] != "0" { + t.Fatalf("the returning unit restarted (a fence exit) instead of serving in process: %+v", s) + } + if !gap1Operational(t, statusAddr, volume) { + return false + } + if now := time.Now().UnixMilli(); now < barrierMs { + t.Fatalf("served at %d, before the master's barrier %d", now, barrierMs) + } + if late := time.Now().UnixMilli() - barrierMs; late > 30_000 { + t.Fatalf("served %d ms after the barrier: past the startup wait's 30 s bound", late) + } + return true + }) + // The holder returns with its own claim at the same epoch: over an idle + // HEAD it resumes with no HEAD write; a session of its claim left open at + // the kill is aborted (a HEAD write) before it serves. + after := layoutHead(t, cluster, base, ref) + if after.Holder != atKill.Holder || after.Epoch != atKill.Epoch || after.ClaimID != atKill.ClaimID || after.State != layout.StateLive || after.Activity.Kind != layout.ActIdle { + t.Fatalf("return did not resume its claim: at kill %+v, after %+v", atKill, after) + } + switch { + case atKill.Activity.Kind == layout.ActIdle && after.Gen != atKill.Gen: + t.Fatalf("return over an idle HEAD wrote it: gen %d -> %d", atKill.Gen, after.Gen) + case atKill.Activity.Kind != layout.ActIdle && after.Gen <= atKill.Gen: + t.Fatalf("return left the open %s session %q: gen %d -> %d", atKill.Activity.Kind, atKill.Activity.Session, atKill.Gen, after.Gen) + } + t.Logf("return resumed claim %s at epoch %d: activity at kill %s, gen %d -> %d", after.ClaimID, after.Epoch, atKill.Activity.Kind, atKill.Gen, after.Gen) + returned := gap1ConnectNVMe(t, nvmeAddr, "nqn.2026-11.test:"+stem) + returned.readExact(t, 8, want) + returned.writeFlush(t, 9, want) + returned.readExact(t, 9, want) + returned.close() + // A real control cut must pass the lease and layer gates after restart. + req, err := http.NewRequest(http.MethodPost, "http://"+statusAddr+"/chunk/cut", bytes.NewBufferString(fmt.Sprintf(`{"volumeID":%q,"timeoutMs":3000}`, volume))) + if err != nil { + t.Fatal(err) + } + resp, err := (&http.Client{Timeout: 5 * time.Second}).Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("post-regrant real cut status%d", resp.StatusCode) + } + s := gap1Unit(t, unit) + if s["Result"] == "start-limit-hit" { + t.Fatalf("systemd rate limit hit: %+v", s) + } + gap1PlannedStopDoesNotRestart(t, ws, unit, statusAddr, volume, after.Epoch, "r1", s["NRestarts"], s["InvocationID"]) + gap1PrestartedTargetServesAfterMove(t, fixture, ws, remote, target, stem, filepath.Join(bin, "blockvolume"), args, root, volume, want) + moved, err := gap1ReadHead(t, remote) + if err != nil || moved.Holder != "s2/r1" { + t.Fatal("target did not claim the moved line", moved, err) + } + gap1MovedSourceNeverServes(t, fixture, filepath.Join(bin, "blockvolume"), args, stem, statusAddr, volume, moved.Epoch) +} + +// gap1MovedSourceNeverServes is the negative case of the in-process wait: +// after the volume moved to another host (and the new holder stopped), the +// old source started again never serves and never adopts the line naming the +// other host. The master proves it was the issued move's source and returns +// typed MOVED even before any own assignment: exit 78, no restart loop. +func gap1MovedSourceNeverServes(t *testing.T, fixture *gap1Fixture, exe string, args []string, stem, statusAddr, volume string, epoch uint64) { + t.Helper() + // The simulated hosts share this kernel's per-host volume lock directory: + // stop the new holder (the prestarted target) so the old source can open + // its root at all; on real separate hosts the two never share a lock. + target := stem + "-prestarted-target" + gap1Systemctl(t, "stop", target) + waitGAP1(t, "the new holder did not stop", 30*time.Second, func() bool { return gap1Unit(t, target)["MainPID"] == "0" }) + unit := stem + "-moved-source" + fixture.start(t, unit, true, exe, args...) + waitGAP1(t, "the moved-away source never exited", 75*time.Second, func() bool { + if gap1Operational(t, statusAddr, volume) { + t.Fatal("the moved-away source served") + } + s := gap1Unit(t, unit) + switch s["ExecMainStatus"] { + case "", "0": + return false + case "78": + return true + } + t.Fatalf("the moved-away source exited %s; want 78 moved, never retry 75: %+v", s["ExecMainStatus"], s) + return false + }) + if gap1Operational(t, statusAddr, volume) { + t.Fatal("the moved-away source served after its exit") + } + // Observe beyond the shipped 5 s RestartSec. The prestarted target above + // is the opposite control: a genuine 75 was restarted by the same policy. + end := time.Now().Add(6 * time.Second) + for time.Now().Before(end) { + s := gap1Unit(t, unit) + if s["NRestarts"] != "0" || s["MainPID"] != "0" || s["ExecMainStatus"] != "78" { + t.Fatalf("moved source restarted or lost its terminal status: %+v", s) + } + time.Sleep(100 * time.Millisecond) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + journal, err := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=cat").CombinedOutput() + if err != nil || !strings.Contains(string(journal), "status=78 reason=moved") || !strings.Contains(string(journal), fmt.Sprintf("holder s2 at epoch %d", epoch)) { + t.Fatalf("moved exit lacks the master's destination proof: %v %s", err, journal) + } + if strings.Contains(string(journal), "adopted as PRIMARY") { + t.Fatalf("the moved-away source adopted a lineage:\n%s", journal) + } + gap1Systemctl(t, "stop", unit) +} + +// gap1MasterWait reads the volume's /status MasterWait (the startup wait's +// reason and the master's barrier time), zero when absent. +func gap1MasterWait(t *testing.T, addr, volume string) struct { + Reason string + UntilMs int64 +} { + t.Helper() + var out struct { + MasterWait *struct { + Reason string + UntilMs int64 + } + } + code, body, err := gap1StatusAt(addr, volume, "/status") + if err != nil || code != http.StatusOK || json.Unmarshal(body, &out) != nil || out.MasterWait == nil { + return struct { + Reason string + UntilMs int64 + }{} + } + return *out.MasterWait +} + +// Roots are deliberately independent of testing.TempDir: unknown unit cleanup +// must never remove an executable or WAL beneath a possible surviving service. +type gap1Fixture struct { + root string + units []string +} + +func newGAP1Fixture(t *testing.T) *gap1Fixture { + t.Helper() + root, err := os.MkdirTemp("", "gap1-runtime-") + if err != nil { + t.Fatal(err) + } + f := &gap1Fixture{root: root} + t.Cleanup(func() { + safe := true + for _, unit := range f.units { + state, err := gap1ReadUnit(unit) + if err != nil || !gap1UnitGone(state) { + t.Errorf("final unit absence unproved: %s state%v err%v", unit, state, err) + safe = false + } + } + if !safe || t.Failed() { + t.Logf("retained run root: %s (safe=%v failed=%v)", root, safe, t.Failed()) + return + } + if err := os.RemoveAll(root); err != nil { + t.Errorf("remove confirmed idle run root: %v", err) + } + }) + return f +} +func (f *gap1Fixture) start(t *testing.T, unit string, restart bool, exe string, args ...string) { + t.Helper() + f.units = append(f.units, unit) + // Persist ownership before the create, including an aggregate test crash. + ownership, err := os.OpenFile(filepath.Join(f.root, "owned-units.txt"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) + if err != nil { + t.Fatal(err) + } + _, writeErr := fmt.Fprintln(ownership, unit) + closeErr := ownership.Close() + if writeErr != nil || closeErr != nil { + t.Fatalf("record unit ownership: %v %v", writeErr, closeErr) + } + // Register BEFORE submission: systemd may create the unit even when the + // command loses its answer or times out. Every uncertain create is owned. + t.Cleanup(func() { gap1CleanupUnit(t, unit) }) + policy := "no" + if restart { + policy = "on-failure" + } + shipped := gap1ShippedPolicy(t) + cmdArgs := []string{"--unit=" + unit, "--property=Type=exec", "--property=Restart=" + policy, "--property=RestartSec=" + shipped["RestartSec"], "--property=RestartPreventExitStatus=" + shipped["RestartPreventExitStatus"], "--property=TimeoutStopSec=" + shipped["TimeoutStopSec"], "--property=StartLimitIntervalSec=10s", "--property=StartLimitBurst=5", "--", exe} + cmdArgs = append(cmdArgs, args...) + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + if out, err := exec.CommandContext(ctx, "systemd-run", cmdArgs...).CombinedOutput(); err != nil { + t.Fatalf("systemd-run %s (creation outcome uncertain; registered cleanup owns it): %v %s", unit, err, out) + } +} +func gap1CleanupUnit(t *testing.T, unit string) { + t.Helper() + command := func(bound time.Duration, args ...string) error { + ctx, cancel := context.WithTimeout(context.Background(), bound) + defer cancel() + out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() + if err != nil { + t.Logf("unit cleanup %s: %v %s", unit, err, out) + } + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + journal, _ := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=short-monotonic").CombinedOutput() + cancel() + t.Logf("real unit %s journal:\n%s", unit, journal) + _ = command(15*time.Second, "stop", unit) + state, err := gap1ReadUnit(unit) + if err != nil || !gap1UnitGone(state) { + _ = command(5*time.Second, "kill", "--kill-who=all", "--signal=KILL", unit) + _ = command(5*time.Second, "stop", unit) + } + _ = command(5*time.Second, "reset-failed", unit) + state, err = gap1ReadUnit(unit) + if err != nil || !gap1UnitGone(state) { + t.Errorf("owned unit/PID cleanup not confirmed; retain run root: %s state%v err%v", unit, state, err) + return + } + t.Logf("confirmed owned unit stopped: %s state%v", unit, state) +} +func gap1UnitGone(s map[string]string) bool { + job, hasJob := s["Job"] + return hasJob && job == "" && s["MainPID"] == "0" && s["ControlPID"] == "0" && + (s["LoadState"] == "not-found" || s["LoadState"] == "loaded") && s["ActiveState"] == "inactive" && s["SubState"] == "dead" +} + +// The absent-unit shape is captured from real systemd249. Refuse incomplete, +// contradictory, queued-job and live-process observations before removing WAL. +func TestGAP1AbsenceRequiresNoJobAndBothPIDsZero(t *testing.T) { + for _, tc := range []struct { + name, key, value string + want bool + }{ + {"collected", "LoadState", "not-found", true}, + {"loaded stopped", "LoadState", "loaded", true}, + {"main lives", "MainPID", "123", false}, + {"control lives", "ControlPID", "123", false}, + {"job queued", "Job", "123", false}, + {"restart pending", "SubState", "auto-restart", false}, + {"contradictory active", "ActiveState", "active", false}, + {"unknown load", "LoadState", "", false}, + } { + t.Run(tc.name, func(t *testing.T) { + s := map[string]string{"MainPID": "0", "ControlPID": "0", "LoadState": "not-found", "ActiveState": "inactive", "SubState": "dead", "Job": ""} + s[tc.key] = tc.value + if gap1UnitGone(s) != tc.want { + t.Fatalf("absence classification %+v want%v", s, tc.want) + } + delete(s, "Job") + if gap1UnitGone(s) { + t.Fatal("missing observation treated as absence") + } + }) + } +} +func gap1ReadHead(t *testing.T, remote storage.ChunkRemote) (storage.ChunkHead, error) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + return remote.GetHead(ctx) +} +func gap1Systemctl(t *testing.T, args ...string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput(); err != nil { + t.Fatalf("systemctl: %v %s", err, out) + } +} +func gap1Unit(t *testing.T, unit string) map[string]string { + t.Helper() + m, err := gap1ReadUnit(unit) + if err != nil { + t.Fatal(err) + } + t.Logf("captured unit %s: %+v", unit, m) + return m +} +func gap1ReadUnit(unit string) (map[string]string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + b, err := exec.CommandContext(ctx, "systemctl", "show", unit, "--property=Job,MainPID,ControlPID,NRestarts,ExecMainStatus,Result,ExecMainStartTimestampMonotonic,RestartUSec,RestartPreventExitStatus,StartLimitBurst,StartLimitIntervalUSec,ActiveState,SubState,LoadState,InvocationID").CombinedOutput() + if err != nil { + return nil, fmt.Errorf("unit show %s: %w %s", unit, err, b) + } + m := map[string]string{} + for _, l := range strings.Split(strings.TrimSpace(string(b)), "\n") { + k, v, ok := strings.Cut(l, "=") + if ok { + m[k] = v + } + } + for _, key := range []string{"Job", "MainPID", "ControlPID", "NRestarts", "ExecMainStatus", "Result", "ExecMainStartTimestampMonotonic", "LoadState", "ActiveState", "SubState"} { + if _, ok := m[key]; !ok { + return nil, fmt.Errorf("captured systemd response lacks %s: %s", key, b) + } + } + return m, nil +} +func gap1Status(addr, volume string) (int, []byte, error) { + return gap1StatusAt(addr, volume, "/status/durable") +} +func gap1StatusAt(addr, volume, route string) (int, []byte, error) { + r, e := (&http.Client{Timeout: time.Second}).Get("http://" + addr + route + "?volume=" + volume) + if e != nil { + return 0, nil, e + } + defer r.Body.Close() + body, e := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + return r.StatusCode, body, e +} + +// /status is a different schema from /status/durable. Presence checks make +// a wrong route or a missing field a failed oracle, not false readiness. +func gap1Readiness(status int, payload []byte, volume string) (bool, error) { + if status != http.StatusOK { + return false, fmt.Errorf("readiness HTTP status%d", status) + } + var body struct { + VolumeID string + Healthy, FrontendPrimaryReady *bool + } + if err := json.Unmarshal(payload, &body); err != nil { + return false, err + } + if body.VolumeID != volume || body.Healthy == nil || body.FrontendPrimaryReady == nil { + return false, fmt.Errorf("readiness response lacks exact volume and readiness fields: %s", payload) + } + return *body.Healthy || *body.FrontendPrimaryReady, nil +} + +func TestGAP1ReadinessRejectsWrongSchema(t *testing.T) { + projection := hostvolume.StatusProjection{} + projection.VolumeID = "v" + projectionPayload := func(healthy, ready bool) []byte { + t.Helper() + projection.Healthy, projection.FrontendPrimaryReady = healthy, ready + b, err := json.Marshal(projection) + if err != nil { + t.Fatal(err) + } + return b + } + for _, tc := range []struct { + name string + status int + body []byte + serving, refused bool + }{ + {"not-ready", 200, projectionPayload(false, false), false, false}, + {"healthy", 200, projectionPayload(true, false), true, false}, + {"frontend-ready", 200, projectionPayload(false, true), true, false}, + {"durable-route", 200, []byte(`{"VolumeID":"v","Volumes":[{"VolumeID":"v","Operational":false}]}`), false, true}, + {"missing-readiness", 200, []byte(`{"VolumeID":"v","Healthy":false}`), false, true}, + {"wrong-volume", 200, []byte(`{"VolumeID":"other","Healthy":false,"FrontendPrimaryReady":false}`), false, true}, + {"http-refusal", 404, projectionPayload(false, false), false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + got, err := gap1Readiness(tc.status, tc.body, "v") + if got != tc.serving || (err != nil) != tc.refused { + t.Fatalf("serving=%v err=%v want=%v refused=%v", got, err, tc.serving, tc.refused) + } + }) + } +} + +func gap1StatusOperational(status int, payload []byte, volume string) bool { + if status != http.StatusOK { + return false + } + var body struct{ Volumes []durable.VolumeStatus } + if json.Unmarshal(payload, &body) != nil { + return false + } + for _, v := range body.Volumes { + if v.VolumeID == volume { + return v.Operational && v.Chunk != nil && v.Chunk.Attached && !v.Chunk.Fenced + } + } + return false +} +func gap1Operational(t *testing.T, addr, volume string) bool { + t.Helper() + status, payload, e := gap1Status(addr, volume) + return e == nil && gap1StatusOperational(status, payload, volume) +} +func waitGAP1(t *testing.T, what string, bound time.Duration, ready func() bool) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), bound) + defer cancel() + tick := time.NewTicker(200 * time.Millisecond) + defer tick.Stop() + for { + if ready() { + return + } + select { + case <-ctx.Done(): + t.Fatal(what) + case <-tick.C: + } + } +} + +// The transient unit exercises the shipped restart policy, not an independently +// tuned retry loop. Both deployed frontend variants must carry the same policy. +func gap1ShippedPolicy(t *testing.T) map[string]string { + t.Helper() + var first map[string]string + for _, name := range []string{"sw-blockvolume.service", "sw-blockvolume@.service", "sw-blockvolume-ublk.service"} { + raw, err := os.ReadFile(filepath.Join("..", "..", "deploy", "systemd", name)) + if err != nil { + t.Fatal(err) + } + fields := map[string]string{} + for _, line := range strings.Split(string(raw), "\n") { + key, value, ok := strings.Cut(strings.TrimSpace(line), "=") + if ok { + fields[key] = value + } + } + if fields["Restart"] != "on-failure" || fields["RestartPreventExitStatus"] != "78 79" || fields["RestartSec"] != "5s" { + t.Fatalf("shipped policy changed: %s %+v", name, fields) + } + if first != nil { + for _, key := range []string{"Restart", "RestartSec", "RestartPreventExitStatus", "TimeoutStopSec"} { + if fields[key] != first[key] { + t.Fatalf("unit policies differ at %s", key) + } + } + } + first = fields + } + return first +} + +// A successful planned revoke is not a retry outcome. The master's ACK and +// systemd's terminal inactive/dead state prove no automatic restart is queued. +func gap1PlannedStopDoesNotRestart(t *testing.T, ws control.WorkspaceServiceClient, unit, addr, volume string, epoch uint64, holder, restarts, invocation string) { + t.Helper() + req, err := http.NewRequest(http.MethodPost, "http://"+addr+"/chunk/detach", bytes.NewBufferString(fmt.Sprintf(`{"volumeID":%q,"plain":true,"timeoutMs":5000}`, volume))) + if err != nil { + t.Fatal(err) + } + resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req) + if err != nil { + t.Fatal(err) + } + body, readErr := io.ReadAll(resp.Body) + _ = resp.Body.Close() + t.Logf("captured plain seal response: status%d body%s", resp.StatusCode, body) + if readErr != nil || resp.StatusCode != http.StatusOK { + t.Fatalf("plain seal: %v status%d", readErr, resp.StatusCode) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + _, err = ws.RevokeWorkspace(ctx, &control.WorkspaceIdentity{VolumeId: volume, ReplicaId: holder, Epoch: epoch}) + cancel() + if err != nil { + t.Fatal(err) + } + waitGAP1(t, "planned revoke never recorded ACK and exited normally", 20*time.Second, func() bool { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + status, err := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: volume}) + if err != nil || status.GetRevocationAck() == nil { + return false + } + ack := status.GetRevocationAck() + t.Logf("captured planned-stop ACK: %s", ack.String()) + if ack.GetIdentity().GetVolumeId() != volume || ack.GetIdentity().GetReplicaId() != holder || ack.GetIdentity().GetEpoch() != epoch || ack.GetHeadGen() == 0 { + t.Fatalf("wrong planned ACK: %s", ack.String()) + } + state := gap1Unit(t, unit) + // systemd may unload a successful transient unit, resetting its + // counters. In that case use the exact invocation's journal proof. + if state["LoadState"] != "not-found" && state["NRestarts"] != restarts { + t.Fatalf("planned stop restarted: %+v", state) + } + if state["MainPID"] != "0" { + return false + } + if state["ExecMainStatus"] != "0" || state["ActiveState"] != "inactive" || state["SubState"] != "dead" { + t.Fatalf("planned stop is not terminal success: %+v", state) + } + starts, parseErr := strconv.Atoi(restarts) + if parseErr != nil || invocation == "" { + t.Fatalf("missing pre-stop systemd identity: starts=%q invocation=%q", restarts, invocation) + } + return gap1JournalTerminalSuccess(t, unit, invocation, starts+1) + }) +} + +// The host-consistency check uses the actual gRPC peer address. Model two +// registered hosts with loopback and a real non-loopback local IPv4 address; +// the target dials the master over that second address. Both processes and +// every restart still run under the same real WSL systemd (not two machines). +type gap1Target struct { + masterAddr, dataAddr, ctrlAddr string +} + +// gap1WriteTLS writes a CA, the master's certificate (valid for loopback and +// the target's address), node certificates for s1 and s2, an admin +// certificate and the role file to root/tls. +func gap1WriteTLS(t *testing.T, root string, target gap1Target) string { + t.Helper() + dir := filepath.Join(root, "tls") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + host, _, err := net.SplitHostPort(target.masterAddr) + if err != nil { + t.Fatal(err) + } + ca := authtest.NewCA(t, "gap1 CA") + ca.WriteCA(t, dir) + until := time.Now().Add(24 * time.Hour) + ca.Issue(t, "blockmaster", until, net.ParseIP(host)).WriteFiles(t, dir, "master") + var roles strings.Builder + for _, p := range []struct{ name, role, id string }{{"s1", "node", "s1"}, {"s2", "node", "s2"}, {"admin", "admin", "gap1-test"}} { + leaf := ca.Issue(t, p.id, until) + leaf.WriteFiles(t, dir, p.name) + fmt.Fprintln(&roles, leaf.Fingerprint, p.role, p.id) + } + if err := os.WriteFile(filepath.Join(dir, "roles"), []byte(roles.String()), 0o600); err != nil { + t.Fatal(err) + } + return dir +} + +func gap1TargetAddresses(t *testing.T, masterAddr string) (gap1Target, string) { + t.Helper() + _, port, err := net.SplitHostPort(masterAddr) + if err != nil { + t.Fatal(err) + } + interfaces, err := net.Interfaces() + if err != nil { + t.Fatal(err) + } + for _, iface := range interfaces { + if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 { + continue + } + addresses, err := iface.Addrs() + if err != nil { + t.Fatal(err) + } + for _, address := range addresses { + ip, _, err := net.ParseCIDR(address.String()) + if err != nil || ip.To4() == nil || ip.IsLoopback() || ip.IsLinkLocalUnicast() { + continue + } + allocate := func() string { + ln, err := net.Listen("tcp", net.JoinHostPort(ip.String(), "0")) + if err != nil { + t.Fatal(err) + } + addr := ln.Addr().String() + if err := ln.Close(); err != nil { + t.Fatal(err) + } + return addr + } + return gap1Target{net.JoinHostPort(ip.String(), port), allocate(), allocate()}, net.JoinHostPort("0.0.0.0", port) + } + } + t.Fatal("qualification requires a real non-loopback IPv4 address; no skip is proof") + return gap1Target{}, "" +} + +// Start the future target before a clean move is issued. It has the same +// logical r1 identity but a different server id, and no own lineage: the source +// line cannot mean it lost anything. Prove75 and automatic restart, then issue +// a real MoveWorkspace and prove lease/HEAD/data admission without touching +// the target unit again. This is not a positive78/no-restart witness. +func gap1PrestartedTargetServesAfterMove(t *testing.T, fixture *gap1Fixture, ws control.WorkspaceServiceClient, remote storage.ChunkRemote, target gap1Target, stem, exe string, args []string, root, volume string, want []byte) { + t.Helper() + changed := append([]string(nil), args...) + addr, nvmeAddr := leaseBinaryAddress(t), leaseBinaryAddress(t) + nqn := "nqn.2026-11.test:" + stem + "-prestarted-target" + replacements := map[string]string{"--master": target.masterAddr, "--server-id": "s2", "--data-addr": target.dataAddr, "--ctrl-addr": target.ctrlAddr, "--status-addr": addr, "--durable-root": filepath.Join(root, "target-store"), "--nvme-listen": nvmeAddr, "--nvme-subsysnqn": nqn, + "--master-tls-cert": filepath.Join(root, "tls", "s2.crt"), "--master-tls-key": filepath.Join(root, "tls", "s2.key")} + for i := 0; i+1 < len(changed); i++ { + if value, ok := replacements[changed[i]]; ok { + changed[i+1] = value + } + } + unit := stem + "-prestarted-target" + fixture.start(t, unit, true, exe, changed...) + waitGAP1(t, "target never observed the source holder before the move", 15*time.Second, func() bool { + status, body, err := gap1StatusAt(addr, volume, "/status") + if err != nil || status != http.StatusOK { + return false + } + serving, err := gap1Readiness(status, body, volume) + if err != nil { + t.Fatal(err) + } + if serving { + t.Fatalf("future target served before the move: %s", body) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=cat") + cmd.WaitDelay = time.Second + journal, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("target journal: %v %s", err, journal) + } + observed := fmt.Sprintf("assignment identity refusal volume=%q replica=%q server=%q", volume, "r1", "s1") + return strings.Contains(string(journal), observed) + }) + waitGAP1(t, "prestarted target did not exit75 before the move", 45*time.Second, func() bool { + s := gap1Unit(t, unit) + if s["ExecMainStatus"] == "78" { + t.Fatalf("zero-lineage target chose no-retry before its move: %+v", s) + } + return s["ExecMainStatus"] == "75" + }) + waitGAP1(t, "prestarted target retry75 did not restart", 15*time.Second, func() bool { + s := gap1Unit(t, unit) + n, err := strconv.Atoi(s["NRestarts"]) + if err != nil || n > 2 { + t.Fatalf("invalid or unbounded target restart count: %+v", s) + } + return n >= 1 && s["MainPID"] != "0" + }) + sealed, err := gap1ReadHead(t, remote) + if err != nil || sealed.State != storage.ChunkHeadDetached || sealed.Holder != "s1/r1" || sealed.Gen == 0 { + t.Fatalf("move source not sealed by its exact holder: %+v %v", sealed, err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + grant, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: stem + "-target-move", VolumeId: volume, ExpectedReplicaId: "r1", ExpectedEpoch: sealed.Epoch, TargetReplicaId: "r1", TargetServerId: "s2", TargetDataAddr: target.dataAddr, TargetCtrlAddr: target.ctrlAddr, Kind: "clean"}) + cancel() + if err != nil || !grant.GetIssued() || grant.GetNewEpoch() <= sealed.Epoch || grant.GetOldHost() != "s1" || grant.GetNewHost() != "s2" || grant.GetHeadGen() != sealed.Gen { + t.Fatalf("real clean move failed: grant=%v err=%v", grant, err) + } + t.Logf("prestarted target move issued after its automatic restart: %s", grant) + waitGAP1(t, "automatically restarted target did not serve after the move", 60*time.Second, func() bool { + s := gap1Unit(t, unit) + n, err := strconv.Atoi(s["NRestarts"]) + if err != nil || n < 1 || n > 2 || s["Result"] == "start-limit-hit" { + t.Fatalf("target restart bound violated after move: %+v", s) + } + return gap1Operational(t, addr, volume) + }) + head, err := gap1ReadHead(t, remote) + if err != nil || head.Gen <= sealed.Gen || head.Epoch != grant.NewEpoch || head.Holder != "s2/r1" || head.State != storage.ChunkHeadActive { + t.Fatalf("target did not claim its issued HEAD: %+v %v", head, err) + } + client := gap1ConnectNVMe(t, nvmeAddr, nqn) + client.readExact(t, 8, want) + client.readExact(t, 9, want) + client.writeFlush(t, 10, want) + client.readExact(t, 10, want) + client.close() + t.Logf("prestarted target served after a real clean move without operator restart: unit=%s HEAD=%+v", unit, head) +} + +// Register before the units: their exact-unit cleanup runs first, then this +// retains failed-run local state before testing.TempDir removes it. Nothing is +// deleted from the evidence directory, including a partial copy on failure. +func gap1PreserveFailure(t *testing.T, roots ...string) { + t.Helper() + destination := os.Getenv("GAP1_EVIDENCE_DIR") + if destination == "" { + return + } + t.Cleanup(func() { + if !t.Failed() { + return + } + if err := os.MkdirAll(destination, 0700); err != nil { + t.Logf("evidence mkdir: %v", err) + return + } + for i, root := range roots { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + out, err := exec.CommandContext(ctx, "cp", "-a", "--sparse=always", root, filepath.Join(destination, fmt.Sprintf("runtime-%d", i))).CombinedOutput() + cancel() + t.Logf("failed-run state retained: source=%s destination=%s err=%v output=%s", root, destination, err, out) + } + }) +} + +// Captured systemd249 journal records supply stable manager message IDs. The +// raw journal is logged when this witness succeeds; no fabricated PID status +// can turn an unknown unit into an ACKed successful invocation. +func gap1JournalTerminalSuccess(t *testing.T, unit, invocation string, expectedStarts int) bool { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + raw, err := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager", "--output=json").CombinedOutput() + if err != nil { + t.Fatalf("unit journal: %v %s", err, raw) + } + starts := 0 + started := map[string]bool{} + succeeded := map[string]bool{} + for _, line := range bytes.Split(raw, []byte{'\n'}) { + if len(line) == 0 { + continue + } + var entry struct { + Unit string `json:"UNIT"` + Invocation string `json:"INVOCATION_ID"` + Message string `json:"MESSAGE_ID"` + PID string `json:"_PID"` + JobResult string `json:"JOB_RESULT"` + } + if err := json.Unmarshal(line, &entry); err != nil { + t.Fatalf("captured journal JSON: %v", err) + } + if entry.Unit != unit+".service" || entry.PID != "1" { + continue + } + switch entry.Message { + case "39f53479d3a045ac8e11786248231fbf": + if entry.JobResult == "done" { + starts++ + started[entry.Invocation] = true + } + case "7ad2d189f7e94e70a38c781354912448": + succeeded[entry.Invocation] = true + } + } + if starts > expectedStarts { + t.Fatalf("unexpected restart in captured unit journal: starts%d want%d", starts, expectedStarts) + } + if invocation == "" && expectedStarts == 1 { + for id := range started { + invocation = id + } + } + complete := invocation != "" && starts == expectedStarts && started[invocation] && succeeded[invocation] + if complete { + t.Logf("captured terminal-success journal for %s invocation%s: %s", unit, invocation, raw) + } + return complete +} + +// Calibrate the terminal parser against the real supervisor before any holder +// is killed. Successful transient units can be collected; their journal is the +// proof, never the default zeros returned for an unknown unit. +func gap1ProbeTerminalSuccess(t *testing.T, fixture *gap1Fixture, unit string) { + t.Helper() + fixture.start(t, unit, true, "/bin/true") + waitGAP1(t, "systemd terminal-success parser preflight failed", 5*time.Second, func() bool { + return gap1JournalTerminalSuccess(t, unit, "", 1) + }) +} diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_master_outage_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_master_outage_integration_test.go new file mode 100644 index 0000000000..de71812de2 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/startup_systemd_master_outage_integration_test.go @@ -0,0 +1,183 @@ +//go:build linux && subprocess && chunkstore_integration && systemd_integration + +package main_test + +import ( + "bufio" + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +// A 10-minute blockmaster outage under real systemd (root), with the shipped +// unit's restart policy and start limit: the serving process fences once and +// exits 75; the unit starts it again and that process waits inside itself +// (no restart loop): the unit never reaches its start limit (NRestarts 1, 2 +// starts), /status shows MasterWait unreachable with its age, and when the +// master returns the volume serves by itself within 2 s of the master's +// barrier time. +// +// A runtime unit file (/run/systemd/system) stands for the installed unit. +func TestUnitSurvivesTenMinuteMasterOutage(t *testing.T) { + if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" { + t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof") + } + if os.Geteuid() != 0 { + t.Fatal("systemd qualification needs root") + } + shipped := gap1ShippedPolicy(t) + interval, burst := shippedStartLimit(t) + + env := startHandoffEnv(t, 1) + b := env.hosts["s1"] + unit := fmt.Sprintf("swb-c04-master-outage-%d.service", os.Getpid()) + writeRuntimeUnit(t, unit, env.h.volume, env.volArgsFor(b), []string{ + "StartLimitIntervalSec=" + interval, + "StartLimitBurst=" + burst, + }, []string{ + "Restart=on-failure", + "RestartSec=" + shipped["RestartSec"], + "RestartPreventExitStatus=" + shipped["RestartPreventExitStatus"], + "TimeoutStopSec=" + shipped["TimeoutStopSec"], + }) + if out, err := runSystemctl("start", unit); err != nil { + t.Fatalf("start %s: %v %s", unit, err, out) + } + poll(t, 2*time.Minute, "v1 never served under the unit", func() bool { return volumeFrontendReady(b.status, "v1") }) + + killAt := time.Now() + env.masterProcess.kill(t) + var state map[string]string + for deadline := killAt.Add(10 * time.Minute); time.Now().Before(deadline); time.Sleep(2 * time.Second) { + s, err := gap1ReadUnit(unit) + if err != nil { + continue + } + state = s + if s["ActiveState"] == "failed" { + t.Fatalf("the unit gave up %v into the outage (NRestarts %s, Result %s)", time.Since(killAt).Round(time.Second), s["NRestarts"], s["Result"]) + } + } + mw, ok := masterWaitOf(b.status) + t.Logf("PHASE0-SYSTEMD master down %v: ActiveState %s NRestarts %s; MasterWait %+v", + time.Since(killAt).Round(time.Second), state["ActiveState"], state["NRestarts"], mw) + if state["ActiveState"] != "active" || state["NRestarts"] != "1" { + t.Fatalf("after 10 min: ActiveState %s NRestarts %s; want active after exactly one restart (the fence)", state["ActiveState"], state["NRestarts"]) + } + if !ok || mw.Reason != "unreachable" || time.Since(mw.Since) < 9*time.Minute { + t.Fatalf("/status MasterWait %+v (present %v); want unreachable for most of the outage", mw, ok) + } + + env.masterProcess = env.h.start(t, "blockmaster-back", env.h.master, env.masterArgs...) + env.masterProcess.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") + var until time.Time + poll(t, 30*time.Second, "/status never showed the master's barrier", func() bool { + mw, ok := masterWaitOf(b.status) + if ok && mw.Reason == "barrier" && !mw.Until.IsZero() { + until = mw.Until + return true + } + return false + }) + for !volumeFrontendReady(b.status, "v1") { + if time.Now().After(until.Add(60 * time.Second)) { + t.Fatal("v1 never served by itself after the master returned") + } + time.Sleep(100 * time.Millisecond) + } + late := time.Since(until) + s, _ := gap1ReadUnit(unit) + t.Logf("PHASE0-SYSTEMD master back: served %v after the barrier time; NRestarts %s", late.Round(time.Millisecond), s["NRestarts"]) + if late > 2*time.Second || s["NRestarts"] != "1" { + t.Fatalf("served %v after the barrier (want <= 2 s), NRestarts %s (want 1)", late.Round(time.Millisecond), s["NRestarts"]) + } +} + +// shippedStartLimit reads StartLimitIntervalSec and StartLimitBurst from the +// shipped sw-blockvolume.service. +func shippedStartLimit(t *testing.T) (interval, burst string) { + t.Helper() + f, err := os.Open(filepath.Join("..", "..", "deploy", "systemd", "sw-blockvolume.service")) + if err != nil { + t.Fatal(err) + } + defer f.Close() + sc := bufio.NewScanner(f) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if v, ok := strings.CutPrefix(line, "StartLimitIntervalSec="); ok { + interval = v + } + if v, ok := strings.CutPrefix(line, "StartLimitBurst="); ok { + burst = v + } + } + if _, err := strconv.Atoi(burst); err != nil || interval == "" { + t.Fatalf("shipped unit start limit unreadable: interval %q burst %q", interval, burst) + } + return interval, burst +} + +// writeRuntimeUnit installs a runtime unit (removed, with daemon-reload, +// when the test ends) that runs exe with args, minus the test-only lock +// directory: under systemd blockvolume uses the real one, which is created +// for the test when missing and removed only if this test created it. +func writeRuntimeUnit(t *testing.T, unit, exe string, args, unitSection, serviceSection []string) { + t.Helper() + quoted := []string{fmt.Sprintf("%q", exe)} + for i := 0; i < len(args); i++ { + if args[i] == "--volume-lock-dir-test-only" { + i++ + continue + } + quoted = append(quoted, fmt.Sprintf("%q", args[i])) + } + const lockDir = "/run/sw-block/locks" + var created []string + for _, dir := range []string{filepath.Dir(lockDir), lockDir} { + if _, err := os.Stat(dir); os.IsNotExist(err) { + if err := os.Mkdir(dir, 0o755); err != nil { + t.Fatal(err) + } + created = append(created, dir) + } + } + path := filepath.Join("/run/systemd/system", unit) + t.Cleanup(func() { + gap1CleanupUnit(t, unit) + _ = os.Remove(path) + _, _ = runSystemctl("daemon-reload") + for i := len(created) - 1; i >= 0; i-- { + _ = os.Remove(created[i]) + } + }) + lines := append([]string{"[Unit]", "Description=sw-block test unit"}, unitSection...) + lines = append(lines, "[Service]", "Type=exec", "ExecStart="+strings.Join(quoted, " ")) + lines = append(lines, serviceSection...) + if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil { + t.Fatal(err) + } + if out, err := runSystemctl("daemon-reload"); err != nil { + t.Fatalf("daemon-reload: %v %s", err, out) + } +} + +func runSystemctl(args ...string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() + return string(out), err +} + +func unitJournal(unit string) string { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + out, _ := exec.CommandContext(ctx, "journalctl", "--unit="+unit, "--no-pager").CombinedOutput() + return string(out) +} diff --git a/seaweed-block/cmd/blockvolume/storage_identity_test.go b/seaweed-block/cmd/blockvolume/storage_identity_test.go new file mode 100644 index 0000000000..82f62da490 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/storage_identity_test.go @@ -0,0 +1,19 @@ +package main + +import ( + "testing" + + "github.com/seaweedfs/seaweed-block/core/storeident" +) + +// The host config carries the durable root's file-system identity (what the +// heartbeat reports); a memback run (no durable root) reports unknown. +func TestHostConfigStorageIdentityFromDurableRoot(t *testing.T) { + root := t.TempDir() + if got, want := hostConfig(flags{durableRoot: root}, nil).StorageIdentity, storeident.Of(root); got != want { + t.Fatalf("durable root identity = %+v, want %+v", got, want) + } + if got := hostConfig(flags{}, nil).StorageIdentity; got != (storeident.Identity{}) { + t.Fatalf("memback identity = %+v, want unknown", got) + } +} diff --git a/seaweed-block/cmd/blockvolume/test_port_claim_other_test.go b/seaweed-block/cmd/blockvolume/test_port_claim_other_test.go new file mode 100644 index 0000000000..dbc6922137 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/test_port_claim_other_test.go @@ -0,0 +1,7 @@ +//go:build !unix + +package main_test + +// claimHostPort: the process-level tests run on Linux only; elsewhere every +// port is this process's to probe. +func claimHostPort(p int) bool { return true } diff --git a/seaweed-block/cmd/blockvolume/test_port_claim_test.go b/seaweed-block/cmd/blockvolume/test_port_claim_test.go new file mode 100644 index 0000000000..8d2e1c93e1 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/test_port_claim_test.go @@ -0,0 +1,144 @@ +//go:build unix + +package main_test + +import ( + "bufio" + "context" + "os" + "os/exec" + "path/filepath" + "strconv" + "testing" + "time" +) + +// claimChild runs this test binary again as a claim helper: mode "hold" +// claims the port, prints "held" (or "refused"), and keeps the claim until +// its stdin closes; mode "try" claims and exits 0 (taken) or 3 (refused). +// The parent never claims, so its own claim map stays empty across -count. +const claimChildEnv = "SWBLOCK_TEST_PORT_CLAIM_CHILD" + +func TestMain(m *testing.M) { + if mode := os.Getenv(claimChildEnv); mode != "" { + p, _ := strconv.Atoi(os.Getenv("SWBLOCK_TEST_PORT_CLAIM_PORT")) + switch mode { + case "hold": + if !claimHostPort(p) { + os.Stdout.WriteString("refused\n") + os.Exit(3) + } + os.Stdout.WriteString("held\n") + _, _ = bufio.NewReader(os.Stdin).ReadString('\n') // until the parent closes stdin + os.Exit(0) + case "try": + if claimHostPort(p) { + os.Exit(0) + } + os.Exit(3) + } + os.Exit(2) + } + os.Exit(m.Run()) +} + +// claimEnv is the environment of a claim helper for port p in dir. +func claimEnv(mode, dir string, p int) []string { + return append(os.Environ(), claimChildEnv+"="+mode, "SWBLOCK_TEST_PORT_CLAIM_PORT="+strconv.Itoa(p), "SWBLOCK_TEST_PORT_CLAIMS="+dir) +} + +// tryClaim runs a "try" helper with a local deadline and returns its exit +// code. +func tryClaim(t *testing.T, dir string, p int) int { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0]) + cmd.Env = claimEnv("try", dir, p) + err := cmd.Run() + if ctx.Err() != nil { + t.Fatalf("the claim helper did not finish: %v", ctx.Err()) + } + if ee, ok := err.(*exec.ExitError); ok { + return ee.ExitCode() + } + if err != nil { + t.Fatal(err) + } + return 0 +} + +// holdClaim starts a "hold" helper and waits until it holds the port; the +// returned release closes its stdin and reaps it, within a deadline. +func holdClaim(t *testing.T, dir string, p int) (release func()) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + cmd := exec.CommandContext(ctx, os.Args[0]) + cmd.Env = claimEnv("hold", dir, p) + in, err := cmd.StdinPipe() + if err != nil { + cancel() + t.Fatal(err) + } + out, err := cmd.StdoutPipe() + if err != nil { + cancel() + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + cancel() + t.Fatal(err) + } + released := false + release = func() { + if released { + return + } + released = true + in.Close() + _ = cmd.Wait() // bounded by ctx: a hung helper is killed at its deadline + cancel() + } + t.Cleanup(release) + line, err := bufio.NewReader(out).ReadString('\n') + if err != nil || line != "held\n" { + release() + t.Fatalf("the holder did not take the port: %q %v", line, err) + } + return release +} + +// A port held by one process is refused to another on the same host, and +// taken once the holder has exited. +func TestHostPortClaimKeepsTwoProcessesApart(t *testing.T) { + dir := t.TempDir() + const p = 15151 + release := holdClaim(t, dir, p) + if code := tryClaim(t, dir, p); code != 3 { + t.Fatalf("a second process took a held port (exit %d)", code) + } + release() + if code := tryClaim(t, dir, p); code != 0 { + t.Fatalf("the port was not free after its holder exited (exit %d)", code) + } +} + +// A lock file left by another runner user, readable but not writable (0444), +// is still claimable: flock needs no write access. Held, it still keeps a +// second process out. +func TestHostPortClaimOnAReadOnlyLockFile(t *testing.T) { + dir := t.TempDir() + const p = 15252 + name := filepath.Join(dir, strconv.Itoa(p)+".lock") + if err := os.WriteFile(name, nil, 0o444); err != nil { + t.Fatal(err) + } + if err := os.Chmod(name, 0o444); err != nil { + t.Fatal(err) + } + release := holdClaim(t, dir, p) + if code := tryClaim(t, dir, p); code != 3 { + t.Fatalf("a second process took a port held through a read-only lock file (exit %d)", code) + } + release() +} diff --git a/seaweed-block/cmd/blockvolume/test_port_claim_unix_test.go b/seaweed-block/cmd/blockvolume/test_port_claim_unix_test.go new file mode 100644 index 0000000000..e4aceaa903 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/test_port_claim_unix_test.go @@ -0,0 +1,83 @@ +//go:build unix + +package main_test + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "sync" + "syscall" +) + +// hostPortClaims holds, for this test process's life, an exclusive flock on +// one file per port it handed out. Two test processes on one host (two CI +// jobs on one machine, each with its own shards) then never hand out the +// same port: the per-shard slice keeps shards of one job apart, the claim +// keeps jobs apart. The kernel drops a claim when its process exits. +var hostPortClaims struct { + sync.Mutex + files map[int]*os.File + reported bool // a claim error other than "held" was reported once +} + +// testPortClaimDir is the host-wide directory of port claims: +// SWBLOCK_TEST_PORT_CLAIMS, else /tmp/swblock-test-port-claims (not TMPDIR, +// which differs per shard and per job). +func testPortClaimDir() string { + if d := os.Getenv("SWBLOCK_TEST_PORT_CLAIMS"); d != "" { + return d + } + return "/tmp/swblock-test-port-claims" +} + +// claimHostPort takes port p for this process, host-wide; false when another +// process holds it. Only "would block" means held: any other error (the +// directory or file cannot be opened) is reported once, with its path, and +// the port is left to the caller's listen probe, as without claims. +func claimHostPort(p int) bool { + hostPortClaims.Lock() + defer hostPortClaims.Unlock() + if hostPortClaims.files == nil { + hostPortClaims.files = map[int]*os.File{} + } + if _, ok := hostPortClaims.files[p]; ok { + return false // already handed out by this process + } + f, err := flockPortFile(testPortClaimDir(), p) + switch { + case err == nil: + hostPortClaims.files[p] = f + return true + case errors.Is(err, syscall.EWOULDBLOCK): + return false + default: + if !hostPortClaims.reported { + hostPortClaims.reported = true + fmt.Fprintf(os.Stderr, "test port claims off: %v\n", err) + } + return true + } +} + +// flockPortFile opens dir/

.lock read-only (creating it if needed) and +// takes an exclusive, non-blocking flock on it; the open file holds the +// claim. flock needs no write access, so a lock file another runner user +// created stays claimable. +func flockPortFile(dir string, p int) (*os.File, error) { + if err := os.MkdirAll(dir, 0o777); err != nil { + return nil, err + } + _ = os.Chmod(dir, 0o777) // shared by every runner user on the host + name := filepath.Join(dir, fmt.Sprintf("%d.lock", p)) + f, err := os.OpenFile(name, os.O_RDONLY|os.O_CREATE, 0o444) + if err != nil { + return nil, fmt.Errorf("%s: %w", name, err) + } + if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + f.Close() + return nil, err + } + return f, nil +} diff --git a/seaweed-block/cmd/blockvolume/test_port_handoff_test.go b/seaweed-block/cmd/blockvolume/test_port_handoff_test.go new file mode 100644 index 0000000000..28ee8a33ba --- /dev/null +++ b/seaweed-block/cmd/blockvolume/test_port_handoff_test.go @@ -0,0 +1,143 @@ +package main_test + +import ( + "errors" + "regexp" + "strings" + "testing" +) + +// handoffRange is the range [lo, hi) a harness-chosen daemon port is drawn +// from: [10000, 20000), cut at the host's ephemeral range when that starts +// lower, so an outgoing connection's source port cannot take a port between +// the free check and the daemon's bind. ok is false when nothing is left. +func handoffRange(ephemeralLo int) (lo, hi int, ok bool) { + lo, hi = 10000, 20000 + if ephemeralLo < hi { + hi = ephemeralLo + } + return lo, hi, hi > lo +} + +// errBindTaken is a start that failed because one of the addresses the +// harness drew for it was taken before the daemon bound it. +var errBindTaken = errors.New("a harness-chosen port was taken before the daemon bound it") + +// bindTakenRe is Go's net error for a listener whose bind found the address +// in use, ending its log line: "listen tcp : bind: address already in +// use". A dial, a quoted copy inside other text, or anything after it on the +// line does not match. +var bindTakenRe = regexp.MustCompile(`(?:^|[\s:])listen tcp (\S+): bind: address already in use$`) + +// bindTakenOn reports the drawn address whose listener bind failed with +// EADDRINUSE in log, if any: only an exact listener-bind error, and only on +// one of drawn (this attempt's own addresses). Anything else is not a taken +// port, so the caller fails as it would without a retry. +func bindTakenOn(log string, drawn []string) (string, bool) { + for _, l := range strings.Split(log, "\n") { + m := bindTakenRe.FindStringSubmatch(strings.TrimRight(l, "\r")) + if m == nil { + continue + } + for _, a := range drawn { + if m[1] == a { + return a, true + } + } + } + return "", false +} + +// startWithBindRetry starts a daemon and waits for it; when the start +// reports errBindTaken, it asks for fresh ports and starts once more. first +// is the first attempt's error when it was retried (kept for the report); +// err is the answer that stands. Any other answer, and a second +// errBindTaken, is returned as it is. +func startWithBindRetry(start func(attempt int) error, freshPorts func()) (first, err error) { + err = start(1) + if !errors.Is(err, errBindTaken) { + return nil, err + } + first = err + freshPorts() + return first, start(2) +} + +func TestHandoffRangeStaysBelowTheEphemeralRange(t *testing.T) { + for _, c := range []struct { + eph, lo, hi int + ok bool + }{ + {32768, 10000, 20000, true}, // the Linux default: the whole range + {20000, 10000, 20000, true}, + {15000, 10000, 15000, true}, // a host whose ephemeral range starts low: cut there + {10001, 10000, 10001, true}, + {10000, 10000, 10000, false}, // nothing left + {1024, 10000, 1024, false}, + } { + lo, hi, ok := handoffRange(c.eph) + if lo != c.lo || hi != c.hi || ok != c.ok { + t.Fatalf("ephemeral from %d: [%d, %d) ok=%v; want [%d, %d) ok=%v", c.eph, lo, hi, ok, c.lo, c.hi, c.ok) + } + } +} + +func TestBindTakenOnOnlyThisAttemptsListener(t *testing.T) { + drawn := []string{"127.0.0.1:11230", "127.0.0.1:11231", "127.0.0.1:11232", "127.0.0.1:11233"} + for _, c := range []struct { + name, log string + addr string + taken bool + }{ + {"a drawn listener's bind", "2026/12/02 05:01:02 blockvolume: status listener: listen tcp 127.0.0.1:11230: bind: address already in use", "127.0.0.1:11230", true}, + {"the bare net error", "listen tcp 127.0.0.1:11233: bind: address already in use", "127.0.0.1:11233", true}, + {"a CRLF line", "listen tcp 127.0.0.1:11231: bind: address already in use\r", "127.0.0.1:11231", true}, + {"another port", "listen tcp 127.0.0.1:11299: bind: address already in use", "", false}, + {"another host, same port", "listen tcp 0.0.0.0:11230: bind: address already in use", "", false}, + {"a dial", "dial tcp 127.0.0.1:11230: connect: address already in use", "", false}, + {"quoted inside other text", `retry: err="listen tcp 127.0.0.1:11230: bind: address already in use"`, "", false}, + {"more after it", "listen tcp 127.0.0.1:11230: bind: address already in use; retrying", "", false}, + {"the words alone", "address already in use", "", false}, + {"udp", "listen udp 127.0.0.1:11230: bind: address already in use", "", false}, + {"nothing", "blockvolume: volume v2 adopted as PRIMARY at r2@1", "", false}, + } { + addr, taken := bindTakenOn("first line\n"+c.log+"\nlast line", drawn) + if addr != c.addr || taken != c.taken { + t.Fatalf("%s: (%q, %v); want (%q, %v)", c.name, addr, taken, c.addr, c.taken) + } + } +} + +func TestStartWithBindRetry(t *testing.T) { + other := errors.New("exited before logging adoption") + taken := func(n int) error { return errors.Join(errBindTaken, errors.New("attempt "+string(rune('0'+n)))) } + for _, c := range []struct { + name string + answers []error + first bool + want error + attempts []int + freshCnt int + }{ + {"ok at once", []error{nil}, false, nil, []int{1}, 0}, + {"another failure is not retried", []error{other}, false, other, []int{1}, 0}, + {"a taken port, then ok", []error{taken(1), nil}, true, nil, []int{1, 2}, 1}, + {"a taken port twice: the second answer stands", []error{taken(1), taken(2)}, true, errBindTaken, []int{1, 2}, 1}, + {"a taken port, then another failure", []error{taken(1), other}, true, other, []int{1, 2}, 1}, + } { + var attempts []int + fresh := 0 + first, err := startWithBindRetry(func(a int) error { attempts = append(attempts, a); return c.answers[a-1] }, func() { fresh++ }) + if (first != nil) != c.first || (c.first && !errors.Is(first, errBindTaken)) { + t.Fatalf("%s: first=%v", c.name, first) + } + if !errors.Is(err, c.want) || (c.want == nil && err != nil) || fresh != c.freshCnt || len(attempts) != len(c.attempts) { + t.Fatalf("%s: err=%v attempts=%v fresh=%d", c.name, err, attempts, fresh) + } + for i, a := range c.attempts { + if attempts[i] != a { + t.Fatalf("%s: attempts %v, want %v", c.name, attempts, c.attempts) + } + } + } +} diff --git a/seaweed-block/cmd/blockvolume/test_port_shard_test.go b/seaweed-block/cmd/blockvolume/test_port_shard_test.go new file mode 100644 index 0000000000..9807e11b41 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/test_port_shard_test.go @@ -0,0 +1,78 @@ +package main_test + +import ( + "os" + "strconv" + "testing" +) + +// testPortSpan narrows a port range [lo, hi) to this test process's share +// when several process-level test binaries run in parallel on one host +// (CI shards): SWBLOCK_TEST_PORT_SHARD=k of SWBLOCK_TEST_PORT_SHARDS=n +// (1 <= k <= n) gets the k-th of n equal slices, so two shards never draw +// the same port. Unset or invalid, the whole range. +func testPortSpan(lo, hi int) (int, int) { + n, errN := strconv.Atoi(os.Getenv("SWBLOCK_TEST_PORT_SHARDS")) + k, errK := strconv.Atoi(os.Getenv("SWBLOCK_TEST_PORT_SHARD")) + if errN != nil || errK != nil || n < 2 || k < 1 || k > n || hi-lo < n { + return lo, hi + } + w := (hi - lo) / n + return lo + (k-1)*w, lo + k*w +} + +// weedPairRange is the range [20000, hi) of a weed server's HTTP port p, +// whose gRPC port is p+10000, given the host's ephemeral range starting at +// ephemeralLo: every gRPC port stays below the ephemeral range when that +// leaves room, and every HTTP port stays below every gRPC port (hi <= 30000), +// so slicing the HTTP range per shard keeps both kinds of port apart. +func weedPairRange(ephemeralLo int) (int, int) { + hi := 30000 + if ephemeralLo-10000 > 20000 && ephemeralLo-10000 < hi { + hi = ephemeralLo - 10000 + } + return 20000, hi +} + +func TestWeedPairSlicesNeverMeetAcrossShards(t *testing.T) { + t.Setenv("SWBLOCK_TEST_PORT_SHARDS", "4") + for _, eph := range []int{28000, 32768, 40000, 50000, 61000} { + type span struct{ k, lo, hi int } + var spans []span + for k := 1; k <= 4; k++ { + t.Setenv("SWBLOCK_TEST_PORT_SHARD", strconv.Itoa(k)) + lo, hi := testPortSpan(weedPairRange(eph)) + spans = append(spans, span{k, lo, hi}, span{k, lo + 10000, hi + 10000}) // HTTP, gRPC + } + for i, a := range spans { + for _, b := range spans[i+1:] { + if a.k != b.k && a.lo < b.hi && b.lo < a.hi { + t.Fatalf("ephemeral from %d: shard %d [%d, %d) meets shard %d [%d, %d)", eph, a.k, a.lo, a.hi, b.k, b.lo, b.hi) + } + } + } + } +} + +func TestTestPortSpanGivesEachShardItsOwnSlice(t *testing.T) { + t.Setenv("SWBLOCK_TEST_PORT_SHARDS", "") + if lo, hi := testPortSpan(10000, 20000); lo != 10000 || hi != 20000 { + t.Fatalf("unsharded: [%d, %d)", lo, hi) + } + t.Setenv("SWBLOCK_TEST_PORT_SHARDS", "4") + prev := 10000 + for k := 1; k <= 4; k++ { + t.Setenv("SWBLOCK_TEST_PORT_SHARD", strconv.Itoa(k)) + lo, hi := testPortSpan(10000, 20000) + if lo != prev || hi-lo != 2500 { + t.Fatalf("shard %d of 4: [%d, %d); want [%d, %d)", k, lo, hi, prev, prev+2500) + } + prev = hi + } + for _, bad := range []string{"0", "5", "x"} { + t.Setenv("SWBLOCK_TEST_PORT_SHARD", bad) + if lo, hi := testPortSpan(10000, 20000); lo != 10000 || hi != 20000 { + t.Fatalf("shard %q of 4: [%d, %d); want the whole range", bad, lo, hi) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/testdata/diskfull.sh b/seaweed-block/cmd/blockvolume/testdata/diskfull.sh new file mode 100755 index 0000000000..631627918a --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/diskfull.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Disk-full harness for TestProcedureLocalDiskFull. Root only; it formats only +# loop devices over private sparse files under WORKDIR and always tears them +# down, also when the test fails or is killed. +# +# diskfull.sh WORKDIR -- TEST_COMMAND... +# +# The test runs with SWBLOCK_DISKFULL_ROOT (512 MiB ext4, for durable roots), +# SWBLOCK_DISKFULL_LIMIT (8 MiB ext4, for --host-limit-dir) and +# SWBLOCK_REPLAY_LOGS. No reserved blocks (-m 0): the test runs as root. +set -euo pipefail +[ "$(id -u)" = 0 ] || { echo "root required" >&2; exit 2; } +work=$(realpath "${1:?existing empty work dir}") +[ "${2:-}" = -- ] || { echo "usage: $0 WORKDIR -- TEST_COMMAND..." >&2; exit 2; } +shift 2 +for c in losetup mkfs.ext4 mount umount mountpoint truncate; do command -v "$c" >/dev/null; done +mkdir "$work/root" "$work/limit" "$work/logs" +loops=() +cleanup() { + local rc=$? failed=0 + set +e + for m in "$work/root" "$work/limit"; do + mountpoint -q "$m" || continue + # A blockvolume that outlived a killed test would hold the mount busy. + command -v fuser >/dev/null && fuser -km "$m" >/dev/null 2>&1 + umount "$m" 2>/dev/null || { sleep 1; umount "$m"; } || { umount -l "$m"; failed=1; } + done + for l in "${loops[@]}"; do losetup -d "$l" || failed=1; done + # Only the sparse images this script created under WORKDIR. + rm -f -- "$work/root.img" "$work/limit.img" + if [ "$failed" = 1 ] || losetup -a | grep -qF "$work/"; then + echo "diskfull.sh: teardown incomplete (busy mount or loop device left)" >&2 + exit 3 + fi + exit $rc +} +trap cleanup EXIT +for fs in root:512M limit:8M; do + name=${fs%%:*} + truncate -s "${fs#*:}" "$work/$name.img" + dev=$(losetup --find --show "$work/$name.img"); loops+=("$dev") + mkfs.ext4 -q -F -m 0 "$dev" + mount "$dev" "$work/$name" +done +set +e +SWBLOCK_DISKFULL_ROOT=$work/root SWBLOCK_DISKFULL_LIMIT=$work/limit SWBLOCK_REPLAY_LOGS=$work/logs "$@" +rc=$? +set -e +exit $rc diff --git a/seaweed-block/cmd/blockvolume/testdata/headroom-small-fs.sh b/seaweed-block/cmd/blockvolume/testdata/headroom-small-fs.sh new file mode 100755 index 0000000000..75469bf5a9 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/headroom-small-fs.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Small-file-system harness for TestHeadroomRefusesRestoreTargetsThenServesThem. +# Root only, on a disposable host; it formats only a loop device over a private +# sparse file under WORKDIR. +# +# headroom-small-fs.sh WORKDIR -- TEST_COMMAND... +# +# It makes a 768 MiB ext4 (no reserved blocks) on a loop device, mounts it at +# WORKDIR/mnt and fills 600 MiB of it with WORKDIR/mnt/filler, so less than a +# volume's size + WAL (256 MiB + 64 MiB) is free; the test removes the filler +# when it needs room. The test runs with CHUNKSTORE_SMALL_ROOT (a directory on +# that file system) and CHUNKSTORE_SMALL_FILLER (the filler). Each run gets a +# fresh file system. Exit status is the test's. Everything this script created +# is removed. +# +# Example (from the repository root, as root): +# mkdir /tmp/headroom && cmd/blockvolume/testdata/headroom-small-fs.sh /tmp/headroom -- \ +# env CHUNKSTORE_WEED=/path/to/weed go test -count=1 -tags 'subprocess chunkstore_integration' \ +# -run '^TestHeadroomRefusesRestoreTargetsThenServesThem$' -timeout 15m ./cmd/blockvolume/ +set -euo pipefail +[ "$(id -u)" = 0 ] || { echo "root required" >&2; exit 2; } +work=$(realpath "${1:?existing empty work dir}") +[ "${2:-}" = -- ] || { echo "usage: $0 WORKDIR -- TEST_COMMAND..." >&2; exit 2; } +shift 2 +for c in losetup mkfs.ext4 mount umount mountpoint truncate dd; do command -v "$c" >/dev/null; done +loop= +cleanup() { + if mountpoint -q "$work/mnt"; then umount "$work/mnt"; fi + if [ -n "$loop" ]; then losetup -d "$loop" || true; fi + rm -rf "$work/mnt" "$work/small.img" +} +trap cleanup EXIT +mkdir "$work/mnt" +truncate -s 768M "$work/small.img" +loop=$(losetup --find --show "$work/small.img") +mkfs.ext4 -q -F -m 0 "$loop" +mount "$loop" "$work/mnt" +dd if=/dev/zero of="$work/mnt/filler" bs=1M count=600 status=none +sync +mkdir "$work/mnt/roots" +status=0 +CHUNKSTORE_SMALL_ROOT="$work/mnt/roots" CHUNKSTORE_SMALL_FILLER="$work/mnt/filler" "$@" || status=$? +exit "$status" diff --git a/seaweed-block/cmd/blockvolume/testdata/maintenance-retention-only.json b/seaweed-block/cmd/blockvolume/testdata/maintenance-retention-only.json new file mode 100644 index 0000000000..cd61734030 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/maintenance-retention-only.json @@ -0,0 +1,21 @@ +{ + "passesOk": 1, + "inProgress": false, + "currentStartNs": 0, + "lastPass": { + "atNs": 1, + "planned": 0, + "removed": 0, + "plannedChunks": 0, + "plannedRoots": 0, + "plannedSegments": 0, + "plannedLists": 0, + "removedChunks": 0, + "removedRoots": 0, + "removedSegments": 0, + "removedLists": 0, + "error": "", + "headGenError": "", + "headGen": 0 + } +} diff --git a/seaweed-block/cmd/blockvolume/testdata/maintenance-retention-only.md b/seaweed-block/cmd/blockvolume/testdata/maintenance-retention-only.md new file mode 100644 index 0000000000..6dd88020cb --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/maintenance-retention-only.md @@ -0,0 +1,18 @@ +# Retention-only maintenance integration control + +`maintenance-retention-only.json` is pinned by +`TestMaintenanceStatusRealPassAndTimeout/retention-only` in the sibling test. +It is the Maintenance portion of the real public-provider status after the +production `newChunkMaintenance(..., collect=false, ...)` callback completes. + +The guard seeds an orphan chunk, root and segment, kicks the holder loop, +requires no cleaner lookup, and proves the HEAD and all three objects remain. +The callback succeeds (`passesOk: 1`, empty error); `headGen: 0` and the zero +counts must NOT be classified as a completed cleaning or an orphan-free store. + +Only `lastPass.atNs` is normalized to 1 after asserting that the actual end time +is positive. A consumer control must use a matching injected evaluation time +(or replace the timestamp with its fresh clock) and require unknown specifically +for missing cleaning evidence. Otherwise a stale-time rejection could hide a +bad passesOk-only classifier. The consumer should read this fixture rather than +invent a second retention-only response. \ No newline at end of file diff --git a/seaweed-block/cmd/blockvolume/testdata/onezero-wrong-geometry-store.txt b/seaweed-block/cmd/blockvolume/testdata/onezero-wrong-geometry-store.txt new file mode 100644 index 0000000000..65fff9cac6 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/onezero-wrong-geometry-store.txt @@ -0,0 +1,73 @@ +# The wrong-size local store a 1.0 first start left (3402e0dd, the 1.0 RC): +# v2 restored with a 65536-block record, started with --durable-blocks 32768; +# captured from that run on tp04 (archive sha256 +# 0905c3af83b3a1dc226b417fa5acf7071907cc3e53478bc14a531481b717c5c1). +# "file ", then " " for each run of +# non-zero bytes; every other byte is zero. +file v2.bin 201334784 644 +0 5357424b030000000100000003000000d1d56a0491714e5ea87e7a1ff22252a3 +32 000000080000000000000100001000000020 +59 04000000007c6a6946b4d0ea1803 +128 9888ed4bd8dfd3b290cc22e299420293 +160 010000000000000001 +177 10 +192 29f7e5d0870411c13727a4bdcbba5f87500df26b1acd9540474cc3e82ed68b9b +224 8fb886e363d422e93964d61f856aed8c +4092 0ca0c6b05357424b030000000100000003000000d1d56a0491714e5ea87e7a1f +4124 f22252a3000000080000000000000100001000000020 +4155 04000000007c6a6946b4d0ea1802 +4224 9888ed4bd8dfd3b290cc22e299420293 +4256 010000000000000001 +4273 10 +4288 29f7e5d0870411c13727a4bdcbba5f87500df26b1acd9540474cc3e82ed68b9b +4320 8fb886e363d422e93964d61f856aed8c +8189 c521d7 +file v2.bin.chunkfresh 6 644 +0 66726573680a +file v2.bin.chunkmap 8192 600 +0 434c4d3301000000d1d56a0491714e5ea87e7a1ff22252a38fb886e363d422e9 +32 3964d61f856aed8c01 +56 20 +72 01 +88 01 +104 01 +120 01 +136 01 +152 01 +168 01 +184 01 +200 01 +216 01 +232 01 +248 01 +264 01 +280 01 +296 01 +312 01 +328 01 +344 01 +360 01 +376 01 +392 01 +408 01 +424 01 +440 01 +456 01 +472 01 +488 01 +504 01 +520 01 +536 01 +552 01 +568 01 +4064 34dec2669b9f5a0e9debd807e6541bb65c2cee5aa86640399e621ac1a8a20cb2 +4096 434c523301000000d1d56a0491714e5ea87e7a1ff22252a38fb886e363d422e9 +4128 3964d61f856aed8c010000000000000020 +4153 04 +4168 0100000000000000a0 +4192 34dec2669b9f5a0e9debd807e6541bb65c2cee5aa86640399e621ac1a8a20cb2 +4224 29f7e5d0870411c13727a4bdcbba5f87500df26b1acd9540474cc3e82ed68b9b +file v2.replica-floor 71 644 +0 7b22736368656d61223a22736561776565642d626c6f636b2e7265706c696361 +32 2d666c6f6f722f7631222c22766f6c756d655f6964223a227632222c2265706f +64 6368223a307d0a diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/detach-plain.stderr b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/detach-plain.stderr new file mode 100644 index 0000000000..cf507d69b7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/detach-plain.stderr @@ -0,0 +1 @@ +sealed HEAD generation: 3 diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/detach-plain.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/detach-plain.stdout new file mode 100644 index 0000000000..4bc78cc8be --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/detach-plain.stdout @@ -0,0 +1 @@ +{"volumeID":"v1","cutLSN":1,"headGen":3,"headEpoch":1,"lastWrittenLSN":1} diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move-dry-run-admitted.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move-dry-run-admitted.stdout new file mode 100644 index 0000000000..9442ec483d --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move-dry-run-admitted.stdout @@ -0,0 +1,4 @@ +preview (advisory): at master time 2026-11-22T15:36:16.705621624Z, may change; admission is re-checked at the move. Nothing was written; this is not a confirmation. +forced move admitted +HEAD now: gen 3, epoch 1, holder s1/r1, remote LSN 1, published at 2026-11-22T15:35:12Z (publishing host clock as recorded in the filer, 1 s resolution) +if moved now: writes with LSN <= 1 are kept; writes acknowledged after that and before 2026-11-22T15:36:16.617154582Z, master clock, may be lost diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move-dry-run-refused.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move-dry-run-refused.stdout new file mode 100644 index 0000000000..082cfcc755 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move-dry-run-refused.stdout @@ -0,0 +1,3 @@ +preview (advisory): at master time 2026-11-22T15:35:12.107989752Z, may change; admission is re-checked at the move. Nothing was written; this is not a confirmation. +forced move not admitted: workspace forced move lease expiry plus clock-skew margin has not elapsed +admissible at 2026-11-22T15:36:16.617154582Z, master clock diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move.stdout new file mode 100644 index 0000000000..0484f10cbc --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/force-move.stdout @@ -0,0 +1,3 @@ +forced move issued: volume v1 request force-v1-1: r1@1 on s1 -> r1@2 on s2 (kept HEAD gen 3, remote LSN 1) +volume v1 restored to the last published image at 2026-11-22T15:35:12Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 3, LSN 1): writes with LSN <= 1 are preserved; writes acknowledged by r1@1 after that and before 2026-11-22T15:36:16.617154582Z, master clock, may be lost; the upper bound is a time, not an LSN. +next: start volume v1 on s2 (this command moved authority only) diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-reopened-s2.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-reopened-s2.stdout new file mode 100644 index 0000000000..8bcafeb22b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-reopened-s2.stdout @@ -0,0 +1 @@ +{"volumeID":"v1","volume":{"origin":"create","numBlocks":65536,"blockSize":4096,"chunkBlocks":1024,"createdNs":1795361693554515613,"parent":null},"head":{"gen":4,"epoch":2,"holder":"s2/r1","remoteLSN":1,"state":"active","detachedBy":null,"chunkCount":1}} diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-reopened.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-reopened.stdout new file mode 100644 index 0000000000..747b6e56dc --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-reopened.stdout @@ -0,0 +1 @@ +{"volumeID":"v1","volume":{"origin":"create","numBlocks":65536,"blockSize":4096,"chunkBlocks":1024,"createdNs":1795337541307771858,"parent":null},"head":{"gen":4,"epoch":2,"holder":"s1/r1","remoteLSN":1,"state":"active","detachedBy":null,"chunkCount":1}} diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-sealed.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-sealed.stdout new file mode 100644 index 0000000000..af1de786d9 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/head-sealed.stdout @@ -0,0 +1 @@ +{"volumeID":"v1","volume":{"origin":"create","numBlocks":65536,"blockSize":4096,"chunkBlocks":1024,"createdNs":1795337541307771858,"parent":null},"head":{"gen":3,"epoch":1,"holder":"s1/r1","remoteLSN":1,"state":"detached","detachedBy":{"holder":"s1/r1","epoch":1,"gen":3},"chunkCount":1}} diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/logs.txt b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/logs.txt new file mode 100644 index 0000000000..3645c7a9f4 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/logs.txt @@ -0,0 +1,9 @@ +2026/11/22 00:52:20 blockmaster: lock acquired, reloaded=0, listen=127.0.0.1:44358 +2026/11/22 00:52:21 blockvolume: volume v1 adopted as PRIMARY at r1@1 (EV=1) +2026/11/22 00:52:21 durable: HEAD claim for volume=v1 starting: target epoch=1 holder="s1/r1" +2026/11/22 00:52:21 durable: HEAD claim for volume=v1 done in 2.250367ms: gen=2 epoch=1 holder="s1/r1" +2026/11/22 00:52:21 workspace lease: fenced volume=v1 replica=r1 epoch=1: revoked by the master +blockvolume: stopping: the workspace lease guard fenced and requested the drain +2026/11/22 00:52:22 blockvolume: volume v1 adopted as PRIMARY at r1@2 (EV=1) +2026/11/22 00:52:22 durable: HEAD claim for volume=v1 starting: target epoch=2 holder="s1/r1" +2026/11/22 00:52:22 durable: HEAD claim for volume=v1 done in 3.597902ms: gen=4 epoch=2 holder="s1/r1" diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/lost-range.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/lost-range.stdout new file mode 100644 index 0000000000..6da93bf717 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/lost-range.stdout @@ -0,0 +1,2 @@ +range 1 of 1: request force-v1-1, r1@1 -> epoch 2, lost after LSN 1, until 2026-11-22T15:36:16.617154582Z (master clock) + volume v1 restored to the last published image at 2026-11-22T15:35:12Z (publishing host clock as recorded in the filer, 1 s resolution) (gen 3, LSN 1): writes with LSN <= 1 are preserved; writes acknowledged by r1@1 after that and before 2026-11-22T15:36:16.617154582Z, master clock, may be lost; the upper bound is a time, not an LSN. diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-clean-s2.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-clean-s2.stdout new file mode 100644 index 0000000000..829f37454f --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-clean-s2.stdout @@ -0,0 +1,2 @@ +clean move issued: volume v1 request move-v1-1: r1@1 -> r1@2 on s2 (sealed HEAD gen 3, remote LSN 1) +next: start volume v1 on s2 (this command moved authority only) diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-clean.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-clean.stdout new file mode 100644 index 0000000000..94de184444 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-clean.stdout @@ -0,0 +1,2 @@ +clean move issued: volume v1 request move-v1-1: r1@1 -> r1@2 on s1 (sealed HEAD gen 3, remote LSN 1) +next: start volume v1 on s1 (this command moved authority only) diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-refused.stderr b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-refused.stderr new file mode 100644 index 0000000000..984df2b1ca --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/move-refused.stderr @@ -0,0 +1 @@ +workspace move: clean move: workspace clean move needs detached HEAD and matching revocation ACK diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/revoke.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/revoke.stdout new file mode 100644 index 0000000000..d8f6e00f41 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/revoke.stdout @@ -0,0 +1,2 @@ +revocation requested: volume v1 holder r1@1 expiry_ns 1795337571673280526 +operator-stated sealed HEAD generation: 3 (not verified); workspace show must report ACK at this generation before move --clean diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-acked.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-acked.stdout new file mode 100644 index 0000000000..8eae3b9488 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-acked.stdout @@ -0,0 +1,8 @@ +volume: v1 (query snapshot, not authority to serve) +replica: r1 +epoch: 1 +lease state: revoking +holder: r1@1 (logical replica) +lease expiry_ns: 1795337571673280526; host validity_ns at query: 19706858270 +recorded ACK: r1@1 HEAD generation 3 +host: unknown (not recorded by the master); issued moves and bindings below are separate facts diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-before-start.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-before-start.stdout new file mode 100644 index 0000000000..284ab8c607 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-before-start.stdout @@ -0,0 +1,7 @@ +volume: v1 (query snapshot, not authority to serve) +replica: none +epoch: none +lease state: none +holder: none +recorded ACK: none +host: unknown (not recorded by the master); issued moves and bindings below are separate facts diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-granted.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-granted.stdout new file mode 100644 index 0000000000..71488987f4 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-granted.stdout @@ -0,0 +1,8 @@ +volume: v1 (query snapshot, not authority to serve) +replica: r1 +epoch: 1 +lease state: granted +holder: r1@1 (logical replica) +lease expiry_ns: 1795337571294082097; host validity_ns at query: 19891253918 +recorded ACK: none +host: unknown (not recorded by the master); issued moves and bindings below are separate facts diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-moved.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-moved.stdout new file mode 100644 index 0000000000..40e1fe5ca0 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-moved.stdout @@ -0,0 +1,9 @@ +volume: v1 (query snapshot, not authority to serve) +replica: r1 +epoch: 2 +lease state: granted +holder: r1@2 (logical replica) +lease expiry_ns: 1795337572110285858; host validity_ns at query: 19885280122 +recorded ACK: none +host: unknown (not recorded by the master); issued moves and bindings below are separate facts +move: request=move-v1-1 kind=clean issued=true s1/r1@1 -> s1/r1@2 HEAD generation 3 remote LSN 1 diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-revoked.stdout b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-revoked.stdout new file mode 100644 index 0000000000..3f0ca8c3c0 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/show-revoked.stdout @@ -0,0 +1,8 @@ +volume: v1 (query snapshot, not authority to serve) +replica: r1 +epoch: 1 +lease state: revoking +holder: r1@1 (logical replica) +lease expiry_ns: 1795338384724043516; host validity_ns at query: 19727540908 +recorded ACK: none +host: unknown (not recorded by the master); issued moves and bindings below are separate facts diff --git a/seaweed-block/cmd/blockvolume/testdata/planned-handoff/status-primary.json b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/status-primary.json new file mode 100644 index 0000000000..f33bc5ac9a --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/planned-handoff/status-primary.json @@ -0,0 +1 @@ +{"VolumeID":"v1","ReplicaID":"r1","Epoch":2,"EndpointVersion":1,"Healthy":true,"Memory":{"HeapAllocBytes":1520736,"HeapInuseBytes":3547136,"HeapSysBytes":7503872,"HeapReleasedBytes":3194880,"SoftLimitBytes":268435456,"RSSBytes":21516288,"AnonymousRSSBytes":5230592},"FrontendPrimaryReady":true,"AuthorityRole":"primary","ReplicationRole":"none"} diff --git a/seaweed-block/cmd/blockvolume/testdata/powerloss-replay.sh b/seaweed-block/cmd/blockvolume/testdata/powerloss-replay.sh new file mode 100755 index 0000000000..fe1f67f54d --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/powerloss-replay.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# Power-loss replay harness for TestPowerLossReplayAckedWritesSurvive and +# TestPowerLossReplayChunkVolume. Root only, on a disposable host with the +# dm_log_writes module and replay-log (upstream log-writes); it formats only +# loop devices over private sparse files under WORKDIR. +# +# powerloss-replay.sh REPLAY_LOG WORKDIR -- TEST_COMMAND... +# +# The test runs with SWBLOCK_REPLAY_ROOT (an ext4 mount on dm-log-writes), +# SWBLOCK_REPLAY_LOGS and SWBLOCK_REPLAY_CUT, a helper with two steps: +# mark marks the current log 'acknowledged' +# replay unmounts, replays the current log only up to that mark onto a +# fresh device, puts a new log-writes layer on it and mounts it at +# the same path, so the next power cut is logged too +# Exit status is the test's. Everything this script created is removed. +set -euo pipefail +[ "$(id -u)" = 0 ] || { echo "root required" >&2; exit 2; } +replayer=$(realpath "${1:?replay-log}") +work=$(realpath "${2:?existing empty work dir}") +[ "${3:-}" = -- ] || { echo "usage: $0 REPLAY_LOG WORKDIR -- TEST_COMMAND..." >&2; exit 2; } +shift 3 +for c in losetup dmsetup mkfs.ext4 mount umount mountpoint blockdev truncate; do command -v "$c" >/dev/null; done +dmsetup targets | awk '$1=="log-writes"{f=1} END{exit !f}' || { echo "dm-log-writes unavailable" >&2; exit 2; } +mkdir "$work/mnt" "$work/logs" +name=swb-powerloss-$$ + +# layer K BACKING_IMG: a log-writes target over BACKING_IMG with log K. The +# log holds only writes made through this layer, so its replay starts from a +# copy of BACKING_IMG as it is now (base-K). +layer() { + local k=$1 img=$2 dev log + cp --sparse=always "$img" "$work/base-$k.img" + truncate -s 2G "$work/log-$k.img" + dev=$(losetup --find --show "$img"); echo "$dev" >> "$work/loops" + log=$(losetup --find --show "$work/log-$k.img"); echo "$log" >> "$work/loops" + dmsetup create "$name-$k" --table "0 $(blockdev --getsz "$dev") log-writes $dev $log" + echo "$k $log" > "$work/current" +} +truncate -s 1G "$work/data-0.img" +layer 0 "$work/data-0.img" +mkfs.ext4 -q -F -E lazy_itable_init=0,lazy_journal_init=0 "/dev/mapper/$name-0" +mount "/dev/mapper/$name-0" "$work/mnt" + +cat > "$work/cut" < "$work/logs/dm-status-\$k.txt" + dmsetup remove "$name-\$k" + n=\$((k + 1)) + cp --sparse=always "$work/base-\$k.img" "$work/data-\$n.img" + rep=\$(losetup --find --show "$work/data-\$n.img") + "$replayer" --log "\$log" --replay "\$rep" --end-mark acknowledged > "$work/logs/replay-\$k.log" 2>&1 + losetup -d "\$rep" + # Layer k's own devices stay attached until cleanup; its images are no longer read. + $(declare -f layer) + name="$name" work="$work" + layer "\$n" "$work/data-\$n.img" + mount "/dev/mapper/$name-\$n" "$work/mnt" + echo "replayed to mark onto layer \$n" ;; + *) echo "usage: cut mark|replay" >&2; exit 2 ;; +esac +EOF +chmod 700 "$work/cut" + +cleanup() { + set +e + mountpoint -q "$work/mnt" && umount "$work/mnt" + for d in $(dmsetup ls | awk -v p="$name-" 'index($1, p) == 1 {print $1}'); do dmsetup remove "$d"; done + [ -f "$work/loops" ] && while read -r l; do losetup -d "$l" 2>/dev/null; done < "$work/loops" + # Only the sparse images this script created under WORKDIR. + rm -f -- "$work"/data-*.img "$work"/log-*.img "$work"/base-*.img +} +trap cleanup EXIT +set +e +SWBLOCK_REPLAY_ROOT=$work/mnt SWBLOCK_REPLAY_CUT=$work/cut SWBLOCK_REPLAY_LOGS=$work/logs "$@" +rc=$? +set -e +exit $rc diff --git a/seaweed-block/cmd/blockvolume/ublk_flags_test.go b/seaweed-block/cmd/blockvolume/ublk_flags_test.go new file mode 100644 index 0000000000..2ecf9790cc --- /dev/null +++ b/seaweed-block/cmd/blockvolume/ublk_flags_test.go @@ -0,0 +1,34 @@ +package main + +import "testing" + +func TestUblkFlags(t *testing.T) { + base := func(extra ...string) []string { + return append(phase150RequiredBlockvolumeArgs(), extra...) + } + off, err := parseFlags(base()) + if err != nil || off.ublkDevice != -1 { + t.Fatalf("default: ublk-device=%d err=%v, want -1 (off)", off.ublkDevice, err) + } + on, err := parseFlags(base("--ublk-device=3", "--ublk-queues=2", "--ublk-queue-depth=128")) + if err != nil { + t.Fatal(err) + } + if on.ublkDevice != 3 || on.ublkQueues != 2 || on.ublkQueueDepth != 128 { + t.Fatalf("parsed ublk flags: device %d queues %d depth %d", on.ublkDevice, on.ublkQueues, on.ublkQueueDepth) + } + if !on.enableT1Readiness { + t.Fatal("--ublk-device did not enable the readiness bridge (the device must serve only through a healthy projection)") + } + for name, args := range map[string][]string{ + "queues without a device": base("--ublk-queues=2"), + "depth without a device": base("--ublk-queue-depth=8"), + "negative device id": base("--ublk-device=-2"), + "too many queues": base("--ublk-device=0", "--ublk-queues=65"), + "queue depth too large": base("--ublk-device=0", "--ublk-queue-depth=4097"), + } { + if _, err := parseFlags(args); err == nil { + t.Errorf("%s: parseFlags succeeded; want an error", name) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/volume_delete_procedure_integration_test.go b/seaweed-block/cmd/blockvolume/volume_delete_procedure_integration_test.go new file mode 100644 index 0000000000..32f83a54ce --- /dev/null +++ b/seaweed-block/cmd/blockvolume/volume_delete_procedure_integration_test.go @@ -0,0 +1,286 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "testing" + "time" +) + +// The volume-lifecycle page's "Delete a volume", end to end with the real +// binaries: seal, revoke and wait for the ACK, delete the snapshots, delete +// the volume; and the page's recovery when blockvolume was stopped by a +// signal after the seal (the ACK was skipped). + +// volumeDelete runs the page's step 4 and returns the answer and the exit +// status. +func (env *handoffEnv) volumeDelete(t *testing.T, request string) (string, string, int) { + t.Helper() + return env.h.run(t, "ops", "chunk", "volume-delete", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, + "--master", env.h.masterAddr, "--request-id", request) +} + +// deletePastPrintedHorizon follows volume-lifecycle steps 2-4. The first +// refusal proves the lease is still live; the timestamp only schedules +// retries. The CLI verdict decides success. All retries keep the same id and +// the first T+5s deadline, even if another lease appears (which fails the test). +func (env *handoffEnv) deletePastPrintedHorizon(t *testing.T, volume, request string, requireLive bool) (string, string, int) { + t.Helper() + call := func(ctx context.Context) (string, string, int) { + out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "volume-delete", "--volume", volume, + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, + "--master", env.h.masterAddr, "--request-id", request) + if err != nil { + // a kill by the deadline below: name the store the delete waits on + t.Fatalf("volume-delete %s: %v (its object store: weed %s)", volume, err, weedState(env.cluster.servers())) + } + return out, errOut, code + } + first, stop := context.WithTimeout(context.Background(), 15*time.Second) + defer stop() + out, errOut, code := call(first) + until, err := deleteLeaseHorizon(out, code) + if err != nil { + if requireLive { + t.Fatalf("first delete must refuse the live lease: %v; %s %s", err, out, errOut) + } + return out, errOut, code + } + if wait := time.Until(until); wait < 0 || wait > 90*time.Second { + t.Fatalf("first refusal horizon must be upcoming and within 90s, got %s: %s", until, out) + } + ctx, cancel := context.WithDeadline(context.Background(), until.Add(5*time.Second)) + defer cancel() + timer := time.NewTimer(time.Until(until)) + defer timer.Stop() + for { + select { + case <-ctx.Done(): + t.Fatalf("delete did not resolve by original horizon + 5s (its object store: weed %s): %s %s", weedState(env.cluster.servers()), out, errOut) + case <-timer.C: + } + out, errOut, code = call(ctx) + next, err := deleteLeaseHorizon(out, code) + if err != nil { + return out, errOut, code + } + if !next.Equal(until) { + t.Fatalf("lease horizon changed from %s to %s; refusing to widen deadline", until, next) + } + timer.Reset(100 * time.Millisecond) + } +} + +// deleteLeaseHorizon accepts only the documented typed CLI refusal, never +// a matching stderr fragment or a successful exit with an error-shaped body. +func deleteLeaseHorizon(out string, code int) (time.Time, error) { + var body struct { + Code string `json:"code"` + Message string `json:"message"` + } + if code != 1 { + return time.Time{}, fmt.Errorf("exit %d is not refusal", code) + } + if err := json.Unmarshal([]byte(out), &body); err != nil { + return time.Time{}, err + } + if body.Code != "not_admitted" { + return time.Time{}, fmt.Errorf("code %q is not not_admitted", body.Code) + } + _, rest, ok := strings.Cut(body.Message, "live until ") + if !ok { + return time.Time{}, fmt.Errorf("missing lease horizon") + } + fields := strings.Fields(rest) + if len(fields) == 0 { + return time.Time{}, fmt.Errorf("empty lease horizon") + } + return time.Parse(time.RFC3339Nano, strings.TrimSuffix(fields[0], ":")) +} + +// The CLI error body, rather than a substring in combined output, is the +// authority for retry timing. Every refusal class stays distinguishable. +func TestDeleteLeaseHorizonRequiresTypedRefusal(t *testing.T) { + const valid = `{"code":"not_admitted","message":"workspace delete: live until 2026-11-26T13:00:00.125Z: lease expiry plus clock-skew margin has not elapsed"}` + for _, tc := range []struct { + name, out string + code int + ok bool + }{ + {"typed horizon", valid, 1, true}, + {"successful exit cannot refuse", valid, 0, false}, + {"usage failure", valid, 2, false}, + {"plain stderr is not evidence", "not_admitted: live until 2026-11-26T13:00:00.125Z", 1, false}, + {"dependent refusal", `{"code":"snapshot_has_dependents","message":"snapshot s1"}`, 1, false}, + {"uncertain lease", `{"code":"not_admitted","message":"restart required"}`, 1, false}, + {"missing time", `{"code":"not_admitted","message":"live until "}`, 1, false}, + {"invalid time", `{"code":"not_admitted","message":"live until tomorrow: refused"}`, 1, false}, + } { + t.Run(tc.name, func(t *testing.T) { + until, err := deleteLeaseHorizon(tc.out, tc.code) + if (err == nil) != tc.ok { + t.Fatalf("horizon %s error %v, want valid=%v", until, err, tc.ok) + } + if tc.ok && until.Format(time.RFC3339Nano) != "2026-11-26T13:00:00.125Z" { + t.Fatalf("wrong horizon %s", until) + } + }) + } +} + +// requireDeleteCompleted checks step 4's documented state:"deleted" result +// (volume-lifecycle.md, "Delete a volume", step 4). Retries use the same +// request id and must complete again; the CLI reports no replayed flag. +func requireDeleteCompleted(t *testing.T, out, errOut string, code int) { + t.Helper() + if code != 0 || !handoffDeleteCompleted(out) { + t.Fatalf("volume-delete: exit %d %s %s; want a volume directory and state deleted", code, out, errOut) + } +} + +// headShown reads head.State and independently counts stored pool objects. +// volume-lifecycle.md step 4 specifies that show has no chunkCount field; +// its object-listing alternative preserves the checks that nothing was +// removed on refusal and no chunks remain after completion. +func (env *handoffEnv) headShown(t *testing.T) (string, int) { + t.Helper() + var head struct { + State string `json:"state"` + } + out := env.headOf(t, "v1") + if err := json.Unmarshal([]byte(out), &head); err != nil { + t.Fatalf("chunk show: %v %s", err, out) + } + return head.State, env.poolObjects(t, "v1") +} + +// requireDeletedForGood checks the page's deleted HEAD and empty pool, +// then repeats the delete with the same request id and checks both again. +func (env *handoffEnv) requireDeletedForGood(t *testing.T, request string) { + t.Helper() + if state, n := env.headShown(t); state != "deleted" || n != 0 { + t.Fatalf("after the delete: HEAD state %q, pool objects %d; want deleted, 0", state, n) + } + out, errOut, code := env.volumeDelete(t, request) + requireDeleteCompleted(t, out, errOut, code) + if state, n := env.headShown(t); state != "deleted" || n != 0 { + t.Fatalf("after the repeated delete: HEAD state %q, pool objects %d; want deleted, 0", state, n) + } +} + +// TestProcedureDeleteAVolume: ACK does not bypass the lease horizon; a +// restored-volume dependent blocks deletion, while ordinary snapshots do not. +// Refusals preserve HEAD/pool; completion empties the pool and replays by id. +func TestProcedureDeleteAVolume(t *testing.T) { + env := startHandoffEnvWith(t, 1, []string{"v2"}) + holder := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, holder, "s1") + env.writeBlock(t, "s1", 0, pattern("delete-a-volume!")) + env.snapshot(t, "s1", "v1", "s1") + env.snapshot(t, "s1", "v1", "plain") + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", + "--snapshot", "s1", "--target", "v2", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + + g := env.seal(t, "s1", e) + env.revoke(t, e, g) + if err := holder.wait(30 * time.Second); err != nil { + t.Fatalf("s1 after the revocation: %v; want a clean exit by itself", err) + } + env.waitAck(t, e, g) + + state0, n0 := env.headShown(t) + out, errOut, code := env.deletePastPrintedHorizon(t, "v1", "del-v1", true) + var refusal struct { + Code string `json:"code"` + Message string `json:"message"` + } + if err := json.Unmarshal([]byte(out), &refusal); err != nil || code != 1 || refusal.Code != "snapshot_has_dependents" || !strings.Contains(refusal.Message, `snapshot "s1"`) { + t.Fatalf("volume-delete with a dependent: exit %d %s %s; want typed snapshot_has_dependents naming s1", code, out, errOut) + } + if state, n := env.headShown(t); state != "detached" || state != state0 || n != n0 || n == 0 { + t.Fatalf("after the refused delete HEAD is %q with %d chunks; want it as before (%q, %d chunks): nothing deleted", state, n, state0, n0) + } + // v2 never started; delete it through the public API (and its own horizon, + // if the master granted a line). This releases s1's dependent. + out, errOut, code = env.deletePastPrintedHorizon(t, "v2", "del-v2", false) + requireDeleteCompleted(t, out, errOut, code) + if state, n := env.headOf(t, "v2"), env.poolObjects(t, "v2"); !strings.Contains(state, `"state":"deleted"`) || n != 0 { + t.Fatalf("restored target not deleted: HEAD %s pool %d", state, n) + } + // Both snapshots still exist, now without dependents: plain snapshots + // must be removed by the volume delete itself, not by this fixture. + snapshots, _ := env.h.command(t, "ops", "chunk", "snapshots", "--master", env.h.masterAddr, + "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + var names []struct { + Name string `json:"name"` + Dependents []string `json:"dependents"` + } + if err := json.Unmarshal([]byte(snapshots), &names); err != nil { + t.Fatal(err) + } + seen := map[string]bool{} + for _, snap := range names { + if len(snap.Dependents) != 0 { + t.Fatalf("dependent not released: %s", snapshots) + } + seen[snap.Name] = true + } + if !seen["s1"] || !seen["plain"] { + t.Fatalf("plain snapshots disappeared before volume-delete: %s", snapshots) + } + out, errOut, code = env.volumeDelete(t, "del-v1") + requireDeleteCompleted(t, out, errOut, code) + env.requireDeletedForGood(t, "del-v1") +} + +// TestProcedureDeleteAfterASignalStop: a sealed holder stopped by SIGTERM +// stays down. The first delete refuses the live lease and changes nothing; +// the same request completes after its printed horizon without a restart or +// ACK. A retry completes again, and a late start cannot claim or serve. +func TestProcedureDeleteAfterASignalStop(t *testing.T) { + env := startHandoffEnv(t, 1) + holder := env.start(t, "blockvolume-s1", "s1") + e := env.adopt(t, holder, "s1") + env.writeBlock(t, "s1", 0, pattern("delete-after-sig")) + env.seal(t, "s1", e) + holder.term(t, 30*time.Second) + stopped := func() { + t.Helper() + select { + case <-holder.done: + default: + t.Fatal("signal-stopped holder is still running") + } + if listening(env.hosts["s1"].status) { + t.Fatal("signal-stopped holder listened again before deletion") + } + } + stopped() + state0, n0 := env.headShown(t) + out, errOut, code := env.volumeDelete(t, "del-v1") + if _, err := deleteLeaseHorizon(out, code); err != nil { + t.Fatalf("volume-delete after signal stop: exit %d %s %s; want typed live-until refusal: %v", code, out, errOut, err) + } + if state, n := env.headShown(t); state != "detached" || state != state0 || n != n0 || n == 0 { + t.Fatalf("refused delete changed HEAD/pool: %q %d; before %q %d", state, n, state0, n0) + } + stopped() + out, errOut, code = env.deletePastPrintedHorizon(t, "v1", "del-v1", true) + requireDeleteCompleted(t, out, errOut, code) + stopped() + env.requireDeletedForGood(t, "del-v1") + late := env.start(t, "blockvolume-s1-late", "s1") + err := late.wait(60 * time.Second) + served := late.has("blockvolume: backend admits I/O: starting the frontends") || volumeFrontendReady(env.hosts["s1"].status, "v1") + keepFullLog(t, late) + if err == nil || strings.Contains(fmt.Sprint(err), "still running") || served { + t.Fatalf("late start after deletion must exit without serving: exit=%v served=%v", err, served) + } + if state, n := env.headShown(t); state != "deleted" || n != 0 { + t.Fatalf("late start changed deleted HEAD/pool: %q %d", state, n) + } +} diff --git a/seaweed-block/cmd/blockvolume/volume_lock_env_ext_test.go b/seaweed-block/cmd/blockvolume/volume_lock_env_ext_test.go new file mode 100644 index 0000000000..0f08caa197 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/volume_lock_env_ext_test.go @@ -0,0 +1,37 @@ +package main_test + +import ( + "os" + "os/exec" + "strings" +) + +// stripSystemdForTestLockDir is the external test package's copy of the +// helper in volume_lock_env_test.go (package main_test cannot use it): a +// child started with --volume-lock-dir-test-only gets an environment without +// INVOCATION_ID, which a systemd-run test runner would otherwise pass on. +func stripSystemdForTestLockDir(cmd *exec.Cmd) *exec.Cmd { + const flag = "--volume-lock-dir-test-only" + hasFlag := false + for _, a := range cmd.Args[1:] { + if a == flag || strings.HasPrefix(a, flag+"=") { + hasFlag = true + break + } + } + if !hasFlag { + return cmd + } + env := cmd.Env + if env == nil { + env = os.Environ() + } + kept := make([]string, 0, len(env)) + for _, kv := range env { + if !strings.HasPrefix(kv, "INVOCATION_ID=") { + kept = append(kept, kv) + } + } + cmd.Env = kept + return cmd +} diff --git a/seaweed-block/cmd/blockvolume/volume_lock_env_test.go b/seaweed-block/cmd/blockvolume/volume_lock_env_test.go new file mode 100644 index 0000000000..7aa93a3144 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/volume_lock_env_test.go @@ -0,0 +1,37 @@ +package main + +import ( + "os" + "os/exec" + "strings" +) + +// stripSystemdForTestLockDir gives a blockvolume child started with +// --volume-lock-dir-test-only an environment without INVOCATION_ID. +// blockvolume refuses the test override under systemd; a test runner that is +// itself a systemd service (a CI runner unit) would otherwise pass its +// INVOCATION_ID to every child. Other children are left as they are. +func stripSystemdForTestLockDir(cmd *exec.Cmd) *exec.Cmd { + hasFlag := false + for _, a := range cmd.Args[1:] { + if a == "--"+volumeLockDirTestOnlyFlag || strings.HasPrefix(a, "--"+volumeLockDirTestOnlyFlag+"=") { + hasFlag = true + break + } + } + if !hasFlag { + return cmd + } + env := cmd.Env + if env == nil { + env = os.Environ() + } + kept := make([]string, 0, len(env)) + for _, kv := range env { + if !strings.HasPrefix(kv, "INVOCATION_ID=") { + kept = append(kept, kv) + } + } + cmd.Env = kept + return cmd +} diff --git a/seaweed-block/cmd/blockvolume/volume_lock_flag_test.go b/seaweed-block/cmd/blockvolume/volume_lock_flag_test.go new file mode 100644 index 0000000000..d0cd8da6fc --- /dev/null +++ b/seaweed-block/cmd/blockvolume/volume_lock_flag_test.go @@ -0,0 +1,52 @@ +package main + +import ( + "io" + "os" + "strings" + "testing" + "time" +) + +// The test lock directory override is refused under systemd +// (INVOCATION_ID set), so it cannot reach a shipped unit. +func TestVolumeLockDirTestOnlyRefusedUnderSystemd(t *testing.T) { + args := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore", "--volume-lock-dir-test-only="+t.TempDir()) + t.Setenv("INVOCATION_ID", "") + f, err := parseFlags(args) + if err != nil || f.volumeLockDirTestOnly == "" { + t.Fatalf("the test override outside systemd: %+v %v", f.volumeLockDirTestOnly, err) + } + t.Setenv("INVOCATION_ID", "0123456789abcdef") + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "refused under systemd") { + t.Fatalf("the test override was accepted under systemd: %v", err) + } +} + +// The test override is hidden from --help. +func TestVolumeLockDirTestOnlyHiddenFromHelp(t *testing.T) { + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + saved := os.Stderr + t.Cleanup(func() { os.Stderr = saved; _ = w.Close(); _ = r.Close() }) + read := make(chan []byte, 1) + go func() { b, _ := io.ReadAll(r); read <- b }() // usage exceeds a pipe buffer + os.Stderr = w + _, parseErr := parseFlags([]string{"-h"}) + os.Stderr = saved + _ = w.Close() // release the reader before joining it + var out []byte + select { + case out = <-read: + case <-time.After(10 * time.Second): + t.Fatal("usage reader did not finish") + } + if parseErr == nil || !strings.Contains(string(out), "-durable-root") { + t.Fatalf("no usage printed: %v %q", parseErr, out) + } + if strings.Contains(string(out), volumeLockDirTestOnlyFlag) { + t.Fatalf("--help lists the test override:\n%s", out) + } +} diff --git a/seaweed-block/cmd/blockvolume/volume_size_admission_test.go b/seaweed-block/cmd/blockvolume/volume_size_admission_test.go new file mode 100644 index 0000000000..495e326770 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/volume_size_admission_test.go @@ -0,0 +1,27 @@ +package main + +import ( + "strconv" + "strings" + "testing" +) + +func TestDurableCreateFlagsValidateOriginalGeometry(t *testing.T) { + if strconv.IntSize < 64 { + t.Skip("64-bit CLI uint overflow case") + } + for _, blocks := range []string{"4294967297", "18446744073709551615"} { + args := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-blocks="+blocks) + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "durable-blocks") { + t.Fatalf("blocks %s: %v", blocks, err) + } + } + args := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-blocks=4294967295", "--durable-blocksize=4096") + if _, err := parseFlags(args); err != nil { + t.Fatal(err) + } + args = append(args, "--durable-blocksize=8192") + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("oversize geometry: %v", err) + } +} diff --git a/seaweed-block/cmd/blockvolume/wal_hold_config_test.go b/seaweed-block/cmd/blockvolume/wal_hold_config_test.go new file mode 100644 index 0000000000..7e1f463dd2 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/wal_hold_config_test.go @@ -0,0 +1,42 @@ +package main + +import ( + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +func TestParseFlagsWALHoldHostTimeout(t *testing.T) { + for _, tc := range []struct { + name string + args []string + hold, host time.Duration + valid bool + }{ + {"defaults", nil, 25 * time.Second, 30 * time.Second, true}, + {"explicit equality", []string{"--wal-hold-timeout", "10s", "--host-io-timeout", "15s"}, 10 * time.Second, 15 * time.Second, true}, + {"host lowered without hold", []string{"--host-io-timeout", "29s"}, 0, 0, false}, + {"hold above margin", []string{"--wal-hold-timeout", "25.000000001s"}, 0, 0, false}, + {"zero hold", []string{"--wal-hold-timeout", "0"}, 0, 0, false}, + } { + t.Run(tc.name, func(t *testing.T) { + args := append(requiredBlockvolumeArgs(), tc.args...) + f, err := parseFlags(args) + if tc.valid { + if err != nil { + t.Fatal(err) + } + if f.walHold.MaxHold != tc.hold || f.walHold.HostIOTimeout != tc.host { + t.Fatalf("parsed policy: %+v", f.walHold) + } + } else { + var invalid *frontend.WALHoldConfigError + if !errors.As(err, &invalid) { + t.Fatalf("want typed startup refusal, got %v", err) + } + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/weed_failure_report_test.go b/seaweed-block/cmd/blockvolume/weed_failure_report_test.go new file mode 100644 index 0000000000..82d4c6e38a --- /dev/null +++ b/seaweed-block/cmd/blockvolume/weed_failure_report_test.go @@ -0,0 +1,214 @@ +package main_test + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "testing" +) + +// weedServer is one weed server of a test cluster: its name, its log file, +// and whether it exited (with its status). +type weedServer struct { + name, log string + exited bool + err error +} + +// weedState names each server, by name, as running or exited with its status. +func weedState(servers []weedServer) string { + s := append([]weedServer(nil), servers...) + sort.Slice(s, func(i, j int) bool { return s[i].name < s[j].name }) + parts := make([]string, 0, len(s)) + for _, x := range s { + switch { + case !x.exited: + parts = append(parts, x.name+" running") + case x.err != nil: + parts = append(parts, fmt.Sprintf("%s exited (%v)", x.name, x.err)) + default: + parts = append(parts, x.name+" exited (status 0)") + } + } + return strings.Join(parts, ", ") +} + +// weedReportTails: the master's and the volume server's last lines a report +// carries, the volume server last. With a header each they are the 20 +// continuation lines the CI summary keeps of one message. +var weedReportTails = []struct { + name string + lines int +}{{"master", 8}, {"volume", 10}} + +// weedFailureReport is a failed test's evidence of its cluster: the state of +// each server, then the master's and the volume server's last log lines. +func weedFailureReport(servers []weedServer) string { + var b strings.Builder + fmt.Fprintf(&b, "weed cluster at the failure: %s\n", weedState(servers)) + for _, tail := range weedReportTails { + for _, s := range servers { + if s.name != tail.name { + continue + } + fmt.Fprintf(&b, "%s, last %d lines:\n", s.name, tail.lines) + for _, l := range lastLogLines(s.log, tail.lines) { + b.WriteString(l + "\n") + } + } + } + return b.String() +} + +// weedCleanupT is what registerWeedReport needs of a test. +type weedCleanupT interface { + Cleanup(func()) + Failed() bool + Log(args ...any) +} + +// registerWeedReport registers the cluster's failure report. Called right +// after each server's own stop cleanup is registered, the latest registration +// runs before every stop (cleanups run last-in first-out), so the report sees +// each server as the failure left it, whenever the test fails, also while the +// cluster is still starting. once makes it one report per cluster; skip +// drops the report of a start attempt that was discarded (its failure message +// already carried one). +func registerWeedReport(t weedCleanupT, once *sync.Once, skip func() bool, servers func() []weedServer) { + t.Cleanup(func() { + if !t.Failed() || skip() { + return + } + once.Do(func() { t.Log(weedFailureReport(servers())) }) + }) +} + +// weedStartFailure is the message of a failed start attempt, with the +// cluster's evidence taken before its servers are stopped. +func weedStartFailure(attempt, starts int, err error, servers []weedServer) string { + return fmt.Sprintf("weed start %d of %d did not start: %v; %s", attempt, starts, err, weedFailureReport(servers)) +} + +// lastLogLines is the last n lines of the log at path (one line naming the +// error when it cannot be read). +func lastLogLines(path string, n int) []string { + data, err := os.ReadFile(path) + if err != nil { + return []string{fmt.Sprintf("(log not readable: %v)", err)} + } + lines := strings.Split(strings.TrimRight(string(data), "\n"), "\n") + if len(lines) > n { + lines = lines[len(lines)-n:] + } + return lines +} + +// fakeWeedLog writes a log of n numbered lines for name. +func fakeWeedLog(t *testing.T, dir, name string, n int) string { + t.Helper() + var b strings.Builder + for i := 1; i <= n; i++ { + fmt.Fprintf(&b, "%s line %d\n", name, i) + } + path := filepath.Join(dir, name+".log") + if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil { + t.Fatal(err) + } + return path +} + +// A failed test's evidence names each weed server as running or exited with +// its status, then the master's and the volume server's last lines (the +// volume server last, inside the 20 continuation lines the CI summary keeps). +func TestWeedFailureReportNamesEachServerAndItsTail(t *testing.T) { + dir := t.TempDir() + servers := []weedServer{ + {name: "volume", log: fakeWeedLog(t, dir, "volume", 30), exited: true, err: errors.New("signal: killed")}, + {name: "master", log: fakeWeedLog(t, dir, "master", 30)}, + {name: "filer", log: fakeWeedLog(t, dir, "filer", 30)}, + } + if got, want := weedState(servers), "filer running, master running, volume exited (signal: killed)"; got != want { + t.Fatalf("state %q, want %q", got, want) + } + lines := strings.Split(strings.TrimRight(weedFailureReport(servers), "\n"), "\n") + if len(lines) < 2 || !strings.Contains(lines[0], weedState(servers)) { + t.Fatalf("report does not open with the state: %q", lines) + } + cont := strings.Join(lines[1:], "\n") + if len(lines)-1 > 20 { + t.Fatalf("%d continuation lines: the CI summary keeps the last 20", len(lines)-1) + } + if lines[len(lines)-1] != "volume line 30" || !strings.Contains(cont, "master line 30") { + t.Fatalf("report does not end with the volume server's last line or lacks the master's: %q", lines) + } + if strings.Contains(cont, "volume line 1\n") || strings.Contains(cont, "filer line") { + t.Fatalf("report holds a whole log or the filer's: %q", lines) + } +} + +// A start that fails (a server never listened, or every attempt failed) is +// reported with the same evidence, taken before its servers are stopped: the +// state of each server and the master's and the volume server's last lines. +func TestWeedStartFailureCarriesTheReport(t *testing.T) { + dir := t.TempDir() + servers := []weedServer{ + {name: "master", log: fakeWeedLog(t, dir, "master", 30)}, + {name: "volume", log: fakeWeedLog(t, dir, "volume", 30), exited: true, err: errors.New("exit status 1")}, + } + msg := weedStartFailure(2, 3, errors.New("volume never listened"), servers) + for _, want := range []string{"start 2 of 3", "volume never listened", weedState(servers), "master line 30", "volume line 30"} { + if !strings.Contains(msg, want) { + t.Fatalf("start failure %q lacks %q", msg, want) + } + } +} + +// fakeCleanupT records cleanups and runs them last-in first-out, as testing.T. +type fakeCleanupT struct { + cleanups []func() + failed bool + logs []string +} + +func (f *fakeCleanupT) Cleanup(fn func()) { f.cleanups = append(f.cleanups, fn) } +func (f *fakeCleanupT) Failed() bool { return f.failed } +func (f *fakeCleanupT) Log(args ...any) { f.logs = append(f.logs, fmt.Sprint(args...)) } +func (f *fakeCleanupT) finish() { + for i := len(f.cleanups) - 1; i >= 0; i-- { + f.cleanups[i]() + } +} + +// A test that fails while its cluster is still starting (a t.Fatal after the +// servers are up but before the start returns) gets one report, taken before +// any server is stopped: the report is registered after each server's own +// stop cleanup, once per cluster. +func TestWeedReportCoversAFailureDuringTheStart(t *testing.T) { + dir := t.TempDir() + ft := &fakeCleanupT{} + alive := map[string]bool{} + var once sync.Once + servers := func() []weedServer { + var out []weedServer + for _, n := range []string{"master", "volume", "filer"} { + if _, started := alive[n]; started { + out = append(out, weedServer{name: n, log: fakeWeedLog(t, dir, n, 3), exited: !alive[n], err: errors.New("signal: killed")}) + } + } + return out + } + for _, n := range []string{"master", "volume", "filer"} { + alive[n] = true + ft.Cleanup(func() { alive[n] = false }) // the server's own stop cleanup + registerWeedReport(ft, &once, func() bool { return false }, servers) + } + ft.failed = true // e.g. the filer front's listener fails before the start returns + ft.finish() + if len(ft.logs) != 1 || !strings.Contains(ft.logs[0], "filer running, master running, volume running") { + t.Fatalf("reports %q: want one, with every server still running", ft.logs) + } +} diff --git a/seaweed-block/cmd/blockvolume/weed_ports_integration_test.go b/seaweed-block/cmd/blockvolume/weed_ports_integration_test.go new file mode 100644 index 0000000000..a5e662abc7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/weed_ports_integration_test.go @@ -0,0 +1,22 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import "testing" + +// TestWeedPortPairsAvoidTheEphemeralRange: no port of a weed port pair lies in +// the host's range for outgoing connections' source ports, where any +// connection could take it between w4FreePortPair's free check and weed's bind +// (a filer's gRPC port inside a host's 43255-47350 failed to bind that way). +func TestWeedPortPairsAvoidTheEphemeralRange(t *testing.T) { + lo, hi := ephemeralPorts() + used := map[int]bool{} + for i := 0; i < 100; i++ { + p := w4FreePortPair(t, used) + for _, q := range []int{p, p + 10000} { + if q >= lo && q <= hi { + t.Fatalf("pair %d/%d: port %d is in the ephemeral range %d-%d", p, p+10000, q, lo, hi) + } + } + } +} diff --git a/seaweed-block/cmd/blockvolume/workspace_flags_test.go b/seaweed-block/cmd/blockvolume/workspace_flags_test.go new file mode 100644 index 0000000000..f4429e1389 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/workspace_flags_test.go @@ -0,0 +1,22 @@ +package main + +import "testing" + +func TestWorkspaceLeaseFlagIsExplicitAndChunkOnly(t *testing.T) { + base := []string{"--master", "127.0.0.1:1", "--server-id", "node-a", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:9100", "--ctrl-addr", "127.0.0.1:9101"} + legacy, err := parseFlags(base) + if err != nil || legacy.workspaceLease { + t.Fatal("legacy mode changed", legacy, err) + } + if _, err := parseFlags(append(append([]string{}, base...), "--workspace-lease")); err == nil { + t.Fatal("workspace lease accepted without walstore-chunk") + } + chunk := append(append([]string{}, base...), "--durable-root", t.TempDir(), "--durable-impl", "walstore-chunk", "--chunk-filer", "127.0.0.1:18888") + if _, err := parseFlags(chunk); err == nil { + t.Fatal("chunk volume started without its required workspace lease") + } + enabled, err := parseFlags(append(chunk, "--workspace-lease")) + if err != nil || !enabled.workspaceLease { + t.Fatal("explicit workspace flag not installed", err) + } +} diff --git a/seaweed-block/cmd/blockvolume/workspace_layout_move_integration_test.go b/seaweed-block/cmd/blockvolume/workspace_layout_move_integration_test.go new file mode 100644 index 0000000000..4face27722 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/workspace_layout_move_integration_test.go @@ -0,0 +1,296 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "os" + "os/exec" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + master "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +// moveHost is one blockvolume process of the move test: its addresses and +// the running binary. +type moveHost struct { + server, data, ctrl, status, nvme, nqn string + cmd *exec.Cmd + done chan error + exited bool +} + +func newMoveHost(t *testing.T, server, nqn string) *moveHost { + return &moveHost{server: server, data: leaseBinaryAddress(t), ctrl: leaseBinaryAddress(t), status: leaseBinaryAddress(t), + nvme: leaseBinaryAddress(t), nqn: nqn} +} + +// start runs the blockvolume binary for vol-a as replica r1 on this host, +// with the master-minted layout identity, and kills it at cleanup. +func (m *moveHost) start(t *testing.T, exe, masterAddr, filerGRPC, base string, layoutID layout.VolumeID) { + t.Helper() + logPath := filepath.Join(t.TempDir(), m.server+".log") + log, err := os.Create(logPath) + if err != nil { + t.Fatal(err) + } + m.cmd = exec.Command(exe, "--master", masterAddr, "--server-id", m.server, "--volume-id", "vol-a", "--replica-id", "r1", + "--data-addr", m.data, "--ctrl-addr", m.ctrl, "--t1-readiness", "--status-addr", m.status, + "--durable-root", t.TempDir(), "--layout-id", layoutID.String(), "--volume-lock-dir-test-only", t.TempDir(), + "--durable-impl", "walstore-chunk", "--durable-blocks", "64", "--chunk-filer", filerGRPC, "--chunk-path", base, + "--chunk-control-endpoint", "--workspace-lease", "--nvme-listen", m.nvme, "--nvme-subsysnqn", m.nqn) + stripSystemdForTestLockDir(m.cmd) + m.cmd.Stdout, m.cmd.Stderr = log, log + if err := m.cmd.Start(); err != nil { + t.Fatal(err) + } + m.done = make(chan error, 1) + go func() { m.done <- m.cmd.Wait() }() + t.Cleanup(func() { + if !m.exited { + _ = m.cmd.Process.Kill() + select { + case <-m.done: + case <-time.After(5 * time.Second): + t.Errorf("%s did not exit after kill", m.server) + } + } + log.Close() + if t.Failed() { + b, _ := os.ReadFile(logPath) + if len(b) > 14000 { + b = b[len(b)-14000:] + } + t.Logf("%s log: %s", m.server, b) + } + }) +} + +// wait waits for the process to end on its own within d. +func (m *moveHost) wait(t *testing.T, d time.Duration) { + t.Helper() + select { + case <-m.done: + m.exited = true + case <-time.After(d): + t.Fatalf("%s did not exit", m.server) + } +} + +// projection is the volume's status as this host reports it. +func (m *moveHost) projection() (frontend.Projection, bool) { + c := &http.Client{Timeout: time.Second} + resp, err := c.Get("http://" + m.status + "/status?volume=vol-a") + if err != nil { + return frontend.Projection{}, false + } + defer resp.Body.Close() + var p frontend.Projection + return p, json.NewDecoder(resp.Body).Decode(&p) == nil +} + +// layoutHead reads ref's HEAD as stored (claim id included). +func layoutHead(t *testing.T, cluster *w4WeedCluster, base string, ref chunkstore.VolumeRef) layout.Head { + t.Helper() + cl := cluster.client(t, base) + cat, err := chunkstore.NewBCatalog(cl, cl, base) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + h, found, err := cat.ReadHead(ctx, ref) + if err != nil || !found { + t.Fatalf("HEAD of %s: found %v, %v", ref.Name, found, err) + } + return h +} + +// A move on the content-named layout with real processes: the master in +// process, SeaweedFS and two blockvolume binaries. Clean: the source writes, +// cuts and stops (HEAD detached by the source's claim), the master moves the +// volume, the target claims HEAD at the higher epoch and reads back every +// acknowledged write. Forced: the source is killed after its cut and one more +// acknowledged write; after the master's barrier the forced move is issued +// with its lost range recorded, and the target claims and reads back what the +// cut published. HEAD's state, epoch, holder and claim are asserted at each +// step. +func TestIntegrationWorkspaceLayoutMove(t *testing.T) { + if os.Getenv("CHUNKSTORE_WEED") == "" { + t.Skip("CHUNKSTORE_WEED not set") + } + exe := blockvolumeUnderTest(t) + cluster := startWorkspaceWeed(t) + for _, kind := range []string{"clean", "forced"} { + t.Run(kind, func(t *testing.T) { layoutMove(t, exe, cluster, kind) }) + } +} + +func layoutMove(t *testing.T, exe string, cluster *w4WeedCluster, kind string) { + base := fmt.Sprintf("/workspace-move-%s-%d", kind, time.Now().UnixNano()) + cl := cluster.client(t, base) + headCat, err := chunkstore.NewBCatalog(cl, cl, base) + if err != nil { + t.Fatal(err) + } + var h *master.Host + reader, err := master.NewLayoutWorkspaceHEADReader(headCat, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) { + return h.WorkspaceLayoutVolume(ctx, name) + }) + if err != nil { + t.Fatal(err) + } + h, err = master.New(master.Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", + WorkspaceRPC: true, LifecycleProductLoop: true, WorkspaceHeadReader: reader, WorkspaceMaxClockSkew: 100 * time.Millisecond, + LayoutCreateVolume: layoutMasterWriter(t, cluster, base)}) + if err != nil { + t.Fatal(err) + } + h.Start() + t.Cleanup(func() { + ctx, c := context.WithTimeout(context.Background(), 5*time.Second) + defer c() + _ = h.Close(ctx) + }) + runProductLoop(t, h) + src, dst := newMoveHost(t, "node-a", "nqn.2026-11.test:move-src-"+kind), newMoveHost(t, "node-b", "nqn.2026-11.test:move-dst-"+kind) + // The master's create writes VOLUME and the unclaimed HEAD, then marks + // the record store-ready; only a store-ready volume gets a placement. + layoutID := createStoreReadyVolume(t, h, "vol-a", 64*4096) + ref := chunkstore.VolumeRef{Name: "vol-a", ID: layoutID} + for _, n := range []*moveHost{src, dst} { + if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: n.server, DataAddr: n.data, CtrlAddr: n.ctrl}); err != nil { + t.Fatal(err) + } + } + if _, err = h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "vol-a", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{ + {VolumeID: "vol-a", ServerID: src.server, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { + t.Fatal(err) + } + earlyLineControl(t, h, src.server, "vol-a", "r1", src.data, src.ctrl) + remote := cluster.remote(t, base, ref) + + // The source starts, reports its process, gets its line, serves, takes + // acknowledged writes, cuts. + src.start(t, exe, h.Addr(), cluster.filerGRPC, base, layoutID) + tickAfterProcessReports(t, h, src.server, "vol-a", "r1") + line, _ := h.Publisher().VolumeAuthorityLine("vol-a") + leaseBinaryPoll(t, "source did not serve", func() bool { p, ok := src.projection(); return ok && p.Healthy && p.Epoch == line.Epoch }) + want, late := bytes.Repeat([]byte{0xD7}, 4096), bytes.Repeat([]byte{0x5A}, 4096) + nv := gap1ConnectNVMe(t, src.nvme, src.nqn) + nv.writeFlush(t, 8, want) + nv.writeFlush(t, 9, want) + leaseBinaryPoll(t, "source cut", func() bool { code, _, e := leaseBinaryPost(src.status, "cut"); return e == nil && code == 200 }) + cut := layoutHead(t, cluster, base, ref) + if cut.Epoch != line.Epoch || cut.Holder != src.server+"/r1" || cut.ClaimID == "" || cut.State != layout.StateLive || cut.Current == nil { + t.Fatalf("HEAD after the source's cut: %+v; want live, held by %s/r1 at epoch %d with a claim", cut, src.server, line.Epoch) + } + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ws := control.NewWorkspaceServiceClient(conn) + ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second) + defer cancel() + q := &control.WorkspaceMove{RequestId: kind + "-move", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch, + TargetReplicaId: "r1", TargetServerId: dst.server, TargetDataAddr: dst.data, TargetCtrlAddr: dst.ctrl, Kind: kind, Force: kind == "forced"} + if kind == "clean" { + nv.close() + code, b, e := leaseBinaryPost(src.status, "detach") + if e != nil || code != 200 { + t.Fatalf("detach: %d %s %v", code, b, e) + } + sealed := layoutHead(t, cluster, base, ref) + if sealed.State != layout.StateDetached || sealed.Epoch != line.Epoch || sealed.Holder != cut.Holder || sealed.ClaimID != cut.ClaimID { + t.Fatalf("HEAD after the detach: %+v; want detached by the source's claim %q at epoch %d", sealed, cut.ClaimID, line.Epoch) + } + if _, err = ws.RevokeWorkspace(ctx, &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: "r1", Epoch: line.Epoch}); err != nil { + t.Fatal(err) + } + leaseBinaryPoll(t, "source did not ACK its drained stop", func() bool { s := h.Publisher().WorkspaceState("vol-a"); return s != nil && s.Ack != nil }) + src.wait(t, 15*time.Second) + } else { + // One more acknowledged write after the cut, then the source dies + // without a stop: the forced move records it as possibly lost. + nv.writeFlush(t, 10, late) + nv.close() + if err = src.cmd.Process.Signal(syscall.SIGKILL); err != nil { + t.Fatal(err) + } + src.wait(t, 10*time.Second) + killed := layoutHead(t, cluster, base, ref) + if killed.State != layout.StateLive || killed.Epoch != line.Epoch || killed.ClaimID != cut.ClaimID { + t.Fatalf("HEAD after the kill: %+v; want still the source's live claim", killed) + } + // The master owns the barrier: wait for its affirmative preview. + for { + pv, err := ws.PreviewWorkspaceMove(ctx, q) + if err != nil { + t.Fatal(err) + } + if pv.Admitted { + break + } + select { + case <-time.After(200 * time.Millisecond): + case <-ctx.Done(): + t.Fatalf("forced preview never admitted: %v (last reason %q)", ctx.Err(), pv.Reason) + } + } + } + before := layoutHead(t, cluster, base, ref) + grant, err := ws.MoveWorkspace(ctx, q) + if err != nil { + t.Fatal(err) + } + if !grant.Issued || grant.NewEpoch <= line.Epoch || grant.OldHost != src.server || grant.NewHost != dst.server || grant.HeadGen != before.Gen || grant.RemoteLsn != before.Position { + t.Fatalf("grant %v not bound to HEAD %+v", grant, before) + } + if after := layoutHead(t, cluster, base, ref); after.Gen != before.Gen || after.Epoch != before.Epoch || after.ClaimID != before.ClaimID { + t.Fatalf("the grant itself changed HEAD: %+v -> %+v", before, after) + } + if kind == "forced" { + if grant.LostRange == nil || grant.LostRange.NewEpoch != grant.NewEpoch || grant.LostRange.OldEpoch != line.Epoch || grant.LostRange.LostAfterLsn != before.Position { + t.Fatalf("forced grant lost range %v; want after LSN %d, epochs %d -> %d", grant.LostRange, before.Position, line.Epoch, grant.NewEpoch) + } + lr, err := ws.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: "vol-a", RequestId: q.RequestId}) + if err != nil || len(lr.GetRanges()) != 1 || lr.GetRanges()[0].GetLostAfterLsn() != before.Position { + t.Fatalf("recorded lost range: %v %v", lr, err) + } + } else if grant.LostRange != nil { + t.Fatalf("clean grant carries a lost range %v", grant.LostRange) + } + + // The target claims HEAD at the new epoch and serves what was published. + dst.start(t, exe, h.Addr(), cluster.filerGRPC, base, layoutID) + leaseBinaryPoll(t, "target did not serve", func() bool { p, ok := dst.projection(); return ok && p.Healthy && p.Epoch == grant.NewEpoch }) + claimed := layoutHead(t, cluster, base, ref) + if claimed.Epoch != grant.NewEpoch || claimed.Holder != dst.server+"/r1" || claimed.State != layout.StateLive || claimed.ClaimID == "" || claimed.ClaimID == cut.ClaimID || claimed.Gen <= before.Gen { + t.Fatalf("HEAD after the target's start: %+v; want live, held by %s/r1 at epoch %d under a new claim", claimed, dst.server, grant.NewEpoch) + } + if eh, err := remote.GetHead(ctx); err != nil || eh.Epoch != grant.NewEpoch || eh.State != "active" || eh.DetachedBy != nil { + t.Fatalf("engine view of HEAD after the claim: %+v %v", eh, err) + } + tv := gap1ConnectNVMe(t, dst.nvme, dst.nqn) + tv.readExact(t, 8, want) + tv.readExact(t, 9, want) + tv.writeFlush(t, 11, want) + tv.readExact(t, 11, want) + tv.close() + t.Logf("%s move on the layout: claim %s@%d -> %s@%d, HEAD gen %d -> %d", kind, cut.ClaimID, line.Epoch, claimed.ClaimID, grant.NewEpoch, before.Gen, claimed.Gen) +} diff --git a/seaweed-block/cmd/blockvolume/workspace_layout_proof_test.go b/seaweed-block/cmd/blockvolume/workspace_layout_proof_test.go new file mode 100644 index 0000000000..0991ba9bf7 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/workspace_layout_proof_test.go @@ -0,0 +1,74 @@ +package main + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +type layoutProofStore struct { + h layout.Head + found bool + err error +} + +func (s layoutProofStore) ReadHead(context.Context) (layout.Head, bool, error) { + return s.h, s.found, s.err +} +func (s layoutProofStore) UpdateHead(context.Context, uint64, layout.Head, layout.HeadWriteCause) error { + return errors.New("proof must not write") +} + +func TestWorkspaceLayoutDetachedProof(t *testing.T) { + for _, tc := range []struct { + name string + mutate func(*layoutProofStore, *control.WorkspaceIdentity, *layout.HolderID) + want bool + }{ + {"exact", nil, true}, + {"absent", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.found = false }, false}, + {"unknown", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { + s.err = errors.New("read lost") + }, false}, + {"live", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { + s.h.State = layout.StateLive + }, false}, + {"deleting", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { + s.h.State = layout.StateDeleting + }, false}, + {"deleted", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { + s.h.State = layout.StateDeleted + }, false}, + {"open activity", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { + s.h.Activity = layout.Activity{Kind: layout.ActSnap, Session: "old"} + }, false}, + {"zero generation", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.Gen = 0 }, false}, + {"other claim", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.ClaimID = "other" }, false}, + {"older HEAD epoch", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.Epoch-- }, false}, + {"newer HEAD epoch", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.Epoch++ }, false}, + {"other HEAD holder", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.Holder = "other/r" }, false}, + {"zero request epoch", func(_ *layoutProofStore, id *control.WorkspaceIdentity, _ *layout.HolderID) { id.Epoch = 0 }, false}, + {"zero epoch everywhere", func(s *layoutProofStore, id *control.WorkspaceIdentity, me *layout.HolderID) { + s.h.Epoch, id.Epoch, me.Epoch = 0, 0, 0 + }, false}, + {"other request server", func(_ *layoutProofStore, id *control.WorkspaceIdentity, _ *layout.HolderID) { id.ServerId = "other" }, false}, + {"other request replica", func(_ *layoutProofStore, id *control.WorkspaceIdentity, _ *layout.HolderID) { id.ReplicaId = "other" }, false}, + {"empty local claim", func(_ *layoutProofStore, _ *control.WorkspaceIdentity, me *layout.HolderID) { me.ClaimID = "" }, false}, + } { + t.Run(tc.name, func(t *testing.T) { + me := layout.HolderID{Epoch: 2, Holder: "s/r", ClaimID: "k"} + id := &control.WorkspaceIdentity{VolumeId: "v", ServerId: "s", ReplicaId: "r", Epoch: 2} + st := layoutProofStore{h: layout.Head{Gen: 7, Epoch: 2, Holder: "s/r", ClaimID: "k", State: layout.StateDetached, Activity: layout.Activity{Kind: layout.ActIdle}}, found: true} + if tc.mutate != nil { + tc.mutate(&st, id, &me) + } + gen, err := workspaceLayoutDetachedGeneration(context.Background(), st, id, me) + if (err == nil) != tc.want || (tc.want && gen != 7) || (!tc.want && gen != 0) { + t.Fatalf("gen=%d err=%v", gen, err) + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/workspace_lease.go b/seaweed-block/cmd/blockvolume/workspace_lease.go new file mode 100644 index 0000000000..523417c5d0 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/workspace_lease.go @@ -0,0 +1,69 @@ +package main + +import ( + "context" + "fmt" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +type workspaceStopResult struct { + gen uint64 + err error +} +type workspaceStopRequest struct { + ctx context.Context + id *control.WorkspaceIdentity + reply chan workspaceStopResult +} + +// The lease worker requests closure; only run's owner closes the actual +// frontends, replication and provider. Signal cancellation suppresses ACK even +// when it races an already-requested revocation drain. +func startWorkspaceLease(ctx context.Context, h *volume.Host) (<-chan workspaceStopRequest, <-chan error) { + requests := make(chan workspaceStopRequest) + done := make(chan error, 1) + go func() { + done <- h.RunWorkspaceLease(ctx, func(stopCtx context.Context, id *control.WorkspaceIdentity) (uint64, error) { + req := workspaceStopRequest{ctx: stopCtx, id: id, reply: make(chan workspaceStopResult, 1)} + select { + case requests <- req: + case <-ctx.Done(): + return 0, ctx.Err() + case <-stopCtx.Done(): + return 0, stopCtx.Err() + } + select { + case result := <-req.reply: + return result.gen, result.err + case <-ctx.Done(): + return 0, ctx.Err() + case <-stopCtx.Done(): + return 0, stopCtx.Err() + } + }) + }() + return requests, done +} + +// workspaceLayoutDetachedGeneration accepts only the attached Start identity's +// exact detached HEAD. Missing, foreign or unknown evidence never yields ACK. +// The returned generation is diagnostic readout, not the clean-move identity: +// the master reads this detached epoch/holder/position when recording the ACK. +func workspaceLayoutDetachedGeneration(ctx context.Context, st layout.HeadStore, id *control.WorkspaceIdentity, me layout.HolderID) (uint64, error) { + if id == nil || me.Epoch == 0 || id.Epoch != me.Epoch || me.Holder == "" || id.ServerId+"/"+id.ReplicaId != me.Holder || me.ClaimID == "" { + return 0, layout.ErrNotHolder + } + h, found, err := st.ReadHead(ctx) + if err != nil { + return 0, err + } + if !found { + return 0, layout.ErrHeadAbsent + } + if !layout.DetachedBy(h, me) { + return 0, fmt.Errorf("workspace: no detached proof for the attached claim") + } + return h.Gen, nil +} diff --git a/seaweed-block/cmd/blockvolume/workspace_lease_binary_test.go b/seaweed-block/cmd/blockvolume/workspace_lease_binary_test.go new file mode 100644 index 0000000000..f149c18968 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/workspace_lease_binary_test.go @@ -0,0 +1,319 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + master "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "io" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "syscall" + "testing" + "time" +) + +func leaseBinaryAddress(t *testing.T) string { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := ln.Addr().String() + ln.Close() + return addr +} +func leaseBinaryPoll(t *testing.T, what string, fn func() bool) { + t.Helper() + end := time.Now().Add(30 * time.Second) + for !fn() { + if time.Now().After(end) { + t.Fatal(what) + } + time.Sleep(20 * time.Millisecond) + } +} +func leaseBinaryPost(addr, op string) (int, []byte, error) { + c := &http.Client{Timeout: 5 * time.Second} + resp, err := c.Post("http://"+addr+"/chunk/"+op, "application/json", bytes.NewBufferString(`{"volumeID":"vol-a","timeoutMs":3000}`)) + if err != nil { + return 0, nil, err + } + defer resp.Body.Close() + b, err := io.ReadAll(io.LimitReader(resp.Body, 65536)) + return resp.StatusCode, b, err +} + +// blockvolumeUnderTest is the blockvolume a test starts: a gate run's +// prebuilt, hashed binary (SWBLOCK_TEST_BINS), or a race-enabled build for a +// local run. +func blockvolumeUnderTest(t *testing.T) string { + t.Helper() + if d := os.Getenv("SWBLOCK_TEST_BINS"); d != "" { + exe := filepath.Join(d, "blockvolume") + if _, err := os.Stat(exe); err != nil { + t.Fatalf("SWBLOCK_TEST_BINS has no blockvolume: %v", err) + } + return exe + } + exe := filepath.Join(t.TempDir(), "blockvolume") + if out, err := exec.Command("go", "build", "-race", "-p", "4", "-o", exe, ".").CombinedOutput(); err != nil { + t.Fatalf("build: %v %s", err, out) + } + return exe +} + +// runProductLoop runs h's lifecycle product loop for the rest of the test, +// as blockmaster runs it (--lifecycle-product-loop-interval). The early-line +// control (SWBLOCK_TEST_EARLY_LINE=1) runs without it, as the fixture did +// before: a running loop could bind after the holder reported and mask it. +func runProductLoop(t *testing.T, h *master.Host) { + t.Helper() + if os.Getenv("SWBLOCK_TEST_EARLY_LINE") == "1" { + return + } + stop, done := make(chan struct{}), make(chan struct{}) + go func() { + defer close(done) + tick := time.NewTicker(100 * time.Millisecond) + defer tick.Stop() + for { + select { + case <-stop: + return + case <-tick.C: + _, _ = h.RunLifecycleProductTick() + } + } + }() + t.Cleanup(func() { close(stop); <-done }) +} + +// A primary line is issued for the process at its endpoints: the bind +// records the process the holder reports, and the holder (blockvolume sets +// LinesNameTheirProcess) refuses a line that names no process. So, as in +// production, the first line is minted only after the holder process has +// reported its slot: tickAfterProcessReports waits for that report, then +// runs the product tick that binds. +// +// SWBLOCK_TEST_EARLY_LINE=1 is the control, the order the fixture used +// before: earlyLineControl mints the line from a hand-ingested observation +// before the holder starts, and no product tick runs after the holder +// starts. The line names no process, the holder refuses it and never +// serves. A tick after the holder reported would re-issue the line for its +// process (an unbound placement goes through the controller, which +// refreshes on a process change), so the control runs none. +func earlyLineControl(t *testing.T, h *master.Host, server, volume, replica, data, ctrl string) { + t.Helper() + if os.Getenv("SWBLOCK_TEST_EARLY_LINE") != "1" { + return + } + if err := h.ObservationHost().Ingest(authority.Observation{ServerID: server, ObservedAt: time.Now().UTC(), + Slots: []authority.SlotFact{{VolumeID: volume, ReplicaID: replica, DataAddr: data, CtrlAddr: ctrl}}}); err != nil { + t.Fatal(err) + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + leaseBinaryPoll(t, "control: no early line", func() bool { line, ok := h.Publisher().VolumeAuthorityLine(volume); return ok && line.Epoch > 0 }) + if line, _ := h.Publisher().VolumeAuthorityLine(volume); line.Incarnation != "" { + t.Fatalf("control: want an early line that names no process, have %+v", line) + } +} + +func tickAfterProcessReports(t *testing.T, h *master.Host, server, volume, replica string) { + t.Helper() + if os.Getenv("SWBLOCK_TEST_EARLY_LINE") == "1" { + return + } + leaseBinaryPoll(t, "the holder never reported its process", func() bool { + s, ok := h.ObservationHost().Store().SlotFactOnServer(server, volume, replica) + return ok && s.Incarnation != "" + }) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + leaseBinaryPoll(t, "no initial authority", func() bool { line, ok := h.Publisher().VolumeAuthorityLine(volume); return ok && line.Epoch > 0 }) +} + +func TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown(t *testing.T) { + if os.Getenv("CHUNKSTORE_WEED") == "" { + t.Skip("CHUNKSTORE_WEED not set") + } + exe := blockvolumeUnderTest(t) + cluster := startWorkspaceWeed(t) + for _, enabled := range []bool{false, true} { + t.Run(fmt.Sprintf("workspace-rpc-%v", enabled), func(t *testing.T) { + base := fmt.Sprintf("/workspace-lease-%d", time.Now().UnixNano()) + cl := cluster.client(t, base) + headCat, err := chunkstore.NewBCatalog(cl, cl, base) + if err != nil { + t.Fatal(err) + } + var h *master.Host + reader, err := master.NewLayoutWorkspaceHEADReader(headCat, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) { + return h.WorkspaceLayoutVolume(ctx, name) + }) + if err != nil { + t.Fatal(err) + } + h, err = master.New(master.Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: enabled, LifecycleProductLoop: true, WorkspaceHeadReader: reader, + LayoutCreateVolume: layoutMasterWriter(t, cluster, base)}) + if err != nil { + t.Fatal(err) + } + h.Start() + t.Cleanup(func() { + ctx, c := context.WithTimeout(context.Background(), 5*time.Second) + defer c() + _ = h.Close(ctx) + }) + runProductLoop(t, h) + dataAddr, ctrlAddr, statusAddr, nvmeAddr := leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t) + // The master's create writes VOLUME and the unclaimed HEAD, then + // marks the record store-ready; only a store-ready volume gets a placement. + layoutID := createStoreReadyVolume(t, h, "vol-a", 64*4096) + if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-a", DataAddr: dataAddr, CtrlAddr: ctrlAddr}); err != nil { + t.Fatal(err) + } + if _, err = h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "vol-a", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: "vol-a", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { + t.Fatal(err) + } + earlyLineControl(t, h, "node-a", "vol-a", "r1", dataAddr, ctrlAddr) + logPath := filepath.Join(t.TempDir(), "volume.log") + log, err := os.Create(logPath) + if err != nil { + t.Fatal(err) + } + cmd := exec.Command(exe, "--master", h.Addr(), "--server-id", "node-a", "--volume-id", "vol-a", "--replica-id", "r1", "--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--t1-readiness", "--status-addr", statusAddr, "--durable-root", t.TempDir(), "--layout-id", layoutID.String(), "--volume-lock-dir-test-only", t.TempDir(), "--durable-impl", "walstore-chunk", "--durable-blocks", "64", "--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease", "--nvme-listen", nvmeAddr, "--nvme-subsysnqn", "nqn.2026-11.test:workspace-lease") + stripSystemdForTestLockDir(cmd) + cmd.Stdout, cmd.Stderr = log, log + if err = cmd.Start(); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { done <- cmd.Wait() }() + exited := false + t.Cleanup(func() { + if !exited { + _ = cmd.Process.Kill() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("binary did not exit after kill") + } + } + log.Close() + if t.Failed() { + b, _ := os.ReadFile(logPath) + if len(b) > 14000 { + b = b[len(b)-14000:] + } + t.Logf("volume log: %s", b) + } + }) + tickAfterProcessReports(t, h, "node-a", "vol-a", "r1") + line, _ := h.Publisher().VolumeAuthorityLine("vol-a") + client := &http.Client{Timeout: time.Second} + projection := func() (frontend.Projection, bool) { + resp, e := client.Get("http://" + statusAddr + "/status?volume=vol-a") + if e != nil { + return frontend.Projection{}, false + } + defer resp.Body.Close() + var p frontend.Projection + e = json.NewDecoder(resp.Body).Decode(&p) + return p, e == nil + } + remote := cluster.remote(t, base, chunkstore.VolumeRef{Name: "vol-a", ID: layoutID}) + if !enabled { + leaseBinaryPoll(t, "unleased host did not adopt assignment", func() bool { p, ok := projection(); return ok && p.Epoch == line.Epoch }) + // Exercise an actual cut request, not just the status presentation. + code, b, e := leaseBinaryPost(statusAddr, "cut") + if e != nil || code >= 200 && code < 300 { + t.Fatalf("unleased cut: %d %s %v", code, b, e) + } + if p, ok := projection(); !ok || p.Healthy { + t.Fatal("disabled WorkspaceRPC served", p, ok) + } + if state := h.Publisher().WorkspaceState("vol-a"); state != nil { + t.Fatal("disabled RPC enrolled a lease", state) + } + _ = cmd.Process.Signal(syscall.SIGTERM) + } else { + leaseBinaryPoll(t, "valid lease did not admit binary", func() bool { p, ok := projection(); return ok && p.Healthy }) + // Actual provider/filer cut and canonical Detach happen before Revoke. + leaseBinaryPoll(t, "provider was not operational", func() bool { code, _, e := leaseBinaryPost(statusAddr, "cut"); return e == nil && code == 200 }) + code, b, e := leaseBinaryPost(statusAddr, "detach") + if e != nil || code != 200 { + t.Fatalf("detach: %d %s %v", code, b, e) + } + detached, e := remote.GetHead(context.Background()) + if e != nil || detached.State != "detached" || detached.DetachedBy == nil { + t.Fatal(detached, e) + } + conn, e := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if e != nil { + t.Fatal(e) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + _, e = control.NewWorkspaceServiceClient(conn).RevokeWorkspace(ctx, &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: "r1", Epoch: line.Epoch}) + cancel() + if e != nil { + t.Fatal(e) + } + leaseBinaryPoll(t, "binary did not ACK its own drained shutdown", func() bool { s := h.Publisher().WorkspaceState("vol-a"); return s != nil && s.Ack != nil }) + state := h.Publisher().WorkspaceState("vol-a") + if state.Ack.HeadGen != detached.Gen { + t.Fatal("ACK differs from stored detached HEAD", state, detached) + } + current, e := remote.GetHead(context.Background()) + if e != nil || current.Gen != detached.Gen { + t.Fatal("revoke performed a forbidden extra cut", current, e) + } + } + select { + case err := <-done: + exited = true + if err != nil { + t.Fatal("binary exit", err) + } + case <-time.After(8 * time.Second): + t.Fatal("binary did not finish shutdown") + } + if c, e := net.DialTimeout("tcp", nvmeAddr, 200*time.Millisecond); e == nil { + c.Close() + t.Fatal("NVMe frontend still accepts after shutdown") + } + if !enabled { + // No claim was ever made: HEAD is absent, or the unclaimed + // HEAD the create wrote (no holder, epoch 0). + cl := cluster.client(t, base) + cat, e := chunkstore.NewBCatalog(cl, cl, base) + if e != nil { + t.Fatal(e) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + head, found, e := cat.ReadHead(ctx, chunkstore.VolumeRef{Name: "vol-a", ID: layoutID}) + cancel() + if e != nil || found && (head.Holder != "" || head.Epoch != 0 || head.ClaimID != "") { + t.Fatal("unleased binary changed HEAD", head, found, e) + } + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/workspace_weed_fresh_ports_integration_test.go b/seaweed-block/cmd/blockvolume/workspace_weed_fresh_ports_integration_test.go new file mode 100644 index 0000000000..20f868385d --- /dev/null +++ b/seaweed-block/cmd/blockvolume/workspace_weed_fresh_ports_integration_test.go @@ -0,0 +1,146 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "context" + "fmt" + "net" + "net/http" + "path/filepath" + "strings" + "testing" + "time" +) + +// A weed start whose volume server's gRPC port is held by another process +// (here a plain HTTP server, as a concurrent job's listener on a shared +// runner) never accepts a write: the master's volume allocation gets an +// HTTP 404. The start is discarded and the cluster is started again on fresh +// ports, and that one accepts writes. +func TestWeedStartAgainOnFreshPortsWhenAPortIsTaken(t *testing.T) { + if testing.Short() { + t.Skip("starts weed twice") + } + pick := w4PickPortPair + t.Cleanup(func() { w4PickPortPair = pick }) + taken := 0 + w4PickPortPair = func(t *testing.T, used map[int]bool, role string) int { + p := w4FreePortPair(t, used) + if role == "volume" && taken == 0 { + taken = p + ln, err := net.Listen("tcp", fmt.Sprintf("%s:%d", testListenHost(), p+10000)) + if err != nil { + t.Fatal(err) + } + srv := &http.Server{Handler: http.NotFoundHandler()} + go func() { _ = srv.Serve(ln) }() + t.Cleanup(func() { _ = srv.Close() }) + } + return p + } + start := time.Now() + c := startWorkspaceWeed(t) + if taken == 0 { + t.Fatal("the first start did not pick a volume pair") + } + cl := c.client(t, "/swblock/vols/fresh-ports") + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := cl.Put(ctx, []byte("after the second start")); err != nil { + t.Fatalf("the cluster started again on fresh ports does not accept a write: %v", err) + } + if c.master == "" || c.dir == "" { + t.Fatal("no cluster") + } + t.Logf("volume port %d's gRPC port %d was taken; the second start accepted writes after %v", taken, taken+10000, time.Since(start).Round(time.Second)) +} + +// A weed start whose master gRPC port is held by another process (a plain +// HTTP server, as on the self-hosted runner) never brings up its filer: the +// filer cannot reach the master, and its gRPC port never listens. That +// start is discarded too, and the cluster is started again on fresh ports. +func TestWeedStartAgainOnFreshPortsWhenAServerNeverListens(t *testing.T) { + if testing.Short() { + t.Skip("starts weed twice") + } + pick := w4PickPortPair + t.Cleanup(func() { w4PickPortPair = pick }) + taken := 0 + w4PickPortPair = func(t *testing.T, used map[int]bool, role string) int { + p := w4FreePortPair(t, used) + if role == "master" && taken == 0 { + taken = p + ln, err := net.Listen("tcp", fmt.Sprintf("%s:%d", testListenHost(), p+10000)) + if err != nil { + t.Fatal(err) + } + srv := &http.Server{Handler: http.NotFoundHandler()} + go func() { _ = srv.Serve(ln) }() + t.Cleanup(func() { _ = srv.Close() }) + } + return p + } + start := time.Now() + c := startWorkspaceWeed(t) + if taken == 0 { + t.Fatal("the first start did not pick a master pair") + } + if c.master == fmt.Sprintf("%s:%d", testListenHost(), taken) { + t.Fatalf("the cluster kept the master port %d whose gRPC port was taken", taken) + } + cl := c.client(t, "/swblock/vols/fresh-ports-master") + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := cl.Put(ctx, []byte("after the second start")); err != nil { + t.Fatalf("the cluster started again on fresh ports does not accept a write: %v", err) + } + t.Logf("master port %d's gRPC port %d was taken; the second start accepted writes after %v", taken, taken+10000, time.Since(start).Round(time.Second)) +} + +// The filer's ports are picked only after the master is up, so a listener +// that appears on the host while the master starts (another job's weed, as +// on the self-hosted runner) cannot hold the port the filer will bind: here +// the hook takes the filer's gRPC port if it was already picked when the +// master started. The cluster must come up on its first start. +func TestWeedPicksTheFilerPortsAfterTheMasterStarts(t *testing.T) { + if testing.Short() { + t.Skip("starts weed") + } + pick, started := w4PickPortPair, w4ServerStarted + t.Cleanup(func() { w4PickPortPair, w4ServerStarted = pick, started }) + picked := map[string]int{} + w4PickPortPair = func(t *testing.T, used map[int]bool, role string) int { + p := w4FreePortPair(t, used) + picked[role] = p + return p + } + taken := 0 + w4ServerStarted = func(role string) { + fp, ok := picked["filer"] + if role != "master" || !ok || taken != 0 { + return + } + taken = fp + 10000 + ln, err := net.Listen("tcp", fmt.Sprintf("%s:%d", testListenHost(), taken)) + if err != nil { + t.Fatal(err) + } + srv := &http.Server{Handler: http.NotFoundHandler()} + go func() { _ = srv.Serve(ln) }() + t.Cleanup(func() { _ = srv.Close() }) + } + c := startWorkspaceWeed(t) + if taken != 0 { + t.Errorf("the filer's gRPC port %d was picked before the master started and was taken meanwhile", taken) + } + if strings.HasPrefix(filepath.Base(c.dir), "start-") { + t.Errorf("the cluster came up only on a later start (%s)", c.dir) + } + cl := c.client(t, "/swblock/vols/pick-at-start") + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := cl.Put(ctx, []byte("first start")); err != nil { + t.Fatalf("the cluster does not accept a write: %v", err) + } +} diff --git a/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go b/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go new file mode 100644 index 0000000000..51bdcdaffe --- /dev/null +++ b/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go @@ -0,0 +1,385 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +// The process helper follows the existing chunkstore integration harness. +// Only real loopback SeaweedFS processes and per-test temporary state are used. +import ( + "context" + "fmt" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "math" + "math/rand" + "net" + "os" + "os/exec" + "path/filepath" + "sync" + "testing" + "time" +) + +type w4WeedCluster struct { + master, filerHTTP, filerGRPC string + dir string + weed string + procs map[string]*w4WeedProc + reported sync.Once // its one failure report (registerWeedReport) + discarded bool // a failed start attempt, already reported +} + +// testListenHost is the address the test harness binds and advertises for +// its weed cluster, blockmaster and blockvolume ports: 127.0.0.1 unless +// SWBLOCK_TEST_LISTEN_HOST names another (a lab run whose processes span two +// hosts). Unset, every test behaves exactly as before. +func testListenHost() string { + if h := os.Getenv("SWBLOCK_TEST_LISTEN_HOST"); h != "" { + return h + } + return "127.0.0.1" +} + +// ephemeralPorts is the host's range for outgoing connections' source ports +// (Linux ip_local_port_range; the Linux default when unreadable). A port in it +// can be taken by any outgoing connection between the free check and weed's +// bind, so a port pair never uses it. +func ephemeralPorts() (int, int) { + lo, hi := 32768, 60999 + if b, err := os.ReadFile("/proc/sys/net/ipv4/ip_local_port_range"); err == nil { + var a, z int + if n, _ := fmt.Sscan(string(b), &a, &z); n == 2 && a > 0 && z >= a { + lo, hi = a, z + } + } + return lo, hi +} + +func w4FreePortPair(t *testing.T, used map[int]bool) int { + t.Helper() + lo, hi := ephemeralPorts() + // A CI shard draws its HTTP ports from its own slice of weedPairRange; + // their gRPC ports (+10000) then never meet another shard's. + sLo, sHi := testPortSpan(weedPairRange(lo)) + for i := 0; i < 200; i++ { + p := sLo + rand.Intn(sHi-sLo) + if used[p] || used[p+10000] { + continue + } + if (p >= lo && p <= hi) || (p+10000 >= lo && p+10000 <= hi) { + continue + } + if !claimHostPort(p) || !claimHostPort(p+10000) { + continue + } + ok := true + for _, q := range []int{p, p + 10000} { + l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", testListenHost(), q)) + if err != nil { + ok = false + break + } + l.Close() + } + if ok { + used[p], used[p+10000] = true, true + return p + } + } + t.Fatal("no free port pair") + return 0 +} + +func w4WaitTCP(t *testing.T, addr string, d time.Duration) { + t.Helper() + if err := w4ListeningWithin(addr, d); err != nil { + t.Fatal(err) + } +} + +// w4ListeningWithin waits until addr accepts a TCP connection. +func w4ListeningWithin(addr string, d time.Duration) error { + deadline := time.Now().Add(d) + for time.Now().Before(deadline) { + if c, err := net.DialTimeout("tcp", addr, 200*time.Millisecond); err == nil { + c.Close() + return nil + } + time.Sleep(100 * time.Millisecond) + } + return fmt.Errorf("%s not listening after %v", addr, d) +} + +// w4PickPortPair picks each weed server's port pair (HTTP p, gRPC p+10000); +// a test replaces it to make a start collide with another listener. +var w4PickPortPair = func(t *testing.T, used map[int]bool, _ string) int { return w4FreePortPair(t, used) } + +func startWorkspaceWeed(t *testing.T) *w4WeedCluster { + t.Helper() + return startWorkspaceWeedAt(t, t.TempDir()) +} + +// A caller-owned root lets process qualification retain its filer evidence +// when external-service cleanup is uncertain. Existing tests keep TempDir. +func startWorkspaceWeedAt(t *testing.T, dir string) *w4WeedCluster { + t.Helper() + return startWorkspaceWeedWith(t, dir, w4WeedOpts{VolumeSizeLimitMB: 256, VolumeMax: 32}) +} + +// w4WeedOpts sizes the weed volume server: VolumeMax volumes of +// VolumeSizeLimitMB each (the default holds about 8 GiB of chunks). +type w4WeedOpts struct { + VolumeSizeLimitMB, VolumeMax int + // A fault-injection front keeps the advertised filer endpoint unchanged. + // The one real filer binds a private loopback address; no second filer is registered. + FilerBind string + FilerFront func(*w4WeedCluster) +} + +// weedStarts is how many times a cluster that does not start (a server +// never listens, or the cluster never accepts a write) is started again on +// fresh ports. A port pair is checked free and then released before weed +// binds it; another process on the host (a concurrent job on a shared +// runner) can take it in between, and a server then cannot reach another's +// gRPC port. Each server's pair is picked just before that server starts, +// which keeps that window short. +var weedStarts = 3 + +// w4ServerStarted, when set, runs after each weed server of a start is +// launched (role "master", "volume", "filer"); a test uses it to act +// between two servers' starts. +var w4ServerStarted func(role string) + +func startWorkspaceWeedWith(t *testing.T, dir string, o w4WeedOpts) *w4WeedCluster { + t.Helper() + weed := os.Getenv("CHUNKSTORE_WEED") + if weed == "" { + t.Skip("CHUNKSTORE_WEED not set") + } + // A fault-injection front is built again for each start, on that + // start's ports (o.FilerFront runs once the filer listens). + starts := weedStarts + for attempt := 1; ; attempt++ { + at := dir + if attempt > 1 { + at = filepath.Join(dir, fmt.Sprintf("start-%d", attempt)) + } + c, err := startWorkspaceWeedOnce(t, at, weed, o) + if err == nil { + return c + } + // The evidence is taken now, before the servers are stopped. + if attempt >= starts { + t.Fatal(weedStartFailure(attempt, starts, err, c.servers())) + } + t.Logf("master %s, filer %s; starting again on fresh ports: %s", c.master, c.filerGRPC, weedStartFailure(attempt, starts, err, c.servers())) + c.discard(t) + } +} + +// discard stops a cluster that failed its start and logs each process's +// log tail; its own cleanups then find the processes already gone. +func (c *w4WeedCluster) discard(t *testing.T) { + t.Helper() + c.discarded = true + for name, p := range c.procs { + if !c.stopProcWithin(name, 5*time.Second) { + t.Errorf("weed %s did not exit after kill", name) + } + b, _ := os.ReadFile(p.log.Name()) + if len(b) > 4000 { + b = b[len(b)-4000:] + } + t.Logf("---- discarded start: %s log tail ----\n%s", name, b) + } +} + +// startWorkspaceWeedOnce starts one cluster on freshly checked ports in dir +// and returns an error when a server never listens or the cluster never +// accepts a write. +func startWorkspaceWeedOnce(t *testing.T, dir, weed string, o w4WeedOpts) (*w4WeedCluster, error) { + t.Helper() + if err := os.MkdirAll(dir, 0700); err != nil { + t.Fatal(err) + } + used := map[int]bool{} + mp := w4PickPortPair(t, used, "master") + c := &w4WeedCluster{ + master: fmt.Sprintf("%s:%d", testListenHost(), mp), + dir: dir, + weed: weed, + } + c.procs = map[string]*w4WeedProc{} + run := func(name string, args ...string) { + c.startProc(t, name, args...) + if w4ServerStarted != nil { + defer w4ServerStarted(name) + } + t.Cleanup(func() { + p := c.procs[name] + if !c.stopProcWithin(name, 5*time.Second) { + t.Errorf("weed %s did not exit after kill", name) + } + p.log.Close() + if t.Failed() { + b, _ := os.ReadFile(p.log.Name()) + if len(b) > 4000 { + b = b[len(b)-4000:] + } + t.Logf("---- %s log tail ----\n%s", name, b) + } + }) + registerWeedReport(t, &c.reported, func() bool { return c.discarded }, c.servers) + } + for _, d := range []string{"m", "v", "f"} { + if err := os.MkdirAll(filepath.Join(dir, d), 0o755); err != nil { + t.Fatal(err) + } + } + run("master", "master", "-ip="+testListenHost(), fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), fmt.Sprintf("-volumeSizeLimitMB=%d", o.VolumeSizeLimitMB), "-defaultReplication=000") + if err := w4ListeningWithin(c.master, 20*time.Second); err != nil { + return c, err + } + vp := w4PickPortPair(t, used, "volume") + run("volume", "volume", "-ip="+testListenHost(), fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, fmt.Sprintf("-max=%d", o.VolumeMax)) + fp := w4PickPortPair(t, used, "filer") + c.filerHTTP = fmt.Sprintf("%s:%d", testListenHost(), fp) + c.filerGRPC = fmt.Sprintf("%s:%d", testListenHost(), fp+10000) + filerArgs := []string{"filer", "-ip=" + testListenHost(), fmt.Sprintf("-port=%d", fp), "-master=" + c.master, "-defaultStoreDir=" + filepath.Join(dir, "f")} + if o.FilerBind != "" { + filerArgs = append(filerArgs, "-ip.bind="+o.FilerBind) + c.filerHTTP = net.JoinHostPort(o.FilerBind, fmt.Sprint(fp)) + c.filerGRPC = net.JoinHostPort(o.FilerBind, fmt.Sprint(fp+10000)) + } + run("filer", filerArgs...) + if err := w4ListeningWithin(c.filerGRPC, 30*time.Second); err != nil { + return c, err + } + if o.FilerFront != nil { + o.FilerFront(c) + } + + // Wait until an assign succeeds (volume registered, volumes growable). + cl := c.client(t, "/swblock/vols/probe") + deadline := time.Now().Add(60 * time.Second) + for { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + _, err := cl.Put(ctx, []byte("probe")) + cancel() + if err == nil { + break + } + if time.Now().After(deadline) { + return c, err + } + time.Sleep(500 * time.Millisecond) + } + return c, nil +} + +// w4WeedProc is one weed process; a restart replaces it under the same name, +// arguments and log, so the cluster's cleanup always ends the current one. +type w4WeedProc struct { + args []string + log *os.File + cmd *exec.Cmd + done chan struct{} + exit *error // this start's exit status, set before done closes (a fresh one per start) +} + +func (c *w4WeedCluster) startProc(t *testing.T, name string, args ...string) { + t.Helper() + p := c.procs[name] + if p == nil { + logf, err := os.Create(filepath.Join(c.dir, name+".log")) + if err != nil { + t.Fatal(err) + } + p = &w4WeedProc{args: args, log: logf} + c.procs[name] = p + } + cmd := exec.Command(c.weed, p.args...) + cmd.Stdout, cmd.Stderr = p.log, p.log + cmd.Dir = c.dir + if err := cmd.Start(); err != nil { + t.Fatalf("start %s: %v", name, err) + } + p.cmd, p.done, p.exit = cmd, make(chan struct{}), new(error) + go func(done chan struct{}, exit *error) { *exit = cmd.Wait(); close(done) }(p.done, p.exit) +} + +// servers is the cluster's servers for weedState and weedFailureReport. +func (c *w4WeedCluster) servers() []weedServer { + out := make([]weedServer, 0, len(c.procs)) + for name, p := range c.procs { + s := weedServer{name: name, log: p.log.Name()} + if p.done == nil { // its launch failed: it never ran + s.exited, s.err = true, fmt.Errorf("not started") + out = append(out, s) + continue + } + select { + case <-p.done: + s.exited, s.err = true, *p.exit + default: + } + out = append(out, s) + } + return out +} + +// stopProcWithin kills name's current process and reports whether it exited. +func (c *w4WeedCluster) stopProcWithin(name string, d time.Duration) bool { + p := c.procs[name] + if p == nil || p.cmd == nil { + return true + } + _ = p.cmd.Process.Kill() + select { + case <-p.done: + return true + case <-time.After(d): + return false + } +} + +// stopProc and restartProc take one weed process (master, volume, filer) down +// and bring it back with the same ports and data directory. +func (c *w4WeedCluster) stopProc(t *testing.T, name string) { + t.Helper() + if !c.stopProcWithin(name, 10*time.Second) { + t.Fatalf("weed %s did not exit after kill", name) + } +} + +func (c *w4WeedCluster) restartProc(t *testing.T, name string) { + t.Helper() + c.startProc(t, name) +} + +func (c *w4WeedCluster) client(t *testing.T, assignPath string) *chunkstore.SWFS { + t.Helper() + cl, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{FilerGRPC: c.filerGRPC, Collection: "swblock", AssignPath: assignPath}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = cl.Close() }) + return cl +} + +// remote reads ref's HEAD under base as the chunk engine sees it, through the +// layout remote of an observer that holds nothing: its epoch, holder and +// claim match no HEAD, so it never rolls a session back or writes. +func (c *w4WeedCluster) remote(t *testing.T, base string, ref chunkstore.VolumeRef) *chunkstore.LayoutRemote { + t.Helper() + cl := c.client(t, base) + cat, err := chunkstore.NewBCatalog(cl, cl, base) + if err != nil { + t.Fatal(err) + } + r, err := chunkstore.NewLayoutRemote(cat, ref, layout.HolderID{Epoch: math.MaxUint64, Holder: "test-observer", ClaimID: "observer"}) + if err != nil { + t.Fatal(err) + } + return r +} diff --git a/seaweed-block/cmd/blockvolume/wrong_geometry_cure_integration_test.go b/seaweed-block/cmd/blockvolume/wrong_geometry_cure_integration_test.go new file mode 100644 index 0000000000..f349664e1a --- /dev/null +++ b/seaweed-block/cmd/blockvolume/wrong_geometry_cure_integration_test.go @@ -0,0 +1,171 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +// The operations-guide cure for a local store of the wrong size left by a +// 1.0 start with the wrong --durable-blocks (from 1.0.1 such a start is +// refused before any store exists), run as written, in one sitting. The +// setup plants that store: testdata/onezero-wrong-geometry-store.txt holds, +// as readable text, the four files a 3402e0dd (1.0 RC) run left under v2's +// --durable-root +// (65536-block record, --durable-blocks 32768). A start with the right flags +// still fails geometry_mismatch at attach and never serves. The process is +// stopped; then the guard: `sw-block ops chunk show` must print the HEAD with +// epoch 0, no holder and state active (the volume never served, so its local +// files hold no acknowledged write); then the four named files are removed +// from --durable-root and a start with the right flags serves. Afterwards the +// same command shows a claimed HEAD (epoch >= 1, a holder): the guard now +// forbids removing those files. +func TestWrongGeometryCureAsWritten(t *testing.T) { + env := startSourceWithSnapshot(t, "v2") + env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2", + "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + plantStore(t, filepath.Join("testdata", "onezero-wrong-geometry-store.txt"), env.hosts["n-v2"].root) + // The planted files are byte for byte the captured ones. + for name, want := range map[string]string{ + "v2.bin": "e9941d515c8b295dc860df1f3c89a4b36c3cc7d372334aa14527da9928b3de7e", + "v2.bin.chunkfresh": "02db0d2659c9d48bc15f81a388594fc0e3cf4c780fdc27ea21e0671afc37de19", + "v2.bin.chunkmap": "ac6dba36a1b8bb106aaf9f10dda148818b5cf0b545cdf7fe92fa5c8ce52df4fc", + "v2.replica-floor": "40ee91af4b55571765a602664a45913101254ccd16974ed3d01fbb8c7efa60e3", + } { + data, err := os.ReadFile(filepath.Join(env.hosts["n-v2"].root, name)) + if err != nil { + t.Fatal(err) + } + if got := fmt.Sprintf("%x", sha256.Sum256(data)); got != want { + t.Fatalf("planted %s: sha256 %s, captured %s", name, got, want) + } + } + stuck := env.h.start(t, "blockvolume-v2-right-flags-on-the-1.0-store", env.h.volume, env.volArgsFor(env.hosts["n-v2"])...) + err := stuck.wait(90 * time.Second) // stopped (under systemd: systemctl stop) + t.Logf("right flags on the 1.0 store: exit %v; %q; %q", err, stuck.line("geometry_mismatch"), stuck.line("exiting status=")) + // The attach check refuses it (the store has its own geometry) and the + // process exits 75 after its retries; the pre-store flag check (exit + // 78) does not apply to an existing store. Over its whole life it never + // started a frontend (no *-listening or ublk-ready phase line). + mismatch := stuck.line("chunk attach check") + served := stuck.has(`"phase":"nvme-listening"`) || stuck.has(`"phase":"iscsi-listening"`) || stuck.has(`"phase":"ublk-ready"`) + if exitCode(err) != 75 || !strings.Contains(mismatch, "geometry_mismatch") || !strings.Contains(mismatch, "VOLUME geometry") || served { + t.Fatalf("setup: the right flags on the 1.0 store must fail the attach check with geometry_mismatch, exit 75, and never serve; exit %v, attach line %q, served %v", err, mismatch, served) + } + b := env.hosts["n-v2"] + guard := env.headOf(t, "v2") + t.Logf("guard: sw-block ops chunk show --volume v2: %s", guard) + if !strings.Contains(guard, `"epoch":0,"holder":""`) || !strings.Contains(guard, `"state":"active"`) { + t.Fatalf("the guard does not show a never-claimed HEAD: %s", guard) + } + for _, name := range []string{"v2.bin", "v2.bin.chunkfresh", "v2.bin.chunkmap", "v2.replica-floor"} { + if err := os.Remove(filepath.Join(b.root, name)); err != nil { + t.Fatalf("remove %s: %v", name, err) + } + } + t.Logf("left under --durable-root after the removal:\n%s", listTree(b.root)) + d := env.startTarget(t, "v2", "blockvolume-v2-cured") + defer d.kill(t) + after := env.headOf(t, "v2") + t.Logf("after the cure: %s", after) + if strings.Contains(after, `"epoch":0`) || strings.Contains(after, `"holder":""`) { + t.Fatalf("a served volume's HEAD must show a claim (the guard then forbids removal): %s", after) + } +} + +// startSourceWithSnapshot starts v1 on s1 with one written block and its +// snapshot s1; the targets are restore targets of it, none started. +func startSourceWithSnapshot(t *testing.T, targets ...string) *handoffEnv { + env := startHandoffEnvWith(t, 1, targets) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + holder := env.start(t, "blockvolume-v1", "s1") + env.adopt(t, holder, "s1") + env.writeBlock(t, "s1", 0, cutCrashBlock('A', 0)) + env.snapshot(t, "s1", "v1", "s1") + return env +} + +// headOf is the first line of `sw-block ops chunk show --volume v`. +func (env *handoffEnv) headOf(t *testing.T, v string) string { + t.Helper() + out, _ := env.h.command(t, "ops", "chunk", "show", "--master", env.h.masterAddr, "--volume", v, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath) + head, err := handoffHeadJSON(out) + if err != nil { + t.Fatalf("show HEAD for %s: %v\n%s", v, err, out) + } + return head +} + +func listTree(root string) string { + var sb strings.Builder + _ = filepath.Walk(root, func(p string, info os.FileInfo, err error) error { + if err == nil { + fmt.Fprintf(&sb, " %s %d\n", strings.TrimPrefix(p, root), info.Size()) + } + return nil + }) + return sb.String() +} + +// plantStore writes the files a text fixture describes into root: each +// "file " line starts a file of that size (all +// zero, sparse where the file system allows), and each " " line +// after it sets those bytes. Lines starting with # are comments. +func plantStore(t *testing.T, fixture, root string) { + t.Helper() + data, err := os.ReadFile(fixture) + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(root, 0o755); err != nil { + t.Fatal(err) + } + var out *os.File + closeOut := func() { + if out != nil { + if err := out.Close(); err != nil { + t.Fatal(err) + } + out = nil + } + } + defer closeOut() + for n, line := range strings.Split(strings.ReplaceAll(string(data), "\r", ""), "\n") { + f := strings.Fields(line) + switch { + case len(f) == 0 || strings.HasPrefix(f[0], "#"): + case f[0] == "file" && len(f) == 4: + closeOut() + size, err1 := strconv.ParseInt(f[2], 10, 64) + mode, err2 := strconv.ParseUint(f[3], 8, 32) + if err1 != nil || err2 != nil || strings.ContainsAny(f[1], "/\\") { + t.Fatalf("%s:%d: bad file line %q", fixture, n+1, line) + } + if out, err = os.OpenFile(filepath.Join(root, f[1]), os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.FileMode(mode)); err != nil { + t.Fatal(err) + } + if err := out.Truncate(size); err != nil { + t.Fatal(err) + } + case out != nil && len(f) == 2: + off, err1 := strconv.ParseInt(f[0], 10, 64) + b, err2 := hex.DecodeString(f[1]) + if err1 != nil || err2 != nil { + t.Fatalf("%s:%d: bad bytes line %q", fixture, n+1, line) + } + if _, err := out.WriteAt(b, off); err != nil { + t.Fatal(err) + } + default: + t.Fatalf("%s:%d: unexpected line %q", fixture, n+1, line) + } + } +} diff --git a/seaweed-block/cmd/m01verify/main.go b/seaweed-block/cmd/m01verify/main.go new file mode 100644 index 0000000000..f17bacee57 --- /dev/null +++ b/seaweed-block/cmd/m01verify/main.go @@ -0,0 +1,164 @@ +//go:build m01verify + +// Hardware-test byte-equal verifier — built only under the +// `m01verify` build tag; never compiled into the production +// blockvolume binary. +// +// Build: +// +// go build -tags m01verify -o m01verify ./cmd/blockvolume/ +// +// Usage: +// +// m01verify --walstore /tmp/g5sm/replica-store/v1.walstore \ +// --lba-start 0 --lba-count 256 --block-size 4096 \ +// --expected-pattern | --expected-file payload.bin +// +// Opens the replica's walstore through `core/storage.OpenReadOnly` +// (NOT raw extent peek), invokes Read(lba) over the target LBA +// range, SHA-256-compares against the known primary write payload. +// Prints OK on equality, MISMATCH lba=N exp=... got=... + exit 1 +// on diff. +// +// Caller (script) MUST ensure the daemon owning the walstore is +// stopped or quiesced before invocation; OpenReadOnly opens the +// file O_RDONLY but the underlying WAL replay assumes no +// concurrent writer. + +package main + +import ( + "crypto/sha256" + "encoding/hex" + "flag" + "fmt" + "os" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type verifyFlags struct { + walstorePath string + lbaStart uint + lbaCount uint + blockSize uint + expectedPattern string // single hex byte (e.g. "ab") + expectedFile string // path to a binary file with the expected per-LBA bytes +} + +func parseVerifyFlags() (verifyFlags, error) { + var f verifyFlags + fs := flag.NewFlagSet("m01verify", flag.ContinueOnError) + fs.StringVar(&f.walstorePath, "walstore", "", "path to replica's walstore file (required)") + fs.UintVar(&f.lbaStart, "lba-start", 0, "first LBA to verify") + fs.UintVar(&f.lbaCount, "lba-count", 1, "number of consecutive LBAs to verify") + fs.UintVar(&f.blockSize, "block-size", 4096, "block size in bytes") + fs.StringVar(&f.expectedPattern, "expected-pattern", "", "expected per-byte pattern as a single hex byte (e.g. 'ab'); each LBA filled with this byte") + fs.StringVar(&f.expectedFile, "expected-file", "", "expected payload file (lba_count * block_size bytes); read concatenated per-LBA") + if err := fs.Parse(os.Args[1:]); err != nil { + return f, err + } + if f.walstorePath == "" { + return f, fmt.Errorf("--walstore required") + } + if f.lbaCount == 0 { + return f, fmt.Errorf("--lba-count must be > 0") + } + if f.expectedPattern == "" && f.expectedFile == "" { + return f, fmt.Errorf("one of --expected-pattern or --expected-file required") + } + if f.expectedPattern != "" && f.expectedFile != "" { + return f, fmt.Errorf("--expected-pattern and --expected-file are mutually exclusive") + } + return f, nil +} + +func main() { + f, err := parseVerifyFlags() + if err != nil { + fmt.Fprintln(os.Stderr, "m01verify:", err) + os.Exit(2) + } + + expected, err := buildExpected(f) + if err != nil { + fmt.Fprintln(os.Stderr, "m01verify: build expected:", err) + os.Exit(2) + } + + r, err := storage.OpenReadOnly(f.walstorePath) + if err != nil { + fmt.Fprintln(os.Stderr, "m01verify: OpenReadOnly:", err) + os.Exit(1) + } + defer func() { _ = r.Close() }() + + mismatches := 0 + for i := uint(0); i < f.lbaCount; i++ { + lba := uint32(f.lbaStart + i) + got, rerr := r.Read(lba) + if rerr != nil { + fmt.Fprintf(os.Stderr, "m01verify: Read lba=%d: %v\n", lba, rerr) + os.Exit(1) + } + want := expected[i] + if !bytesEqual(got, want) { + gotSum := sha256.Sum256(got) + wantSum := sha256.Sum256(want) + fmt.Printf("MISMATCH lba=%d exp_sha256=%s got_sha256=%s\n", + lba, hex.EncodeToString(wantSum[:8]), hex.EncodeToString(gotSum[:8])) + mismatches++ + } + } + if mismatches > 0 { + fmt.Printf("FAIL %d mismatch(es) over %d LBA(s)\n", mismatches, f.lbaCount) + os.Exit(1) + } + fmt.Printf("OK %d LBA(s) byte-equal\n", f.lbaCount) +} + +// buildExpected returns the expected bytes for each verified LBA. +// Either every LBA is filled with --expected-pattern, or the bytes +// come from --expected-file split into block-size chunks. +func buildExpected(f verifyFlags) ([][]byte, error) { + out := make([][]byte, f.lbaCount) + if f.expectedPattern != "" { + raw, err := hex.DecodeString(f.expectedPattern) + if err != nil || len(raw) != 1 { + return nil, fmt.Errorf("--expected-pattern must be a single hex byte (e.g. 'ab'); got %q", f.expectedPattern) + } + b := raw[0] + for i := range out { + block := make([]byte, f.blockSize) + for j := range block { + block[j] = b + } + out[i] = block + } + return out, nil + } + data, err := os.ReadFile(f.expectedFile) + if err != nil { + return nil, fmt.Errorf("read expected file: %w", err) + } + want := int(f.lbaCount * f.blockSize) + if len(data) < want { + return nil, fmt.Errorf("expected file too short: got %d bytes, want >= %d", len(data), want) + } + for i := uint(0); i < f.lbaCount; i++ { + out[i] = data[i*f.blockSize : (i+1)*f.blockSize] + } + return out, nil +} + +func bytesEqual(a, b []byte) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} diff --git a/seaweed-block/cmd/overview.md b/seaweed-block/cmd/overview.md new file mode 100644 index 0000000000..76a8a2f095 --- /dev/null +++ b/seaweed-block/cmd/overview.md @@ -0,0 +1,26 @@ +# `cmd/` Overview + +This directory contains executable entry points. Command packages should be thin: +they parse flags, wire modules, and run loops. Product semantics should live in +`core/`. + +## Commands + +| Directory | Purpose | Main Interfaces | +|---|---|---| +| `blockmaster/` | Control-plane daemon for desired volumes, node inventory, placement, authority publication, and launcher output. | lifecycle store, authority publisher, launcher renderer, master RPC/HTTP surfaces | +| `blockvolume/` | Data-plane daemon for one volume replica. Serves frontend protocols and subscribes to assignment facts. | storage backend, frontend target, authority subscription, replication/recovery | +| `blockcsi/` | Kubernetes CSI driver. Handles Create/Delete, ControllerPublish, NodeStage, NodePublish. | CSI gRPC, blockmaster client, Linux iSCSI/mount helpers | +| `sw-testops/` | Minimal scenario runner for registered TestOps scenarios. | `internal/testops` registry and drivers | +| `m01verify/` | Hardware/lab verification helper. | lab-only verification flow | +| `sparrow/` | Older/bootstrap experimental command surface retained for compatibility and tests. | bootstrap and calibration helpers | + +## Design Rules + +- Do not mint authority facts directly from command packages. +- Do not put storage/recovery policy in flag parsing code. +- Keep Kubernetes-specific runtime wiring in `blockmaster`/`blockcsi` edges, not + in generic lifecycle or authority packages. +- New product behavior should be testable below `cmd/` before a subprocess test + is added. + diff --git a/seaweed-block/cmd/sparrow/bootstrap.go b/seaweed-block/cmd/sparrow/bootstrap.go new file mode 100644 index 0000000000..c2544788d1 --- /dev/null +++ b/seaweed-block/cmd/sparrow/bootstrap.go @@ -0,0 +1,25 @@ +package main + +// The durable-authority bootstrap logic now lives in +// core/host/bootstrap so that both cmd/sparrow and cmd/v3master +// can share it. This file keeps the prior sparrow-internal names +// as thin aliases so existing S5 / S7 tests compile unchanged. + +import ( + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/host/bootstrap" +) + +// DurableAuthorityBootstrap is re-exported from core/host/bootstrap +// so existing sparrow code and tests can keep using the short name. +type DurableAuthorityBootstrap = bootstrap.DurableAuthorityBootstrap + +// Bootstrap and BootstrapFromStore are forwarded to the shared +// library. Signatures are preserved verbatim. +func Bootstrap(storeDir string, directive authority.Directive) (*DurableAuthorityBootstrap, error) { + return bootstrap.Bootstrap(storeDir, directive) +} + +func BootstrapFromStore(lock *authority.StoreLock, store authority.AuthorityStore, directive authority.Directive) (*DurableAuthorityBootstrap, error) { + return bootstrap.BootstrapFromStore(lock, store, directive) +} diff --git a/seaweed-block/cmd/sparrow/bootstrap_test.go b/seaweed-block/cmd/sparrow/bootstrap_test.go new file mode 100644 index 0000000000..84d855faaa --- /dev/null +++ b/seaweed-block/cmd/sparrow/bootstrap_test.go @@ -0,0 +1,439 @@ +package main + +import ( + "bytes" + "context" + "errors" + "log" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" +) + +// ============================================================ +// P14 S5 — Live Bootstrap Tests (cmd/sparrow) +// +// Architect round-5 ask: the durable authority route must be +// exercised through a real non-test caller, and LoadErrors() +// must surface as startup logging. These tests drive the +// Bootstrap helper in cmd/sparrow/bootstrap.go directly (same +// entry point runS5Bootstrap uses) and verify: +// +// - lock is acquired on fresh dir +// - reloaded records populate Publisher state +// - LoadErrors is logged at startup (not stranded) +// - lock refuses a second concurrent bootstrap on same dir +// - Close() releases lock and store cleanly +// ============================================================ + +// captureLog redirects the default logger to a byte buffer for +// the duration of the test. Returns the buffer (snapshot-on-call) +// and a restore func. +func captureLog(t *testing.T) (*bytes.Buffer, func()) { + t.Helper() + prev := log.Writer() + var buf bytes.Buffer + var mu sync.Mutex + log.SetOutput(writerFunc(func(p []byte) (int, error) { + mu.Lock() + defer mu.Unlock() + return buf.Write(p) + })) + return &buf, func() { log.SetOutput(prev) } +} + +type writerFunc func(p []byte) (int, error) + +func (w writerFunc) Write(p []byte) (int, error) { return w(p) } + +func TestBootstrap_FreshDir_AcquiresLockAndReloads(t *testing.T) { + dir := t.TempDir() + + logBuf, restore := captureLog(t) + defer restore() + + directive := authority.NewStaticDirective(nil) + boot, err := Bootstrap(dir, directive) + if err != nil { + t.Fatalf("Bootstrap: %v", err) + } + defer boot.Close() + + // Lock was acquired — lockfile must exist on disk. + if _, err := os.Stat(filepath.Join(dir, authority.LockFilename)); err != nil { + t.Fatalf("lock file not present: %v", err) + } + + // No prior records, so reload count is 0 and no skips. + if boot.ReloadedRecords != 0 { + t.Fatalf("fresh dir reload count: got %d want 0", boot.ReloadedRecords) + } + if len(boot.ReloadSkips) != 0 { + t.Fatalf("fresh dir must have no skips, got %v", boot.ReloadSkips) + } + + // Startup logs must include the lock-acquired line and the + // reload-count line. These are the surfaces the architect + // asked for: real startup visibility of the durable route. + logOutput := logBuf.String() + if !strings.Contains(logOutput, "durable authority lock acquired") { + t.Fatalf("startup log missing lock-acquired line:\n%s", logOutput) + } + if !strings.Contains(logOutput, "durable authority reload: 0 records") { + t.Fatalf("startup log missing reload-count line:\n%s", logOutput) + } +} + +func TestBootstrap_WithExistingRecord_ReloadsPublisherState(t *testing.T) { + dir := t.TempDir() + + // Simulate a prior run via the real publisher-run path: + // construct a Publisher with a Directive that emits one + // Bind, run briefly to let the write-through land, then + // tear down cleanly. This keeps the S5 boundary intact — + // the test does NOT call store.Put directly (only + // core/authority/ production code is allowed to do that). + seedDurableRecord(t, dir, authority.AssignmentAsk{ + VolumeID: "v-reload", ReplicaID: "r1", + DataAddr: "d1", CtrlAddr: "c1", + Intent: authority.IntentBind, + }) + + // Now the real bootstrap. + logBuf, restore := captureLog(t) + defer restore() + + boot, err := Bootstrap(dir, authority.NewStaticDirective(nil)) + if err != nil { + t.Fatalf("Bootstrap: %v", err) + } + defer boot.Close() + + if boot.ReloadedRecords != 1 { + t.Fatalf("reload count: got %d want 1", boot.ReloadedRecords) + } + + basis, ok := boot.Publisher.LastAuthorityBasis("v-reload", "r1") + if !ok { + t.Fatal("Publisher must have reloaded r1 into state") + } + if basis.Epoch != 1 { + t.Fatalf("reloaded Epoch: got %d want 1", basis.Epoch) + } + + if !strings.Contains(logBuf.String(), "durable authority reload: 1 records") { + t.Fatalf("startup log missing reload=1 line:\n%s", logBuf.String()) + } +} + +func TestBootstrap_CorruptRecord_LoggedAtStartup(t *testing.T) { + dir := t.TempDir() + + // Seed one good record via the publisher-run path. + seedDurableRecord(t, dir, authority.AssignmentAsk{ + VolumeID: "v-good", ReplicaID: "r1", + DataAddr: "d", CtrlAddr: "c", + Intent: authority.IntentBind, + }) + + // Now drop a corrupt file next to it. The filename uses the + // expected extension so Load will try to parse it. + badPath := filepath.Join(dir, "v-bad.v3auth.json") + if err := os.WriteFile(badPath, []byte("{not valid}"), 0o644); err != nil { + t.Fatalf("write corrupt: %v", err) + } + + // Bootstrap MUST succeed despite the corrupt record (per-volume + // fail-closed). The skip MUST be logged at startup so operators + // see it, not stranded inside Publisher.LoadErrors. + logBuf, restore := captureLog(t) + defer restore() + + boot, err := Bootstrap(dir, authority.NewStaticDirective(nil)) + if err != nil { + t.Fatalf("Bootstrap must survive corrupt record: %v", err) + } + defer boot.Close() + + if boot.ReloadedRecords != 1 { + t.Fatalf("good record must still reload: got %d", boot.ReloadedRecords) + } + if len(boot.ReloadSkips) == 0 { + t.Fatal("corrupt record must produce a reload skip") + } + + out := logBuf.String() + if !strings.Contains(out, "reload skip") { + t.Fatalf("startup log missing reload-skip line:\n%s", out) + } +} + +func TestBootstrap_LockContention_RefusesSecondBootstrap(t *testing.T) { + dir := t.TempDir() + + first, err := Bootstrap(dir, authority.NewStaticDirective(nil)) + if err != nil { + t.Fatalf("first Bootstrap: %v", err) + } + defer first.Close() + + second, err := Bootstrap(dir, authority.NewStaticDirective(nil)) + if err == nil { + second.Close() + t.Fatal("second Bootstrap must fail while first holds the lock") + } + if !errors.Is(err, authority.ErrStoreLockHeld) { + t.Fatalf("second Bootstrap: want ErrStoreLockHeld, got %v", err) + } + + // After first.Close(), a third bootstrap must succeed. + if err := first.Close(); err != nil { + t.Fatalf("first Close: %v", err) + } + third, err := Bootstrap(dir, authority.NewStaticDirective(nil)) + if err != nil { + t.Fatalf("third Bootstrap after first Close: %v", err) + } + third.Close() +} + +func TestBootstrap_EmptyStoreDir_Errors(t *testing.T) { + _, err := Bootstrap("", authority.NewStaticDirective(nil)) + if err == nil { + t.Fatal("Bootstrap with empty dir must fail") + } +} + +// seedDurableRecord simulates "a prior sparrow run persisted an +// assignment, then exited cleanly". Uses the real Publisher+ +// Directive path so the store is written by core/authority/ — +// respecting the S5 boundary that only the authority package +// may call store write verbs. +// +// Blocks until the record is visible in the store or the +// deadline elapses. +func seedDurableRecord(t *testing.T, dir string, ask authority.AssignmentAsk) { + t.Helper() + lock, err := authority.AcquireStoreLock(dir) + if err != nil { + t.Fatalf("seed acquire lock: %v", err) + } + store, err := authority.NewFileAuthorityStore(dir) + if err != nil { + _ = lock.Release() + t.Fatalf("seed store: %v", err) + } + directive := authority.NewStaticDirective([]authority.AssignmentAsk{ask}) + pub := authority.NewPublisher(directive, authority.WithStore(store)) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { _ = pub.Run(ctx) }() + + deadline := time.Now().Add(1 * time.Second) + for time.Now().Before(deadline) { + recs, err := store.Load() + if err == nil && len(recs) > 0 { + break + } + time.Sleep(5 * time.Millisecond) + } + cancel() + if err := store.Close(); err != nil { + t.Fatalf("seed close store: %v", err) + } + if err := lock.Release(); err != nil { + t.Fatalf("seed release lock: %v", err) + } +} + +// TestParseFlags_AuthorityStoreRequiresS5Bootstrap is the +// regression for architect round-8 finding #1: the default +// validation path is not restart-clean, so --authority-store +// must only be accepted when paired with --s5-bootstrap. The +// flag parser rejects the combination at parse time. +func TestParseFlags_AuthorityStoreRequiresS5Bootstrap(t *testing.T) { + cases := []struct { + name string + args []string + wantErr bool + }{ + { + name: "store-without-bootstrap rejected", + args: []string{"--authority-store", "/tmp/sparrow"}, + wantErr: true, + }, + { + name: "bootstrap-without-store rejected", + args: []string{"--s5-bootstrap"}, + wantErr: true, + }, + { + name: "both-together accepted", + args: []string{"--authority-store", "/tmp/sparrow", "--s5-bootstrap"}, + wantErr: false, + }, + { + name: "neither accepted (default mode)", + args: []string{}, + wantErr: false, + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + _, err := parseFlags(c.args) + if c.wantErr && err == nil { + t.Fatal("expected error, got nil") + } + if !c.wantErr && err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) + } +} + +// TestS5Bootstrap_RepeatedRunsAreRestartClean is the regression +// for architect round-8 finding #3: the test must actually +// exercise repeated runs, check exit codes, and prove the +// behavior it claims. Here we run runS5Bootstrap twice against +// the same directory with a durable record seeded in between +// (via the real publisher path). Both runs must exit 0, and the +// second run must report the reloaded count. +// +// Without the pre-check in Bootstrap (fix #2), the second run +// would still have worked because the index is readable; the +// value of this test is primarily the repeated-run integrity +// assertion: no stale lock, no silent failure. +func TestS5Bootstrap_RepeatedRunsAreRestartClean(t *testing.T) { + dir := t.TempDir() + + stdout := os.Stdout + devNull, _ := os.OpenFile(os.DevNull, os.O_WRONLY, 0) + if devNull != nil { + os.Stdout = devNull + defer func() { + os.Stdout = stdout + devNull.Close() + }() + } + + // First live bootstrap: empty store. + exit1 := runS5Bootstrap(options{authorityStore: dir, s5Bootstrap: true}) + if exit1 != 0 { + t.Fatalf("first runS5Bootstrap exit: got %d want 0", exit1) + } + + // Seed a durable record between runs via the real + // publisher+directive path (core/authority/ is the only + // allowed writer per S5 boundary; this uses the same helper + // used by the other bootstrap tests). + seedDurableRecord(t, dir, authority.AssignmentAsk{ + VolumeID: "v-persisted", ReplicaID: "r1", + DataAddr: "d", CtrlAddr: "c", + Intent: authority.IntentBind, + }) + + // Second run on the same directory must be restart-clean: + // no stale-lock failure, no Bind-on-already-bound, exit 0. + // It also must report the reload. + logBuf, restore := captureLog(t) + defer restore() + + exit2 := runS5Bootstrap(options{authorityStore: dir, s5Bootstrap: true}) + if exit2 != 0 { + t.Fatalf("second runS5Bootstrap exit: got %d want 0 (restart-clean failure; log:\n%s)", + exit2, logBuf.String()) + } + + if !strings.Contains(logBuf.String(), "durable authority reload: 1 records") { + t.Fatalf("second run did not reload persisted record; log:\n%s", logBuf.String()) + } +} + + +// indexFailingAuthorityStore is a mock AuthorityStore whose +// LoadWithSkips always returns an index-level error. Used to +// deterministically exercise the pre-check cleanup path in +// BootstrapFromStore — a filesystem-permission-based approach +// does not portably reproduce the path across Unix and Windows. +type indexFailingAuthorityStore struct { + closed bool +} + +var errInjectedIndexFailure = errors.New("injected index failure") + +func (s *indexFailingAuthorityStore) Load() ([]authority.DurableRecord, error) { + return nil, nil +} +func (s *indexFailingAuthorityStore) LoadWithSkips() ([]authority.DurableRecord, []error, error) { + return nil, nil, errInjectedIndexFailure +} +func (s *indexFailingAuthorityStore) Put(_ authority.DurableRecord) error { return nil } +func (s *indexFailingAuthorityStore) Close() error { s.closed = true; return nil } + +// TestBootstrap_PreCheckFailure_ReleasesLockAndClosesStore is +// the direct regression for architect round-8 finding #2 plus +// round-9 finding 3 (previous test did not actually exercise +// the pre-check branch). +// +// Uses the BootstrapFromStore seam to inject a mock store whose +// LoadWithSkips deterministically returns an index-level error +// on every platform. Asserts: +// 1. BootstrapFromStore returns the wrapped injected error. +// 2. The mock store's Close() was called. +// 3. A fresh AcquireStoreLock on the same directory succeeds, +// proving the lock was released despite the failure — the +// core cleanup contract of the round-8 fix. +func TestBootstrap_PreCheckFailure_ReleasesLockAndClosesStore(t *testing.T) { + dir := t.TempDir() + + lock, err := authority.AcquireStoreLock(dir) + if err != nil { + t.Fatalf("AcquireStoreLock: %v", err) + } + + fake := &indexFailingAuthorityStore{} + _, err = BootstrapFromStore(lock, fake, authority.NewStaticDirective(nil)) + if err == nil { + t.Fatal("BootstrapFromStore must return error on index-level LoadWithSkips failure") + } + if !errors.Is(err, errInjectedIndexFailure) { + t.Fatalf("error must wrap the injected sentinel, got %v", err) + } + if !fake.closed { + t.Fatal("store.Close() must be called on pre-check failure") + } + + // Second AcquireStoreLock must succeed — proves the lock was + // released by the failing BootstrapFromStore path. + lock2, err := authority.AcquireStoreLock(dir) + if err != nil { + t.Fatalf("AcquireStoreLock after pre-check failure must succeed (proves release): %v", err) + } + _ = lock2.Release() +} + +func TestBootstrap_Close_Idempotent(t *testing.T) { + dir := t.TempDir() + boot, err := Bootstrap(dir, authority.NewStaticDirective(nil)) + if err != nil { + t.Fatalf("Bootstrap: %v", err) + } + if err := boot.Close(); err != nil { + t.Fatalf("first Close: %v", err) + } + if err := boot.Close(); err != nil { + t.Fatalf("second Close must be idempotent: %v", err) + } +} + +func (s *indexFailingAuthorityStore) PutWorkspaceLostRanges(string, []authority.WorkspaceLostRange) error { + return nil +} +func (s *indexFailingAuthorityStore) LoadWorkspaceLostRanges() (map[string][]authority.WorkspaceLostRange, []error, error) { + return nil, nil, nil +} diff --git a/seaweed-block/cmd/sparrow/calibrate.go b/seaweed-block/cmd/sparrow/calibrate.go new file mode 100644 index 0000000000..cb70bfe7a1 --- /dev/null +++ b/seaweed-block/cmd/sparrow/calibrate.go @@ -0,0 +1,74 @@ +package main + +import ( + "encoding/json" + "fmt" + "os" + + "github.com/seaweedfs/seaweed-block/core/calibration" +) + +// runCalibration executes the Phase 06 first calibration pass and +// emits the Report. Text mode prints a per-scenario PASS/FAIL line +// plus the summary; --json emits the full machine-readable artifact +// suitable for piping into docs/calibration/ evidence review. +// +// Exit codes follow the sparrow contract: +// 0 all scenarios passed +// 1 one or more scenarios diverged or errored +// +// This is deliberately an addition to the sparrow binary rather than a +// new CLI — per v3-operations-design.md §1.3 and +// v3-phase-06-checklist.md §4 S1, Phase 06 reuses the accepted Phase 05 +// bootstrap entry path. +func runCalibration(opts options) int { + report := calibration.Runner{}.Run(calibration.AllScenarios()) + + if opts.json { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + _ = enc.Encode(report) + } else { + fmt.Println("=== V3 Phase 06 Calibration ===") + fmt.Println() + for _, r := range report.Results { + status := "PASS" + if !r.Pass { + status = "FAIL" + } + fmt.Printf(" [%s] %-28s %s — %s\n", r.Family, r.ID, status, r.Intent) + if !r.Pass { + printDivergenceText(r) + } + } + fmt.Println() + fmt.Printf("=== Summary: %d/%d passed, %d diverged, %d errored ===\n", + report.Summary.Passed, report.Summary.Total, + report.Summary.Diverged, report.Summary.Errors) + if !report.Summary.AllPassed { + fmt.Println() + fmt.Println("Record each divergence in docs/calibration/divergence-log.md") + fmt.Println("before changing the route or the expectations.") + } + } + + if report.Summary.AllPassed { + return 0 + } + return 1 +} + +func printDivergenceText(r calibration.Result) { + if r.Error != "" { + fmt.Printf(" error: %s\n", r.Error) + return + } + fmt.Printf(" expected: decision=%s final_mode=%s includes=%v excludes=%v\n", + r.Expected.Decision, r.Expected.FinalMode, + r.Expected.CommandPathIncludes, r.Expected.CommandPathExcludes) + fmt.Printf(" observed: decision=%s final_mode=%s command_path=%v\n", + r.Observed.Decision, r.Observed.FinalMode, r.Observed.CommandPath) + if r.Divergence != nil { + fmt.Printf(" divergence: %+v\n", *r.Divergence) + } +} diff --git a/seaweed-block/cmd/sparrow/main.go b/seaweed-block/cmd/sparrow/main.go new file mode 100644 index 0000000000..da2b628f0d --- /dev/null +++ b/seaweed-block/cmd/sparrow/main.go @@ -0,0 +1,345 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "log" + "net" + "net/http" + "os" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/engine" + "github.com/seaweedfs/seaweed-block/core/ops" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +type options struct { + json bool + runs int + httpAddr string + calibrate bool + persistDemo bool + persistDir string + authorityStore string + s5Bootstrap bool + s7RestartSmoke bool +} + +type demoResult struct { + Demo string `json:"demo"` + Pass bool `json:"pass"` + Reason string `json:"reason,omitempty"` + Projection engine.ReplicaProjection `json:"projection"` +} + +func main() { + log.SetFlags(log.Lmicroseconds) + + opts, err := parseFlags(os.Args[1:]) + if err != nil { + fmt.Fprintln(os.Stderr, "sparrow:", err) + os.Exit(2) + } + + switch { + case opts.calibrate: + os.Exit(runCalibration(opts)) + case opts.persistDemo: + os.Exit(runPersistDemo(opts)) + case opts.s5Bootstrap: + os.Exit(runS5Bootstrap(opts)) + case opts.s7RestartSmoke: + os.Exit(runS7RestartSmoke(opts)) + default: + os.Exit(runSparrow(opts)) + } +} + +func parseFlags(args []string) (options, error) { + var opts options + fs := flag.NewFlagSet("sparrow", flag.ContinueOnError) + fs.BoolVar(&opts.json, "json", false, "emit machine-readable JSON output") + fs.IntVar(&opts.runs, "runs", 1, "repeat the validation path N times") + fs.StringVar(&opts.httpAddr, "http", "", "start read-only HTTP ops server on ADDR") + fs.BoolVar(&opts.calibrate, "calibrate", false, "run the calibration package") + fs.BoolVar(&opts.persistDemo, "persist-demo", false, "run the single-node persistence demonstration") + fs.StringVar(&opts.persistDir, "persist-dir", "", "directory for --persist-demo backing file") + fs.StringVar(&opts.authorityStore, "authority-store", "", "directory for durable authority records") + fs.BoolVar(&opts.s5Bootstrap, "s5-bootstrap", false, "run the durable authority bootstrap (requires --authority-store)") + // --s7-restart-smoke is a test-only entry for the real-subprocess + // restart smoke. It is intentionally undocumented in operator + // tooling; the flag help string is terse so running sparrow with + // --help doesn't advertise it as a workflow. + fs.BoolVar(&opts.s7RestartSmoke, "s7-restart-smoke", false, "internal test-only: restart smoke (requires --authority-store)") + fs.SetOutput(ioDiscard{}) + if err := fs.Parse(args); err != nil { + return options{}, err + } + if opts.runs < 1 { + return options{}, fmt.Errorf("--runs must be >= 1") + } + // --authority-store only makes sense under the durable + // bootstrap mode. The default validation demos are SMOKE + // tests by design — their Bind → Reassign → Reassign + // sequence is not restart-clean against a persisted store + // and forcing it to be would smuggle durability-aware + // branches into demo code. Keep the durable flag strict: + // only --s5-bootstrap consumes it. Future slices (S6 / S7) + // can widen this. + if opts.authorityStore != "" && !opts.s5Bootstrap && !opts.s7RestartSmoke { + return options{}, fmt.Errorf("--authority-store requires --s5-bootstrap or --s7-restart-smoke; use one of those for the durable authority path") + } + if opts.s5Bootstrap && opts.authorityStore == "" { + return options{}, fmt.Errorf("--s5-bootstrap requires --authority-store

") + } + if opts.s7RestartSmoke && opts.authorityStore == "" { + return options{}, fmt.Errorf("--s7-restart-smoke requires --authority-store ") + } + if opts.s5Bootstrap && opts.s7RestartSmoke { + return options{}, fmt.Errorf("--s5-bootstrap and --s7-restart-smoke are mutually exclusive") + } + return opts, nil +} + +func runSparrow(opts options) int { + state := ops.NewState() + var srv *http.Server + if opts.httpAddr != "" { + boundSrv, boundAddr, err := startHTTPOpsWithState(opts.httpAddr, state) + if err != nil { + fmt.Fprintf(os.Stderr, "sparrow: failed to bind --http %s: %v\n", opts.httpAddr, err) + return 3 + } + srv = boundSrv + fmt.Printf("listening on %s\n", boundAddr) + defer shutdownServer(srv) + } + + // The default validation path is in-memory by design. + // Durable authority (--authority-store) is only valid under + // --s5-bootstrap; see parseFlags for why. Attempting to run + // the demos against a durable store is rejected earlier. + allPassed := true + var allResults [][]demoResult + for i := 0; i < opts.runs; i++ { + results, err := runValidationPass(state, "vol1") + if err != nil { + fmt.Fprintf(os.Stderr, "sparrow: validation run %d: %v\n", i+1, err) + return 3 + } + allResults = append(allResults, results) + for _, r := range results { + if !r.Pass { + allPassed = false + } + } + } + + if opts.json { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + _ = enc.Encode(allResults) + } else { + fmt.Println("=== V3 Block Sparrow ===") + for runIdx, results := range allResults { + fmt.Printf("\nRun %d:\n", runIdx+1) + for _, r := range results { + status := "FAIL" + if r.Pass { + status = "PASS" + } + fmt.Printf(" %s: %s", r.Demo, status) + if r.Reason != "" { + fmt.Printf(" (%s)", r.Reason) + } + fmt.Println() + } + } + } + + if allPassed { + return 0 + } + return 1 +} + +func runValidationPass(state *ops.State, volumeID string, pubOpts ...authority.PublisherOption) ([]demoResult, error) { + var results []demoResult + + // All three demos route assignment truth through the S2 authority + // publisher — the publisher mints Epoch/EndpointVersion, no demo + // code constructs AssignmentInfo directly. + // + // pubOpts is an S5-era wiring seam kept for forward-compat, + // but runSparrow ALWAYS passes the empty option set today: + // --authority-store is rejected at parseFlags unless paired + // with --s5-bootstrap, which is a separate mode and does not + // reach this function. The default validation demos run + // entirely in memory. Any LoadErrors() from an empty-option + // publisher will be zero-length; the logging loop below is a + // no-op in the default path and is kept for forward-compat + // with future slices that may legitimately pass a store here. + // + // volumeID is caller-chosen so future slices (S6/S7) can + // widen the flag surface without reworking this signature. + // Today the only caller is runSparrow, which passes "vol1". + dir := authority.NewStaticDirective(nil) + pub := authority.NewPublisher(dir, pubOpts...) + if errs := pub.LoadErrors(); len(errs) > 0 { + for _, e := range errs { + log.Printf("sparrow: durable authority reload skip: %v", e) + } + } + pubCtx, pubCancel := context.WithCancel(context.Background()) + defer pubCancel() + go func() { _ = pub.Run(pubCtx) }() + + primaryStore := storage.NewBlockStore(256, 4096) + replicaStore := storage.NewBlockStore(256, 4096) + + replicaListener, err := transport.NewReplicaListener("127.0.0.1:0", replicaStore) + if err != nil { + return nil, fmt.Errorf("replica listener: %w", err) + } + replicaListener.Serve() + defer replicaListener.Stop() + replicaAddr := replicaListener.Addr() + + exec := transport.NewBlockExecutor(primaryStore, replicaAddr) + adpt := adapter.NewVolumeReplicaAdapter(exec) + state.Update("healthy", adpt) + + for i := uint32(0); i < 10; i++ { + data := make([]byte, 4096) + data[0] = byte(i + 1) + _, _ = primaryStore.Write(i, data) + } + _, _ = primaryStore.Sync() + blocks, err := primaryStore.AllBlocks() + if err != nil { + return nil, fmt.Errorf("snapshot primary: %w", err) + } + _, _, pH := primaryStore.Boundaries() + for lba, data := range blocks { + _ = replicaStore.ApplyEntry(lba, data, pH) + } + _, _ = replicaStore.Sync() + + bridge1Ctx, bridge1Cancel := context.WithCancel(pubCtx) + go authority.Bridge(bridge1Ctx, pub, adpt, volumeID, "r1") + dir.Append(authority.AssignmentAsk{ + VolumeID: volumeID, ReplicaID: "r1", + DataAddr: replicaAddr, CtrlAddr: replicaAddr, + Intent: authority.IntentBind, + }) + time.Sleep(200 * time.Millisecond) + results = append(results, buildResult("healthy", adpt.Projection())) + bridge1Cancel() + + for i := uint32(10); i < 20; i++ { + data := make([]byte, 4096) + data[0] = byte(i + 1) + _, _ = primaryStore.Write(i, data) + } + _, _ = primaryStore.Sync() + exec2 := transport.NewBlockExecutor(primaryStore, replicaAddr) + adpt2 := adapter.NewVolumeReplicaAdapter(exec2) + state.Update("catch_up", adpt2) + + bridge2Ctx, bridge2Cancel := context.WithCancel(pubCtx) + go authority.Bridge(bridge2Ctx, pub, adpt2, volumeID, "r1") + dir.Append(authority.AssignmentAsk{ + VolumeID: volumeID, ReplicaID: "r1", + DataAddr: replicaAddr, CtrlAddr: replicaAddr, + Intent: authority.IntentReassign, + Evidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindForced}, // a demo: a forced move + }) + results = append(results, buildResult("catch_up", waitForMode(adpt2, engine.ModeHealthy, 5*time.Second))) + bridge2Cancel() + + replicaStore2 := storage.NewBlockStore(256, 4096) + replicaListener2, err := transport.NewReplicaListener("127.0.0.1:0", replicaStore2) + if err != nil { + return nil, fmt.Errorf("replica listener 2: %w", err) + } + replicaListener2.Serve() + defer replicaListener2.Stop() + replicaAddr2 := replicaListener2.Addr() + primaryStore.AdvanceWALTail(primaryStore.NextLSN()) + exec3 := transport.NewBlockExecutor(primaryStore, replicaAddr2) + adpt3 := adapter.NewVolumeReplicaAdapter(exec3) + state.Update("rebuild", adpt3) + + bridge3Ctx, bridge3Cancel := context.WithCancel(pubCtx) + defer bridge3Cancel() + go authority.Bridge(bridge3Ctx, pub, adpt3, volumeID, "r1") + dir.Append(authority.AssignmentAsk{ + VolumeID: volumeID, ReplicaID: "r1", + DataAddr: replicaAddr2, CtrlAddr: replicaAddr2, + Intent: authority.IntentReassign, + Evidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindForced}, // a demo: a forced move + }) + results = append(results, buildResult("rebuild", waitForMode(adpt3, engine.ModeHealthy, 5*time.Second))) + + return results, nil +} + +func buildResult(name string, proj engine.ReplicaProjection) demoResult { + r := demoResult{ + Demo: name, + Pass: proj.Mode == engine.ModeHealthy, + Projection: proj, + } + if !r.Pass { + if proj.Reason != "" { + r.Reason = proj.Reason + } else { + r.Reason = string(proj.Mode) + } + } + return r +} + +func startHTTPOps(addr string) (*http.Server, string, error) { + return startHTTPOpsWithState(addr, ops.NewState()) +} + +func startHTTPOpsWithState(addr string, state *ops.State) (*http.Server, string, error) { + srv := ops.NewServer(addr, Version, ScopeStatement, state) + ln, err := net.Listen("tcp", addr) + if err != nil { + return nil, "", err + } + go func() { + _ = srv.Serve(ln) + }() + return srv, ln.Addr().String(), nil +} + +func shutdownServer(srv *http.Server) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + _ = srv.Shutdown(ctx) +} + +func waitForMode(adpt *adapter.VolumeReplicaAdapter, want engine.Mode, timeout time.Duration) engine.ReplicaProjection { + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + p := adpt.Projection() + if p.Mode == want { + return p + } + time.Sleep(50 * time.Millisecond) + } + return adpt.Projection() +} + +type ioDiscard struct{} + +func (ioDiscard) Write(p []byte) (int, error) { return len(p), nil } diff --git a/seaweed-block/cmd/sparrow/main_test.go b/seaweed-block/cmd/sparrow/main_test.go new file mode 100644 index 0000000000..21dd5db812 --- /dev/null +++ b/seaweed-block/cmd/sparrow/main_test.go @@ -0,0 +1,259 @@ +package main + +import ( + "context" + "io" + "net" + "net/http" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/engine" +) + +func TestParseFlags_Defaults(t *testing.T) { + opts, err := parseFlags(nil) + if err != nil { + t.Fatal(err) + } + if opts.json { + t.Fatal("default --json should be false") + } + if opts.runs != 1 { + t.Fatalf("default --runs = %d, want 1", opts.runs) + } + if opts.httpAddr != "" { + t.Fatalf("default --http = %q, want empty", opts.httpAddr) + } +} + +func TestParseFlags_AllFlagsSet(t *testing.T) { + opts, err := parseFlags([]string{"--json", "--runs", "5", "--http", ":9090"}) + if err != nil { + t.Fatal(err) + } + if !opts.json { + t.Fatal("--json not set") + } + if opts.runs != 5 { + t.Fatalf("--runs = %d, want 5", opts.runs) + } + if opts.httpAddr != ":9090" { + t.Fatalf("--http = %q, want :9090", opts.httpAddr) + } +} + +func TestParseFlags_RejectsBadRuns(t *testing.T) { + _, err := parseFlags([]string{"--runs", "0"}) + if err == nil { + t.Fatal("expected error for --runs 0") + } + _, err = parseFlags([]string{"--runs", "-3"}) + if err == nil { + t.Fatal("expected error for --runs -3") + } +} + +func TestScopeStatement_HonestAboutUnsupported(t *testing.T) { + // The scope statement is the authoritative capability claim shown + // by --help and echoed by /status. Verify it lists every + // unsupported item we care about. + mustContain := []string{ + "Supported:", + "Not supported", + "persistence", + "master service", + "RF3", + "iSCSI", + "NVMe-oF", + "concurrent writer", + "real operator CLI", + } + for _, s := range mustContain { + if !strings.Contains(ScopeStatement, s) { + t.Fatalf("ScopeStatement missing %q", s) + } + } +} + +func TestVersion_HasPhaseTag(t *testing.T) { + // The version string should make the pre-production status obvious + // (zero-dot prefix) and tag the current phase explicitly. + if !strings.HasPrefix(Version, "0.") { + t.Fatalf("Version %q should start with 0. (pre-production)", Version) + } + if !strings.Contains(Version, "phase") { + t.Fatalf("Version %q should tag the phase explicitly", Version) + } +} + +func TestRunSparrow_AllThreePathsPass(t *testing.T) { + // Exercise the full validation path once in non-verbose mode. + // All three demos should PASS; exit code 0. + code := runSparrow(options{json: true, runs: 1}) + if code != 0 { + t.Fatalf("runSparrow exit code = %d, want 0 (all pass)", code) + } +} + +func TestRunSparrow_RepeatableAcrossRuns(t *testing.T) { + // Repeat runs must all pass. If any run flakes, the exit code + // becomes non-zero. This is the deterministic-validation proof. + code := runSparrow(options{json: true, runs: 3}) + if code != 0 { + t.Fatalf("runSparrow --runs=3 exit code = %d, want 0", code) + } +} + +func TestBuildResult_PassWhenHealthy(t *testing.T) { + healthy := engine.ReplicaProjection{ + Mode: engine.ModeHealthy, R: 100, S: 10, H: 100, + } + r := buildResult("x", healthy) + if !r.Pass { + t.Fatal("expected Pass=true for healthy mode") + } + if r.Reason != "" { + t.Fatalf("healthy result should have no reason, got %q", r.Reason) + } +} + +func TestStartHTTPOps_BindsAndServes(t *testing.T) { + // Happy path: bind succeeds on :0, returns a real address, the + // server actually answers /status requests. + srv, boundAddr, err := startHTTPOps("127.0.0.1:0") + if err != nil { + t.Fatalf("unexpected bind error: %v", err) + } + defer func() { + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) + defer cancel() + _ = srv.Shutdown(ctx) + }() + + // Bound address must be concrete — not ":0" and not empty. + if boundAddr == "" || strings.HasSuffix(boundAddr, ":0") { + t.Fatalf("boundAddr should resolve to a real port, got %q", boundAddr) + } + + // Server must actually answer. Retry briefly for goroutine schedule. + var resp *http.Response + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + resp, err = http.Get("http://" + boundAddr + "/status") + if err == nil { + break + } + time.Sleep(20 * time.Millisecond) + } + if err != nil { + t.Fatalf("GET /status never succeeded: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + t.Fatalf("/status: got %d, want 200", resp.StatusCode) + } + body, _ := io.ReadAll(resp.Body) + if !strings.Contains(string(body), "phase") { + t.Fatalf("/status body should contain version tag, got: %s", body) + } +} + +func TestStartHTTPOps_FailsOnPortConflict(t *testing.T) { + // Hold a port so the ops server cannot bind it. This is the + // regression test for the honesty bug: the old code printed + // "listening" even when ListenAndServe() failed asynchronously. + blocker, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("could not reserve port: %v", err) + } + defer blocker.Close() + busyAddr := blocker.Addr().String() + + _, _, err = startHTTPOps(busyAddr) + if err == nil { + t.Fatalf("expected bind failure on occupied port %s, got nil", busyAddr) + } + // Must be a real net error, not a wrapped log line. + if !strings.Contains(err.Error(), "bind") && !strings.Contains(err.Error(), "address") { + t.Logf("note: error is %v (platform-dependent message; this is not a failure)", err) + } +} + +func TestRunPersistDemo_HappyPath(t *testing.T) { + dir := t.TempDir() + code := runPersistDemo(options{ + json: true, + persistDemo: true, + persistDir: dir, + }) + if code != 0 { + t.Fatalf("runPersistDemo exit code = %d, want 0 (data should survive restart)", code) + } +} + +func TestRunPersistDemo_RequiresPersistDir(t *testing.T) { + code := runPersistDemo(options{ + persistDemo: true, + persistDir: "", // missing + }) + if code != 2 { + t.Fatalf("runPersistDemo without --persist-dir: code=%d, want 2 (usage)", code) + } +} + +// TestRunPersistDemo_RepeatableInSameDir locks in that running the +// demo twice in the same dir works. The first run creates the file; +// the second run must remove the prior file and recreate cleanly. +// Without the prior-file cleanup, CreateWALStore's O_EXCL would fail +// on the second invocation. +func TestRunPersistDemo_RepeatableInSameDir(t *testing.T) { + dir := t.TempDir() + for i := 0; i < 2; i++ { + code := runPersistDemo(options{ + json: true, + persistDemo: true, + persistDir: dir, + }) + if code != 0 { + t.Fatalf("run %d: exit code = %d, want 0", i+1, code) + } + } +} + +func TestRunSparrow_HTTPBindFailure_ReturnsExit3(t *testing.T) { + // End-to-end honesty check: when --http can't bind, runSparrow + // must exit with code 3 (runtime error), NOT silently proceed + // to run demos as if the server were live. + blocker, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("could not reserve port: %v", err) + } + defer blocker.Close() + busyAddr := blocker.Addr().String() + + code := runSparrow(options{ + json: true, + runs: 1, + httpAddr: busyAddr, + }) + if code != 3 { + t.Fatalf("exit code = %d, want 3 (http bind failure)", code) + } +} + +func TestBuildResult_FailWhenNotHealthy(t *testing.T) { + degraded := engine.ReplicaProjection{ + Mode: engine.ModeDegraded, + RecoveryDecision: engine.DecisionUnknown, + R: 0, S: 10, H: 100, + } + r := buildResult("x", degraded) + if r.Pass { + t.Fatal("expected Pass=false for degraded mode") + } + if r.Reason == "" { + t.Fatal("failing result should carry a reason") + } +} diff --git a/seaweed-block/cmd/sparrow/persist.go b/seaweed-block/cmd/sparrow/persist.go new file mode 100644 index 0000000000..c4e021c7b2 --- /dev/null +++ b/seaweed-block/cmd/sparrow/persist.go @@ -0,0 +1,206 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "path/filepath" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// runPersistDemo is the single-node persistence demonstration: +// write a known pattern, Sync, Close, reopen, Recover, read it back. +// +// What this exercises: +// - the LogicalStorage interface admits a real on-disk backend +// - acked data (covered by a successful Sync) survives Close + +// Reopen + Recover round trip +// +// Crash consistency for acked writes is verified separately by +// TestWALStore_AckedWritesSurviveSimulatedCrash in the storage +// package, which bypasses Close to simulate a process kill. +// +// What this DOES NOT prove (intentional scope boundary): +// - distributed durability across nodes +// +// Exit codes follow the sparrow contract: +// +// 0 data round-tripped intact +// 1 data did not survive restart (the actual failure mode for this demo) +// 2 usage / flag error +// 3 runtime error (file create/open/read/write/sync failure) +func runPersistDemo(opts options) int { + dir := opts.persistDir + if dir == "" { + fmt.Fprintln(os.Stderr, "sparrow: --persist-demo requires --persist-dir DIR") + return 2 + } + path := filepath.Join(dir, "sparrow-persist.dat") + + // The owned COW map is a file. Refuse an unexpected directory before + // changing the prior demo; never recursively remove a caller's directory. + mapPath := path + ".chunkmap" + if st, err := os.Lstat(mapPath); err == nil && st.IsDir() { + fmt.Fprintln(os.Stderr, "sparrow: persist demo: unexpected directory at map file path") + return 3 + } else if err != nil && !os.IsNotExist(err) { + fmt.Fprintf(os.Stderr, "sparrow: persist demo: inspect map: %v\n", err) + return 3 + } + + // Demo is meant to be reproducible: every invocation creates a + // fresh file. If a previous demo left bytes behind, remove them + // before Round 1 so CreateWALStore's O_EXCL doesn't collide. + // Only the named demo file and its owned map sidecar are retired; the + // supplied parent directory and unrelated siblings are preserved. + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + fmt.Fprintf(os.Stderr, "sparrow: persist demo: cannot remove prior file %s: %v\n", path, err) + return 3 + } + + // V3 owns a COW map file at this exact sibling path. + // Removing only the volume would leave the next O_EXCL map create blocked. + if err := os.Remove(mapPath); err != nil && !os.IsNotExist(err) { + fmt.Fprintf(os.Stderr, "sparrow: persist demo: cannot remove prior map: %v\n", err) + return 3 + } + + const ( + numBlocks = 16 + blockSize = 4096 + nWrites = 4 + ) + + // Round 1: create, write, sync, close. + r1, err := persistRound1(path, numBlocks, blockSize, nWrites) + if err != nil { + fmt.Fprintf(os.Stderr, "sparrow: persist round1: %v\n", err) + return 3 + } + + // Round 2: open, recover, read back, compare. + r2, err := persistRound2(path, nWrites) + if err != nil { + fmt.Fprintf(os.Stderr, "sparrow: persist round2: %v\n", err) + return 3 + } + + report := persistReport{ + Path: path, + NumBlocks: numBlocks, + BlockSize: blockSize, + NWrites: nWrites, + SyncedBefore: r1.synced, + RecoveredAfter: r2.recovered, + AllMatched: r2.allMatched, + FailedLBAs: r2.failedLBAs, + } + + if opts.json { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + _ = enc.Encode(report) + } else { + fmt.Println("=== Single-Node Persistence Demo (WAL+extent backend) ===") + fmt.Println() + fmt.Printf(" path: %s\n", report.Path) + fmt.Printf(" blocks written: %d (block size %d)\n", report.NWrites, report.BlockSize) + fmt.Printf(" synced LSN: %d\n", report.SyncedBefore) + fmt.Printf(" recovered LSN: %d\n", report.RecoveredAfter) + fmt.Println() + if report.AllMatched { + fmt.Println(" result: PASS — all blocks survived restart") + } else { + fmt.Printf(" result: FAIL — LBAs %v did not survive\n", report.FailedLBAs) + } + fmt.Println() + fmt.Println("Scope:") + fmt.Println(" - acked writes survive crash (verified by simulated-kill test in storage package)") + fmt.Println(" - single-node only; distributed durability NOT in scope") + } + + if !report.AllMatched { + return 1 + } + return 0 +} + +type persistReport struct { + Path string `json:"path"` + NumBlocks uint32 `json:"num_blocks"` + BlockSize int `json:"block_size"` + NWrites int `json:"n_writes"` + SyncedBefore uint64 `json:"synced_before_close"` + RecoveredAfter uint64 `json:"recovered_after_open"` + AllMatched bool `json:"all_matched"` + FailedLBAs []uint32 `json:"failed_lbas,omitempty"` +} + +type round1Result struct { + synced uint64 +} + +func persistRound1(path string, numBlocks uint32, blockSize, nWrites int) (round1Result, error) { + s, err := storage.CreateWALStore(path, numBlocks, blockSize) + if err != nil { + return round1Result{}, fmt.Errorf("create: %w", err) + } + for i := 0; i < nWrites; i++ { + data := makePattern(blockSize, byte(0xA0+i)) + if _, err := s.Write(uint32(i), data); err != nil { + _ = s.Close() + return round1Result{}, fmt.Errorf("write LBA %d: %w", i, err) + } + } + synced, err := s.Sync() + if err != nil { + _ = s.Close() + return round1Result{}, fmt.Errorf("sync: %w", err) + } + if err := s.Close(); err != nil { + return round1Result{}, fmt.Errorf("close: %w", err) + } + return round1Result{synced: synced}, nil +} + +type round2Result struct { + recovered uint64 + allMatched bool + failedLBAs []uint32 +} + +func persistRound2(path string, nWrites int) (round2Result, error) { + s, err := storage.OpenWALStore(path) + if err != nil { + return round2Result{}, fmt.Errorf("open: %w", err) + } + defer s.Close() + recovered, err := s.Recover() + if err != nil { + return round2Result{}, fmt.Errorf("recover: %w", err) + } + + out := round2Result{recovered: recovered, allMatched: true} + for i := 0; i < nWrites; i++ { + got, err := s.Read(uint32(i)) + if err != nil { + return round2Result{}, fmt.Errorf("read LBA %d: %w", i, err) + } + want := makePattern(s.BlockSize(), byte(0xA0+i)) + if !bytes.Equal(got, want) { + out.allMatched = false + out.failedLBAs = append(out.failedLBAs, uint32(i)) + } + } + return out, nil +} + +func makePattern(blockSize int, fill byte) []byte { + b := make([]byte, blockSize) + for i := range b { + b[i] = fill + } + return b +} diff --git a/seaweed-block/cmd/sparrow/persist_sidecar_test.go b/seaweed-block/cmd/sparrow/persist_sidecar_test.go new file mode 100644 index 0000000000..08b305adfc --- /dev/null +++ b/seaweed-block/cmd/sparrow/persist_sidecar_test.go @@ -0,0 +1,52 @@ +package main + +import ( + "os" + "path/filepath" + "testing" +) + +func TestRunPersistDemoRetiresOnlyItsOwnedMap(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "sparrow-persist.dat") + if err := os.WriteFile(path, []byte("prior demo"), 0600); err != nil { + t.Fatal(err) + } + stale := path + ".chunkmap" + if err := os.WriteFile(stale, []byte("stale map"), 0600); err != nil { + t.Fatal(err) + } + other := path + ".unrelated" + if err := os.WriteFile(other, []byte("keep"), 0600); err != nil { + t.Fatal(err) + } + if code := runPersistDemo(options{json: true, persistDemo: true, persistDir: dir}); code != 0 { + t.Fatalf("demo exit=%d", code) + } + if got, err := os.ReadFile(stale); err == nil && string(got) == "stale map" { + t.Fatal("prior map file survives") + } else if err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + if got, err := os.ReadFile(other); err != nil || string(got) != "keep" { + t.Fatalf("unrelated sibling changed: %q %v", got, err) + } +} + +func TestRunPersistDemoRefusesUnexpectedMapDirectory(t *testing.T) { + dir := t.TempDir() + mapPath := filepath.Join(dir, "sparrow-persist.dat.chunkmap") + if err := os.Mkdir(mapPath, 0700); err != nil { + t.Fatal(err) + } + keep := filepath.Join(mapPath, "keep") + if err := os.WriteFile(keep, []byte("unrecognized directory"), 0600); err != nil { + t.Fatal(err) + } + if code := runPersistDemo(options{json: true, persistDemo: true, persistDir: dir}); code != 3 { + t.Fatalf("unexpected map directory exit=%d want3", code) + } + if got, err := os.ReadFile(keep); err != nil || string(got) != "unrecognized directory" { + t.Fatalf("unexpected directory changed: %q %v", got, err) + } +} diff --git a/seaweed-block/cmd/sparrow/s5_bootstrap.go b/seaweed-block/cmd/sparrow/s5_bootstrap.go new file mode 100644 index 0000000000..05062a4917 --- /dev/null +++ b/seaweed-block/cmd/sparrow/s5_bootstrap.go @@ -0,0 +1,82 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "log" + "os" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" +) + +// runS5Bootstrap is the live, non-test entrypoint exercising the +// durable authority bootstrap path: +// +// 1. AcquireStoreLock — single-owner OS lock on the store dir +// 2. NewFileAuthorityStore — open file-per-volume backend +// 3. NewPublisher(..., WithStore(store)) — reload synchronously +// 4. log LoadErrors() at startup so reload-corruption is visible +// +// The mode is intentionally narrow: it proves the durable route +// is wired end-to-end under a real flag, and produces machine- +// readable output so CI (or a real operator) can verify the +// reload count and skip list. +// +// Without --authority-store, sparrow continues to run in-memory +// (existing behavior preserved). With --authority-store AND +// --s5-bootstrap, sparrow performs the durable bootstrap and +// exits 0 on success. Running twice in a row against the same +// store directory exercises the reload path. +func runS5Bootstrap(opts options) int { + if opts.authorityStore == "" { + fmt.Fprintln(os.Stderr, "sparrow: --s5-bootstrap requires --authority-store ") + return 2 + } + + directive := authority.NewStaticDirective(nil) + boot, err := Bootstrap(opts.authorityStore, directive) + if err != nil { + fmt.Fprintln(os.Stderr, "sparrow:", err) + return 1 + } + defer func() { + if cerr := boot.Close(); cerr != nil { + log.Printf("sparrow: close durable bootstrap: %v", cerr) + } + }() + + // Let the Publisher's Run goroutine start so the bootstrapped + // state is observably "live" — not just constructed. A short + // context cancel returns promptly; the bootstrap's own logs + // already recorded the reload outcome. + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + go func() { _ = boot.Publisher.Run(ctx) }() + <-ctx.Done() + + if opts.json { + report := map[string]any{ + "store": opts.authorityStore, + "reloaded_records": boot.ReloadedRecords, + "reload_skip_count": len(boot.ReloadSkips), + "reload_skip_reasons": summarizeSkips(boot.ReloadSkips), + } + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + _ = enc.Encode(report) + } else { + fmt.Printf("sparrow s5-bootstrap: store=%q reloaded=%d skips=%d\n", + opts.authorityStore, boot.ReloadedRecords, len(boot.ReloadSkips)) + } + return 0 +} + +func summarizeSkips(skips []error) []string { + out := make([]string, 0, len(skips)) + for _, e := range skips { + out = append(out, e.Error()) + } + return out +} diff --git a/seaweed-block/cmd/sparrow/s7_bootstrap_test.go b/seaweed-block/cmd/sparrow/s7_bootstrap_test.go new file mode 100644 index 0000000000..78bca682f1 --- /dev/null +++ b/seaweed-block/cmd/sparrow/s7_bootstrap_test.go @@ -0,0 +1,194 @@ +package main + +import ( + "os" + "path/filepath" + "testing" + + "github.com/seaweedfs/seaweed-block/core/authority" +) + +// ============================================================ +// P14 S7 — Component-layer (in-process) tests +// +// These close proof-matrix rows 8, 9, 10 from +// sw-block/design/v3-phase-14-s7-sketch.md §13.2. They run +// Bootstrap() twice against the same t.TempDir() inside ONE +// test process, asserting directly on Bootstrap fields and +// Publisher state — the assertions that are awkward to read +// through stdout. The real-subprocess gate (row 10b) lives in +// s7_restart_smoke_test.go per §8.1 shape 2. +// +// Strict Windows residual scope (sketch §8.5): a cleanup-phase +// teardown error may be residual, but a store write / reload +// error is a hard test failure. These tests use only the +// high-level Bootstrap surface; any error returned by +// Bootstrap() fails the test. +// ============================================================ + +// Row 8: sparrow Bootstrap with durable store, reload, publisher +// route construction, clean exit — component layer. +func TestS7Process_BootstrapReloadRouteSmoke(t *testing.T) { + dir := t.TempDir() + + // Fresh dir: ReloadedRecords==0, no skips. + boot1, err := Bootstrap(dir, authority.NewStaticDirective(nil)) + if err != nil { + t.Fatalf("first Bootstrap: %v", err) + } + if boot1.ReloadedRecords != 0 { + t.Fatalf("fresh dir reload count: got %d want 0", boot1.ReloadedRecords) + } + if len(boot1.ReloadSkips) != 0 { + t.Fatalf("fresh dir skips: got %v want none", boot1.ReloadSkips) + } + if err := boot1.Close(); err != nil { + t.Fatalf("first Close: %v", err) + } + + // Seed one record via the real publisher-run path. + seedDurableRecord(t, dir, authority.AssignmentAsk{ + VolumeID: "s7-vol", ReplicaID: "r1", + DataAddr: "d1", CtrlAddr: "c1", + Intent: authority.IntentBind, + }) + + // Second Bootstrap reloads and exits cleanly. + boot2, err := Bootstrap(dir, authority.NewStaticDirective(nil)) + if err != nil { + t.Fatalf("second Bootstrap: %v", err) + } + defer func() { + if err := boot2.Close(); err != nil { + t.Fatalf("second Close: %v", err) + } + }() + if boot2.ReloadedRecords != 1 { + t.Fatalf("reload count: got %d want 1", boot2.ReloadedRecords) + } +} + +// Row 9: second in-process Bootstrap on same dir sees prior +// authority and does NOT mint backward. Verifies restart +// truth is preserved across in-process teardown + rebuild. +func TestS7Process_RestartDoesNotRegressAuthorityLine(t *testing.T) { + dir := t.TempDir() + + // Seed one Bind through the real publisher-run path so the + // durable store holds r1@1. A single record is sufficient to + // prove "no backward mint on restart" — any reload-driven + // re-mint (even a fresh Epoch=1 that rewrites the same line) + // would be a violation of the §3 load-bearing constraint. + seedDurableRecord(t, dir, authority.AssignmentAsk{ + VolumeID: "s7-vol", ReplicaID: "r1", + DataAddr: "d1", CtrlAddr: "c1", + Intent: authority.IntentBind, + }) + + // Bootstrap round 1 — should reload r1@1. + boot1, err := Bootstrap(dir, authority.NewStaticDirective(nil)) + if err != nil { + t.Fatalf("Bootstrap round 1: %v", err) + } + line1, ok := boot1.Publisher.VolumeAuthorityLine("s7-vol") + if !ok { + t.Fatal("round 1: VolumeAuthorityLine missing after reload") + } + if line1.ReplicaID != "r1" || line1.Epoch != 1 { + t.Fatalf("round 1 line: got %+v want r1@1", line1) + } + if err := boot1.Close(); err != nil { + t.Fatalf("Close round 1: %v", err) + } + + // Bootstrap round 2 — MUST see the same line. No reload- + // driven mint may advance OR rewrite the Epoch. + boot2, err := Bootstrap(dir, authority.NewStaticDirective(nil)) + if err != nil { + t.Fatalf("Bootstrap round 2: %v", err) + } + defer boot2.Close() + line2, ok := boot2.Publisher.VolumeAuthorityLine("s7-vol") + if !ok { + t.Fatal("round 2: VolumeAuthorityLine missing after reload") + } + if line2.ReplicaID != line1.ReplicaID || + line2.Epoch != line1.Epoch || + line2.EndpointVersion != line1.EndpointVersion { + t.Fatalf("restart changed authority line (§3 violation): round1=%+v round2=%+v", line1, line2) + } +} + +// Row 10: reload skips and unsupported evidence surface in +// structured form. The test drops a corrupt store file and +// checks that Bootstrap.ReloadSkips carries the per-file +// error; controller-side UnsupportedEvidence is exercised in +// the L1 route tests, not here (this is a bootstrap-surface +// assertion). +func TestS7Process_RestartReportsEvidence(t *testing.T) { + dir := t.TempDir() + + // Seed one good record. + seedDurableRecord(t, dir, authority.AssignmentAsk{ + VolumeID: "s7-good", ReplicaID: "r1", + DataAddr: "d", CtrlAddr: "c", + Intent: authority.IntentBind, + }) + + // Write one corrupt record next to it. + corrupt := "{not valid json}" + badPath := filepath.Join(dir, "s7-bad.v3auth.json") + if err := os.WriteFile(badPath, []byte(corrupt), 0o644); err != nil { + t.Fatalf("write corrupt: %v", err) + } + + boot, err := Bootstrap(dir, authority.NewStaticDirective(nil)) + if err != nil { + t.Fatalf("Bootstrap must survive corrupt record: %v", err) + } + defer boot.Close() + + if boot.ReloadedRecords != 1 { + t.Fatalf("reloaded count: got %d want 1 (the good record)", boot.ReloadedRecords) + } + if len(boot.ReloadSkips) == 0 { + t.Fatal("ReloadSkips must report the corrupt record as a structured error") + } +} + +// TestParseFlags_S7RestartSmoke covers the flag-combination +// rules for --s7-restart-smoke. +func TestParseFlags_S7RestartSmoke(t *testing.T) { + cases := []struct { + name string + args []string + wantErr bool + }{ + { + name: "s7-smoke-without-store rejected", + args: []string{"--s7-restart-smoke"}, + wantErr: true, + }, + { + name: "s7-smoke-with-store accepted", + args: []string{"--authority-store", "/tmp/sparrow", "--s7-restart-smoke"}, + wantErr: false, + }, + { + name: "s5 and s7 mutually exclusive", + args: []string{"--authority-store", "/tmp/sparrow", "--s5-bootstrap", "--s7-restart-smoke"}, + wantErr: true, + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + _, err := parseFlags(c.args) + if c.wantErr && err == nil { + t.Fatal("expected error, got nil") + } + if !c.wantErr && err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) + } +} diff --git a/seaweed-block/cmd/sparrow/s7_restart_smoke.go b/seaweed-block/cmd/sparrow/s7_restart_smoke.go new file mode 100644 index 0000000000..d317d85f1e --- /dev/null +++ b/seaweed-block/cmd/sparrow/s7_restart_smoke.go @@ -0,0 +1,171 @@ +package main + +import ( + "context" + "encoding/json" + "log" + "os" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" +) + +// runS7RestartSmoke is the narrow test-only entry that drives the +// real-subprocess restart smoke. It is NOT advertised in --help and +// has no operator workflow; it exists only so the L2 process test +// can spawn a real `sparrow` binary twice against the same store +// directory and assert on structured stdout. +// +// Contract: +// +// 1. Bootstrap against --authority-store (acquire lock, open +// file store, reload Publisher). +// 2. If the store is empty after reload (ReloadedRecords == 0), +// this is the FIRST run: mint one Bind through the +// Publisher so there is durable state for the next run to +// observe. If the store already has records, this is the +// SECOND run: report reloaded state without minting. +// 3. Emit exactly ONE structured JSON line to stdout matching +// the s7RestartSmokeReport schema below, then exit 0. +// 4. On any error path, emit the structured line with Pass="" +// and a non-empty Error, exit non-zero. +// +// "No backward mint" is enforced by construction: the smoke +// only mints on the first run (when the store is empty), so +// the second run cannot produce a lower Epoch than the first. +// The test still asserts backwardMint=false in the stdout line +// so a future bug that accidentally re-minted on reload would +// fail the test loudly. +func runS7RestartSmoke(opts options) int { + if opts.authorityStore == "" { + emitSmokeErr("s7-restart-smoke requires --authority-store ", nil, false) + return 2 + } + + directive := authority.NewStaticDirective(nil) + boot, err := Bootstrap(opts.authorityStore, directive) + if err != nil { + emitSmokeErr(err.Error(), nil, false) + return 1 + } + defer func() { + if cerr := boot.Close(); cerr != nil { + log.Printf("sparrow: close durable bootstrap: %v", cerr) + } + }() + + var runLabel string + var reportedLine *s7SmokeLine + backwardMint := false + + if boot.ReloadedRecords == 0 { + // First run: mint one Bind through the real Publisher + + // durable store path so the next run has something to + // reload. We drive the mint via the static directive so + // the full publisher.Run loop (not a synthetic apply) is + // what writes to the store. + runLabel = "first" + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + go func() { _ = boot.Publisher.Run(ctx) }() + + directive.Append(authority.AssignmentAsk{ + VolumeID: "s7-smoke-vol", + ReplicaID: "s7-smoke-r1", + DataAddr: "data-s7-smoke", + CtrlAddr: "ctrl-s7-smoke", + Intent: authority.IntentBind, + }) + + // Wait for the mint to land durably. We poll + // VolumeAuthorityLine because the publisher's internal + // apply is asynchronous relative to directive.Append. + deadline := time.Now().Add(2 * time.Second) + var line authority.AuthorityBasis + ok := false + for time.Now().Before(deadline) { + if line, ok = boot.Publisher.VolumeAuthorityLine("s7-smoke-vol"); ok && line.Assigned { + break + } + time.Sleep(10 * time.Millisecond) + } + if !ok || !line.Assigned { + emitSmokeErr("first run: mint did not reach publisher within deadline", nil, false) + return 1 + } + reportedLine = &s7SmokeLine{ + VolumeID: "s7-smoke-vol", + ReplicaID: line.ReplicaID, + Epoch: line.Epoch, + EndpointVersion: line.EndpointVersion, + } + } else { + // Second (or subsequent) run: record the reloaded line. + // No mint — the publisher's directive is empty; Run is + // not even needed for the observation we return. + runLabel = "second" + if line, ok := boot.Publisher.VolumeAuthorityLine("s7-smoke-vol"); ok && line.Assigned { + reportedLine = &s7SmokeLine{ + VolumeID: "s7-smoke-vol", + ReplicaID: line.ReplicaID, + Epoch: line.Epoch, + EndpointVersion: line.EndpointVersion, + } + // Epoch==1 is what the first run minted via IntentBind. + // Anything < 1 or a missing line on the reload side + // would indicate a reload regression. + if line.Epoch < 1 { + backwardMint = true + } + } else { + emitSmokeErr("second run: reloaded line missing for s7-smoke-vol", nil, false) + return 1 + } + } + + emitSmokeOK(runLabel, boot.ReloadedRecords, len(boot.ReloadSkips), reportedLine, backwardMint) + return 0 +} + +// s7RestartSmokeReport is the exact JSON schema the smoke +// emits on stdout. Pinned by sketch §8.4. +type s7RestartSmokeReport struct { + Pass string `json:"pass"` + Run string `json:"run"` + Reloaded int `json:"reloaded"` + Skips int `json:"skips"` + Line *s7SmokeLine `json:"line"` + BackwardMint bool `json:"backwardMint"` + Error string `json:"error,omitempty"` +} + +type s7SmokeLine struct { + VolumeID string `json:"vid"` + ReplicaID string `json:"rid"` + Epoch uint64 `json:"epoch"` + EndpointVersion uint64 `json:"endpointVersion"` +} + +func emitSmokeOK(run string, reloaded, skips int, line *s7SmokeLine, backwardMint bool) { + r := s7RestartSmokeReport{ + Pass: "s7-restart-smoke", + Run: run, + Reloaded: reloaded, + Skips: skips, + Line: line, + BackwardMint: backwardMint, + } + _ = json.NewEncoder(os.Stdout).Encode(r) +} + +func emitSmokeErr(msg string, line *s7SmokeLine, backwardMint bool) { + r := s7RestartSmokeReport{ + Pass: "", + Run: "", + Line: line, + BackwardMint: backwardMint, + Error: msg, + } + _ = json.NewEncoder(os.Stdout).Encode(r) +} diff --git a/seaweed-block/cmd/sparrow/s7_restart_smoke_test.go b/seaweed-block/cmd/sparrow/s7_restart_smoke_test.go new file mode 100644 index 0000000000..084ab77014 --- /dev/null +++ b/seaweed-block/cmd/sparrow/s7_restart_smoke_test.go @@ -0,0 +1,169 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +// TestS7Process_RealSubprocessRestartSmoke is the L2 process +// proof required by P14 S7 sketch §8.1 shape 2 and row 10b of +// the proof matrix. +// +// Shape: +// 1. Build the sparrow binary into a tempdir. +// 2. Spawn `sparrow --authority-store --s7-restart-smoke`. +// First invocation sees an empty store, mints one Bind, +// emits {"run":"first",...}, exits 0. +// 3. Spawn the same command again against the same dir. +// Second invocation sees the reloaded line, mints nothing, +// emits {"run":"second",...} whose Epoch matches the first +// run's Epoch, exits 0. +// 4. Parent test asserts: both exit 0, both runs emitted the +// pinned JSON pass-line, the lock was released between +// runs (second run started cleanly), the line reloaded +// matches what the first run wrote, and backwardMint is +// false on both runs. +// +// Windows residual-risk scope (sketch §8.5): only teardown / +// cleanup-phase errors may be logged as residual. Any error +// from Bootstrap / the store itself must remain a hard +// failure. This test treats every stdout-parse failure and +// every exit!=0 as a hard failure. +func TestS7Process_RealSubprocessRestartSmoke(t *testing.T) { + if testing.Short() { + t.Skip("skipping subprocess smoke under -short") + } + + // Bound the whole test (build + two subprocess runs) to a + // conservative deadline so a hung `go build` or subprocess + // dies when `go test` times out instead of lingering. + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + + tmp := t.TempDir() + binName := "sparrow-s7-smoke" + if runtime.GOOS == "windows" { + binName += ".exe" + } + binPath := filepath.Join(tmp, binName) + + // Build the sparrow binary against the current module. Using + // the Go toolchain the test runs under keeps versions aligned + // with the test process. + buildCmd := exec.CommandContext(ctx, "go", "build", "-o", binPath, "github.com/seaweedfs/seaweed-block/cmd/sparrow") + var buildErr bytes.Buffer + buildCmd.Stderr = &buildErr + if err := buildCmd.Run(); err != nil { + t.Fatalf("go build sparrow: %v\nstderr: %s", err, buildErr.String()) + } + + storeDir := filepath.Join(tmp, "store") + + // First run. + firstReport := runS7Smoke(ctx, t, binPath, storeDir, "first") + if firstReport.Error != "" { + t.Fatalf("first run reported error: %s", firstReport.Error) + } + if firstReport.Pass != "s7-restart-smoke" { + t.Fatalf("first run pass tag: got %q want %q", firstReport.Pass, "s7-restart-smoke") + } + if firstReport.Run != "first" { + t.Fatalf("first run label: got %q want %q (empty store should produce a first-run)", firstReport.Run, "first") + } + if firstReport.Reloaded != 0 { + t.Fatalf("first run reloaded: got %d want 0 (empty store)", firstReport.Reloaded) + } + if firstReport.Line == nil { + t.Fatal("first run must report the minted line") + } + if firstReport.Line.Epoch != 1 || firstReport.Line.ReplicaID != "s7-smoke-r1" { + t.Fatalf("first run line: got %+v, want Epoch=1 rid=s7-smoke-r1", firstReport.Line) + } + if firstReport.BackwardMint { + t.Fatal("first run must not report backwardMint") + } + + // Second run against the same store directory. + secondReport := runS7Smoke(ctx, t, binPath, storeDir, "second") + if secondReport.Error != "" { + t.Fatalf("second run reported error: %s", secondReport.Error) + } + if secondReport.Pass != "s7-restart-smoke" { + t.Fatalf("second run pass tag: got %q want %q", secondReport.Pass, "s7-restart-smoke") + } + if secondReport.Run != "second" { + t.Fatalf("second run label: got %q want %q (non-empty store should produce a second-run)", secondReport.Run, "second") + } + if secondReport.Reloaded < 1 { + t.Fatalf("second run reloaded: got %d, expected >= 1", secondReport.Reloaded) + } + if secondReport.Line == nil { + t.Fatal("second run must report the reloaded line") + } + if secondReport.Line.Epoch != firstReport.Line.Epoch || + secondReport.Line.ReplicaID != firstReport.Line.ReplicaID || + secondReport.Line.VolumeID != firstReport.Line.VolumeID || + secondReport.Line.EndpointVersion != firstReport.Line.EndpointVersion { + t.Fatalf("reloaded line mismatch: first=%+v second=%+v", firstReport.Line, secondReport.Line) + } + if secondReport.BackwardMint { + t.Fatal("second run must not report backwardMint") + } +} + +// runS7Smoke spawns one invocation of the smoke binary, +// captures stdout, parses exactly one JSON line, and returns +// the decoded report. Asserts exit 0 and that the pass-line +// was emitted; anything else is a hard test failure. +func runS7Smoke(ctx context.Context, t *testing.T, binPath, storeDir, label string) s7RestartSmokeReport { + t.Helper() + + cmd := exec.CommandContext(ctx, binPath, "--authority-store", storeDir, "--s7-restart-smoke") + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + + err := cmd.Run() + exitCode := 0 + if exitErr, ok := err.(*exec.ExitError); ok { + exitCode = exitErr.ExitCode() + } else if err != nil { + t.Fatalf("%s run: unexpected error invoking subprocess: %v", label, err) + } + if exitCode != 0 { + t.Fatalf("%s run: exit code %d\nstdout: %s\nstderr: %s", label, exitCode, stdout.String(), stderr.String()) + } + + // The schema is ONE JSON line. Decode the last non-empty + // line in stdout so any incidental log output before the + // pass-line would not break parsing. The child emits + // exactly one encoded object via json.Encoder, so in the + // happy path there is only one line. + line := lastNonEmptyLine(stdout.String()) + if line == "" { + t.Fatalf("%s run: no stdout line emitted\nstderr: %s", label, stderr.String()) + } + var report s7RestartSmokeReport + if decodeErr := json.Unmarshal([]byte(line), &report); decodeErr != nil { + t.Fatalf("%s run: failed to decode stdout line: %v\nline: %s", label, decodeErr, line) + } + return report +} + +func lastNonEmptyLine(s string) string { + lines := strings.Split(strings.TrimSpace(s), "\n") + for i := len(lines) - 1; i >= 0; i-- { + ln := strings.TrimSpace(lines[i]) + if ln != "" { + return ln + } + } + return "" +} diff --git a/seaweed-block/cmd/sparrow/scope.go b/seaweed-block/cmd/sparrow/scope.go new file mode 100644 index 0000000000..ba5e6db6a0 --- /dev/null +++ b/seaweed-block/cmd/sparrow/scope.go @@ -0,0 +1,33 @@ +package main + +// ScopeStatement is the authoritative honest capability statement. +// Shown by `sparrow --help` and echoed by the optional HTTP /status +// endpoint so no interface ever overclaims what the semantic core +// actually owns. +const ScopeStatement = `seaweed-block sparrow, runnable slice with bootstrap, calibration, and single-node persistence. + +Supported: + - run the three canonical demos (healthy, catch-up, rebuild) + - repeatable validation via --runs N + - machine-readable output via --json + - optional read-only HTTP inspection surface via --http ADDR + - calibration pass via --calibrate (5 scenarios C1-C5) + - single-node persistence demo via --persist-demo --persist-dir DIR + (WAL+extent backend; write -> Sync -> Close -> reopen -> Recover -> read) + - crash consistency for acked writes (writes covered by a successful Sync + survive process kill; verified by simulated-crash test in the + storage package, not by this CLI demo) + +Not supported (errors surface explicitly): + - distributed durability across nodes + - master service / dynamic assignment + - any mutation via the HTTP ops surface + - RF3 and multi-replica flows + - frontend protocols (iSCSI, NVMe-oF) + - concurrent writer during replication + - a real operator CLI surface (weed shell is the future path) +` + +// Version is the current binary version. Zero-dot to make the +// pre-production status explicit — not a 1.x contract. +const Version = "0.7.0-phase07" diff --git a/seaweed-block/cmd/sw-block/catalog_snapshot_operation.go b/seaweed-block/cmd/sw-block/catalog_snapshot_operation.go new file mode 100644 index 0000000000..36bc322ce0 --- /dev/null +++ b/seaweed-block/cmd/sw-block/catalog_snapshot_operation.go @@ -0,0 +1,79 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" +) + +// chunkRunCatalogSnapshotDelete is the CLI-owned execution/observation seam. +// Admission supplies the retained identity. A nil work override uses the +// catalog's shared atomic unlink/intent adapter. No background server or +// process-local progress is added. +func chunkRunCatalogSnapshotDelete(ctx context.Context, cat *chunkstore.BCatalog, volume chunkstore.VolumeRef, op chunkstore.SnapshotOperation, work chunkstore.SnapshotDeleteWork, noWait bool, stdout, stderr io.Writer) int { + answer, err := chunkCatalogSnapshotDeleteAnswer(ctx, cat, volume, op, work, noWait, stderr) + if err != nil { + return chunkResult("snapshot-delete", nil, err, stdout, stderr) + } + if raw, ok := answer.(json.RawMessage); ok { + if err := writeAll(stdout, raw); err != nil { + return chunkExitFailed + } + return 0 + } + return chunkResult("snapshot-delete", answer, nil, stdout, stderr) +} + +func chunkCatalogSnapshotDeleteAnswer(ctx context.Context, cat *chunkstore.BCatalog, volume chunkstore.VolumeRef, op chunkstore.SnapshotOperation, work chunkstore.SnapshotDeleteWork, noWait bool, stderr io.Writer) (any, error) { + fmt.Fprintf(stderr, "snapshot-delete %s request id %s instance %s sequence %d; repeat with the same --request-id to resume\n", snapshotIncarnation(op), op.ID, op.Instance, op.Sequence) + if op.State == "refused" { + return nil, &chunkstore.CatalogError{Code: op.ErrorCode, Message: op.ErrorMessage} + } + if noWait { + return map[string]any{"operation_id": op.ID, "volume_id": op.VolumeID.String(), "incarnation": snapshotIncarnation(op), "instance": op.Instance, "sequence": op.Sequence, "state": op.State}, nil + } + answer, err := cat.RunSnapshotDeleteOperation(ctx, volume, op, work) + if err != nil { + return nil, &chunkstore.CatalogError{Code: "no_progress", Message: err.Error() + "; resume with --request-id " + op.ID, Retryable: true, Err: err} + } + if answer.State == "refused" { + return nil, &chunkstore.CatalogError{Code: answer.ErrorCode, Message: answer.ErrorMessage} + } + if answer.State != "succeeded" || len(answer.Result) == 0 || !json.Valid(answer.Result) { + return nil, &chunkstore.CatalogError{Code: codeInternalCLI, Message: "operation has no terminal result"} + } + return answer.Result, nil +} + +// snapshotIncarnation names the incarnation a delete operation captured, +// name@gen (the name alone while none is captured). +func snapshotIncarnation(op chunkstore.SnapshotOperation) string { + if op.TargetGeneration == nil || *op.TargetGeneration == 0 { + return op.Name + } + return fmt.Sprintf("%s@%d", op.Name, *op.TargetGeneration) +} + +// chunkAdmitCatalogSnapshotDelete admits a delete operation for name; a +// nonzero pin admits it only for that incarnation (name@pin). +func chunkAdmitCatalogSnapshotDelete(ctx context.Context, cat *chunkstore.BCatalog, volume chunkstore.VolumeRef, id, name string, pin uint64, noWait bool, stderr io.Writer) (any, error) { + st, err := cat.Store(volume) + if err != nil { + return nil, err + } + op, err := st.AdmitSnapshotDeleteOperation(ctx, id, name, chunkstore.SnapshotDeleteTarget(st, name, pin)) + if err != nil { + if errors.Is(err, chunkstore.ErrSnapshotOperationIntent) { + return nil, &chunkstore.CatalogError{Code: "operation_intent_conflict", Message: err.Error(), Err: err} + } + if errors.Is(err, chunkstore.ErrSnapshotOperationRetired) { + return nil, &chunkstore.CatalogError{Code: "operation_retired", Message: err.Error(), Err: err} + } + return nil, err + } + return chunkCatalogSnapshotDeleteAnswer(ctx, cat, volume, op, nil, noWait, stderr) +} diff --git a/seaweed-block/cmd/sw-block/catalog_snapshot_operation_test.go b/seaweed-block/cmd/sw-block/catalog_snapshot_operation_test.go new file mode 100644 index 0000000000..f1c93916e5 --- /dev/null +++ b/seaweed-block/cmd/sw-block/catalog_snapshot_operation_test.go @@ -0,0 +1,365 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +func TestSnapshotDeleteOfflineCLILeavesProgressInFiler(t *testing.T) { + ctx := context.Background() + mem := newMemChunkStore() + cat, err := chunkstore.NewBCatalog(mem, mem, "/blocks") + if err != nil { + t.Fatal(err) + } + id, err := layout.ParseVolumeID("00000000000000000000000000000001") + if err != nil { + t.Fatal(err) + } + v := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err := cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + st, err := cat.Store(v) + if err != nil { + t.Fatal(err) + } + op, err := st.AdmitSnapshotDeleteOperation(ctx, "offline-original", "daily", func(context.Context) (uint64, error) { return 19, nil }) + if err != nil { + t.Fatal(err) + } + var out, logs bytes.Buffer + code := chunkRunCatalogSnapshotDelete(ctx, cat, v, op, func(context.Context, *chunkstore.LayoutStore, chunkstore.SnapshotOperation) error { + t.Fatal("no-wait launched local work") + return nil + }, true, &out, &logs) + if code != 0 || !strings.Contains(out.String(), `"operation_id":"offline-original"`) || !strings.Contains(logs.String(), op.Instance) { + t.Fatalf("no resumable identity: code=%d out=%s logs=%s", code, &out, &logs) + } + unchanged, err := st.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence) + if err != nil || unchanged.Revision != op.Revision { + t.Fatalf("no-wait mutated authority: %+v %v", unchanged, err) + } + out.Reset() + logs.Reset() + code = chunkRunCatalogSnapshotDelete(ctx, cat, v, op, func(context.Context, *chunkstore.LayoutStore, chunkstore.SnapshotOperation) error { + return errors.New("interrupted durable work") + }, false, &out, &logs) + if code == 0 || !strings.Contains(out.String(), `"retryable":true`) { + t.Fatalf("interruption reported completion: code=%d out=%s", code, &out) + } + other, err := chunkstore.NewBCatalog(mem, mem, "/blocks") + if err != nil { + t.Fatal(err) + } + store, err := other.Store(v) + if err != nil { + t.Fatal(err) + } + retained, err := store.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence) + if err != nil || retained.State != "stalled" { + t.Fatalf("progress was process local: %+v %v", retained, err) + } + out.Reset() + logs.Reset() + code = chunkRunCatalogSnapshotDelete(ctx, other, v, retained, func(_ context.Context, st *chunkstore.LayoutStore, got chunkstore.SnapshotOperation) error { + if *got.TargetGeneration != 19 { + t.Fatalf("changed target: %+v", got) + } + _, err := st.AdvanceSnapshotOperation(ctx, got, "succeeded", json.RawMessage(`{"name":"daily","state":"absent"}`), "") + return err + }, false, &out, &logs) + if code != 0 || out.String() != `{"name":"daily","state":"absent"}` { + t.Fatalf("resume result: code=%d out=%q", code, out.String()) + } +} + +func TestSnapshotDeleteOfflineCLIUsesAtomicLogicalStep(t *testing.T) { + ctx := context.Background() + mem := newMemChunkStore() + cat, err := chunkstore.NewBCatalog(mem, mem, "/blocks") + if err != nil { + t.Fatal(err) + } + id, err := layout.ParseVolumeID("00000000000000000000000000000001") + if err != nil { + t.Fatal(err) + } + v := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err := cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + st, err := cat.Store(v) + if err != nil { + t.Fatal(err) + } + root, segments, err := layout.Build(map[uint64]layout.Ref{}) + if err != nil { + t.Fatal(err) + } + rn, err := layout.PrepareRoot(ctx, st, root, segments, "seed") + if err != nil { + t.Fatal(err) + } + h, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + h.Version = layout.HeadVersion1 + h.Snapshots = map[string]layout.Snapshot{"daily": {Root: rn, Gen: 2}} + if err := st.UpdateHead(ctx, h.Gen, h, layout.CauseSnapshotUnchanged); err != nil { + t.Fatal(err) + } + op, err := st.AdmitSnapshotDeleteOperation(ctx, "cli-real", "daily", func(context.Context) (uint64, error) { return 2, nil }) + if err != nil { + t.Fatal(err) + } + var out, logs bytes.Buffer + code := chunkRunCatalogSnapshotDelete(ctx, cat, v, op, nil, false, &out, &logs) + if code != 0 || out.String() != `{"volume_id":"00000000000000000000000000000001","name":"daily","gen":2}` { + t.Fatalf("real logical answer: code=%d out=%s logs=%s", code, &out, &logs) + } + h, _, err = st.ReadHead(ctx) + if err != nil || h.Gen != 3 || h.List == nil || len(h.Snapshots) != 0 { + t.Fatalf("CLI did not use atomic unlink/intent: %+v %v", h, err) + } +} + +func TestSnapshotDeletePublicOperationKeepsTargetAcrossRecreation(t *testing.T) { + ctx := context.Background() + mem := newMemChunkStore() + useMemChunkStore(t, mem) + v := cliVolume(t, mem, "v1", "daily") + cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI) + st, _ := cat.Store(v) + h, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + target := h.Snapshots["daily"] + target.Gen = h.Gen + 1 + h.Version = layout.HeadVersion1 + h.Snapshots["daily"] = target + if err = st.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil { + t.Fatal(err) + } + args := cliArgs("snapshot-delete", volArgs("volume", v), []string{"--name", "daily", "--request-id", "delete-original"}) + code, first, logs := runChunk(args...) + if code != 0 { + t.Fatalf("delete admission: %d %s %s", code, first, logs) + } + if !strings.Contains(logs, "delete-original") { + t.Fatalf("missing resumable identity: %s", logs) + } + h, _, err = st.ReadHead(ctx) + if err != nil || len(h.Snapshots) != 0 || h.List == nil { + t.Fatalf("logical delete: %+v %v", h, err) + } + replacement := target + replacement.Gen = h.Gen + 1 + h.Snapshots = map[string]layout.Snapshot{"daily": replacement} + if err = st.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil { + t.Fatal(err) + } + code, replay, logs := runChunk(args...) + if code != 0 || replay != first { + t.Fatalf("original reply changed: code=%d first=%s replay=%s logs=%s", code, first, replay, logs) + } + h, _, err = st.ReadHead(ctx) + if err != nil || h.Snapshots["daily"].Gen != replacement.Gen { + t.Fatalf("retry removed replacement: %+v %v", h, err) + } +} + +func TestSnapshotDeletePublicNoWaitResumesSameAdmission(t *testing.T) { + ctx := context.Background() + mem := newMemChunkStore() + useMemChunkStore(t, mem) + v := cliVolume(t, mem, "v1", "daily") + cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI) + st, _ := cat.Store(v) + h, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + snap := h.Snapshots["daily"] + snap.Gen = h.Gen + 1 + h.Version = layout.HeadVersion1 + h.Snapshots["daily"] = snap + if err = st.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil { + t.Fatal(err) + } + args := cliArgs("snapshot-delete", volArgs("volume", v), []string{"--name", "daily", "--request-id", "queued-delete"}) + code, out, logs := runChunk(append(args, "--no-wait")...) + if code != 0 || !strings.Contains(out, `"operation_id":"queued-delete"`) { + t.Fatalf("admission: %d %s %s", code, out, logs) + } + after, _, err := st.ReadHead(ctx) + if err != nil || after.Gen != h.Gen+1 || len(after.Snapshots) != 1 { + t.Fatalf("no-wait executed: %+v %v", after, err) + } + op, found, err := st.ReadSnapshotOperation(ctx, "queued-delete", "delete") + if err != nil || !found || *op.TargetGeneration != snap.Gen { + t.Fatalf("missing durable target: %+v %v", op, err) + } + code, out, logs = runChunk(args...) + if code != 0 || !strings.Contains(out, `"gen":`) { + t.Fatalf("resume: %d %s %s", code, out, logs) + } + after, _, err = st.ReadHead(ctx) + if err != nil || len(after.Snapshots) != 0 || after.List == nil { + t.Fatalf("resume not logical: %+v %v", after, err) + } +} + +func TestSnapshotDeletePublicAbsentHeadRefuses(t *testing.T) { + mem := newMemChunkStore() + useMemChunkStore(t, mem) + id, _ := layout.ParseVolumeID("00000000000000000000000000000001") + v := chunkstore.VolumeRef{Name: "missing", ID: id} + args := cliArgs("snapshot-delete", volArgs("volume", v), []string{"--name", "daily", "--request-id", "absent"}) + code, out, _ := runChunk(args...) + if code != chunkExitFailed || chunkErrorOut(t, out).Code != "volume_not_found" { + t.Fatalf("absent HEAD accepted: %d %s", code, out) + } +} + +func TestSnapshotDeletePublicRefusesUnstampedLegacyAndChangedIntent(t *testing.T) { + ctx := context.Background() + mem := newMemChunkStore() + useMemChunkStore(t, mem) + v := cliVolume(t, mem, "v1", "daily") + args := cliArgs("snapshot-delete", volArgs("volume", v), []string{"--name", "daily", "--request-id", "kept"}) + code, out, _ := runChunk(args...) + if code != chunkExitFailed || chunkErrorOut(t, out).Code != "snapshot_generation_unavailable" || !chunkErrorOut(t, out).Retryable { + t.Fatalf("legacy target admitted: %d %s", code, out) + } + cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI) + st, _ := cat.Store(v) + h, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + snap := h.Snapshots["daily"] + snap.Gen = h.Gen + 1 + h.Version = layout.HeadVersion1 + h.Snapshots["daily"] = snap + if err = st.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil { + t.Fatal(err) + } + code, out, _ = runChunk(append(args, "--no-wait")...) + if code != 0 { + t.Fatalf("admission: %d %s", code, out) + } + changed := cliArgs("snapshot-delete", volArgs("volume", v), []string{"--name", "other", "--request-id", "kept"}) + code, out, _ = runChunk(changed...) + if code != chunkExitFailed || chunkErrorOut(t, out).Code != "operation_intent_conflict" || chunkErrorOut(t, out).Retryable { + t.Fatalf("changed intent accepted: %d %s", code, out) + } + h, _, err = st.ReadHead(ctx) + if err != nil || h.Snapshots["daily"].Gen != snap.Gen { + t.Fatalf("changed intent wrote HEAD: %+v %v", h, err) + } +} + +func TestSnapshotDeletePublicInitiallyAbsentIsRetainedRefusal(t *testing.T) { + ctx := context.Background() + mem := newMemChunkStore() + useMemChunkStore(t, mem) + v := cliVolume(t, mem, "v1", "daily") + cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI) + st, _ := cat.Store(v) + h, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + snap := h.Snapshots["daily"] + snap.Gen = h.Gen + 1 + h.Version = layout.HeadVersion1 + h.Snapshots["daily"] = snap + if err = st.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil { + t.Fatal(err) + } + args := cliArgs("snapshot-delete", volArgs("volume", v), []string{"--name", "absent", "--request-id", "missing-delete", "--no-wait"}) + code, out, _ := runChunk(args...) + if code != chunkExitFailed || chunkErrorOut(t, out).Code != "not_found" { + t.Fatalf("absence reported accepted: %d %s", code, out) + } + op, found, err := st.ReadSnapshotOperation(ctx, "missing-delete", "delete") + if err != nil || !found || op.State != "refused" || *op.TargetGeneration != 0 { + t.Fatalf("absence not retained: %+v %v", op, err) + } +} + +func TestSnapshotDeletePublicAfterV11CommitStampsEveryIncarnation(t *testing.T) { + for _, snapshot := range []string{"modern", ""} { + t.Run("snapshot="+snapshot, func(t *testing.T) { + ctx := context.Background() + mem := newMemChunkStore() + useMemChunkStore(t, mem) + v := cliVolume(t, mem, "v1", "legacy-one") + addSnapshot(t, mem, v, "legacy-two", layout.SnapshotMeta{}, "legacy-second", 2) + cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI) + st, _ := cat.Store(v) + h, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + reader, _ := layout.NewReader(defaultChunkPathCLI, v.Dir(), st.Fetch) + image, err := reader.Open(ctx, *h.Current) + if err != nil { + t.Fatal(err) + } + ref, _, err := image.Resolve(ctx, 1) + if err != nil { + t.Fatal(err) + } + entries := map[uint64]layout.Ref{1: ref} + me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + begun, err := layout.RunBegin(ctx, st, me, "modern-cut") + if err != nil { + t.Fatal(err) + } + root, segments, _ := layout.Build(entries) + rn, rb, _ := layout.NameRoot(root) + objects := map[string][]byte{rn.Path(): rb} + for name, data := range segments { + objects[name.Path()] = data + } + for name, data := range objects { + if err := layout.EnsureObject(ctx, st, name, data, "modern-cut"); err != nil { + t.Fatal(err) + } + } + // A v1.1 holder commits at its attach level: a new cluster's 1. + committed, err := layout.RunCommit(layout.WithFormatLevel(ctx, 1), st, st, v.Name, me, layout.CommitRequest{Session: "modern-cut", Prev: entries, Next: entries, Position: 3, Snapshot: snapshot, V11: true}, layout.CauseCommit) + if err != nil { + t.Fatal(err) + } + for name, entry := range committed.Snapshots { + if entry.Gen != begun.Gen+1 { + t.Fatalf("snapshot %s generation=%d want=%d", name, entry.Gen, begun.Gen+1) + } + args := cliArgs("snapshot-delete", volArgs("volume", v), []string{"--name", name, "--request-id", "delete-" + name}) + code, out, logs := runChunk(args...) + if code != 0 { + t.Fatalf("delete %s: code=%d %s %s", name, code, out, logs) + } + if _, err := layout.RunConsumeSnapshotDeleteIntent(ctx, st, reader); err != nil { + t.Fatal(err) + } + } + after, _, err := st.ReadHead(ctx) + if err != nil || len(after.Snapshots) != 0 { + t.Fatalf("snapshots remain: %+v err=%v", after, err) + } + }) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go new file mode 100644 index 0000000000..34a29a6d89 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -0,0 +1,405 @@ +package main + +// sw-block ops chunk: the walstore-chunk control plane (B9 W2 §0.1, §3). +// cut, snapshot and detach call a blockvolume's /chunk/* routes +// (--status-addr). snapshots, snapshot-delete and fork read and write the +// filer directly (--chunk-filer, --chunk-path), so they work while the +// volume is offline. Each prints the operation's JSON body on stdout. A +// failure prints the routes' error body {code,message,retryable} on stdout +// and a log line on stderr, and exits non-zero (2 for usage errors). + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/ops" +) + +const ( + chunkExitFailed = 1 + // chunkExitFindings: the command completed and found problems (verify). + chunkExitFindings = 3 + defaultChunkPathCLI = "/swblock/chunks" + chunkResponseLimit = 64 << 20 +) + +// dialChunkFiler opens the filer for the direct commands; tests replace it. +var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) { + c, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{FilerGRPC: addr}) + if err != nil { + return nil, nil, err + } + return c, c.Close, nil +} + +// checkSingleFiler is the start check of a command that writes chunk +// metadata: block metadata goes through exactly one filer, the +// same rule blockvolume enforces at start. Tests replace it. +var checkSingleFiler = func(ctx context.Context, f chunkstore.Filer) error { + if s, ok := f.(*chunkstore.SWFS); ok && s != nil { + return s.CheckSingleFiler(ctx) + } + return fmt.Errorf("%w: single-filer census requires a live SWFS client, got %T", chunkstore.ErrNotSingleFiler, f) +} + +// refuseUnlessSingleFiler runs the start check within the command's own +// timeout (a stalled filer or master cannot hold the command longer); exit +// >= 0 means refused. +func refuseUnlessSingleFiler(name string, f chunkstore.Filer, timeout time.Duration, stdout, stderr io.Writer) int { + return refuseUnlessSingleFilerWithin(context.Background(), name, f, timeout, stdout, stderr) +} + +// refuseUnlessSingleFilerWithin is refuseUnlessSingleFiler bounded by parent +// too (a caller's whole-pass deadline or cancellation); a refusal names the +// parent's cancellation cause. +func refuseUnlessSingleFilerWithin(parent context.Context, name string, f chunkstore.Filer, timeout time.Duration, stdout, stderr io.Writer) int { + ctx, cancel := context.WithTimeout(parent, timeout) + defer cancel() + err := checkSingleFiler(ctx, f) + if err != nil && parent.Err() != nil { + if c := context.Cause(parent); c != nil && !errors.Is(err, c) { + err = fmt.Errorf("%w (%v)", err, c) + } + } + switch { + case err == nil: + return -1 + case errors.Is(err, chunkstore.ErrNotSingleFiler): + return chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + default: + return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "single-filer start check: "+err.Error(), true) + } +} + +func runOpsChunk(args []string, stdout, stderr io.Writer) int { + if len(args) == 0 { + return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|detach|show|usage|verify|volume-delete|restore|release|retain", false) + } + switch args[0] { + case "cut": + return chunkCut(args[1:], stdout, stderr) + case "snapshot": + return chunkSnapshot(args[1:], stdout, stderr) + case "detach": + return chunkDetach(args[1:], stdout, stderr) + case "snapshots": + return chunkSnapshots(args[1:], stdout, stderr) + case "snapshot-delete": + return chunkSnapshotDelete(args[1:], stdout, stderr) + case "show": + return chunkShow(args[1:], stdout, stderr) + case "usage": + return chunkUsage(args[1:], stdout, stderr) + case "release": + return chunkRelease(args[1:], stdout, stderr) + case "retain": + return chunkRetain(args[1:], stdout, stderr) + case "verify": + return chunkVerify(args[1:], stdout, stderr) + case "volume-delete": + return chunkVolumeDelete(args[1:], stdout, stderr) + case "restore": + return chunkRestore(args[1:], stdout, stderr) + default: + return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, fmt.Sprintf("unknown subcommand %q", args[0]), false) + } +} + +// labelFlags collects repeated --label k=v. +type labelFlags map[string]string + +func (l labelFlags) String() string { return "" } + +func (l labelFlags) Set(v string) error { + k, val, ok := strings.Cut(v, "=") + if !ok || k == "" { + return fmt.Errorf("label %q: want key=value", v) + } + l[k] = val + return nil +} + +func newRequestID() string { + var b [16]byte + _, _ = rand.Read(b[:]) + return hex.EncodeToString(b[:]) +} + +func chunkFlagSet(name string, stderr io.Writer) *flag.FlagSet { + fs := flag.NewFlagSet("sw-block ops chunk "+name, flag.ContinueOnError) + fs.SetOutput(stderr) + return fs +} + +// chunkRequestBound is the server's bound on one /chunk/* request +// (chunkstore.DefaultOpDeadline). A var only so tests can shorten it. +var chunkRequestBound = chunkstore.DefaultOpDeadline + +// chunkPost sends one /chunk/* request and relays the outcome. The server +// bounds the operation by timeoutMs; the client waits a little longer. +func chunkPost(name, statusAddr, route string, timeout time.Duration, body map[string]any, stdout, stderr io.Writer, admission ...*snapshotCLIAdmission) int { + return chunkPostUntil(name, statusAddr, route, timeout, time.Now().Add(timeout+5*time.Second), body, stdout, stderr, admission...) +} + +// chunkPostUntil is chunkPost with the client's wait for the answer ending at +// waitUntil (chunkPostLoop keeps it inside the command's own --timeout). +func chunkPostUntil(name, statusAddr, route string, timeout time.Duration, waitUntil time.Time, body map[string]any, stdout, stderr io.Writer, admission ...*snapshotCLIAdmission) int { + base := statusAddr + if !strings.Contains(base, "://") { + base = "http://" + base + } + body["timeoutMs"] = timeout.Milliseconds() + data, err := json.Marshal(body) + if err != nil { + return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false) + } + ctx, cancel := context.WithDeadline(context.Background(), waitUntil) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(base, "/")+route, bytes.NewReader(data)) + if err != nil { + return chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + req.Header.Set("Content-Type", "application/json") + if len(admission) == 1 && admission[0] != nil { + req.Header.Set("Prefer", "respond-async") + } + resp, err := chunkHTTPClient.Do(req) + if err != nil { + return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "blockvolume not reachable: "+err.Error(), true) + } + defer resp.Body.Close() + out, err := io.ReadAll(io.LimitReader(resp.Body, chunkResponseLimit+1)) + if err != nil { + return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "read the response: "+err.Error(), true) + } + if int64(len(out)) > chunkResponseLimit { + // Refuse rather than relay a truncated body; the operation may have + // happened, and its result is what would be lost. + return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, + fmt.Sprintf("HTTP %d response exceeds %d bytes; not relaying a truncated body", resp.StatusCode, chunkResponseLimit), false) + } + if resp.StatusCode == http.StatusAccepted && len(admission) == 1 && admission[0] != nil { + a := admission[0] + if err := json.Unmarshal(out, &a.Answer); err != nil || a.Answer.ID != body["requestID"] || resp.Header.Get("Location") == "" { + return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, "invalid snapshot operation admission", false) + } + a.Raw = append([]byte(nil), out...) + a.Location = resp.Header.Get("Location") + a.Accepted = true + return 0 + } + if resp.StatusCode == http.StatusOK { + if err := writeAll(stdout, out); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk %s: write the result: %v\n", name, err) + return chunkExitFailed + } + return ops.VolumeStatusExitOK + } + var e chunkErrBody + if json.Unmarshal(out, &e) != nil || e.Code == "" { + return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(out))), false) + } + // The route's error body is already the CLI's error body: relay it. + fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, e.Code, e.Message) + if err := writeAll(stdout, out); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk %s: write the error: %v\n", name, err) + } + return chunkExitFailed +} + +func chunkCut(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("cut", stderr) + var ( + volumeID, statusAddr string + minLSN uint64 + timeout time.Duration + ) + fs.StringVar(&volumeID, "volume", "", "volume id") + fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") + fs.Uint64Var(&minLSN, "min-lsn", 0, "fail unless the cut reaches this LSN") + fs.DurationVar(&timeout, "timeout", 60*time.Second, chunkTimeoutHelp) + if err := fs.Parse(args); err != nil { + return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + if volumeID == "" || statusAddr == "" { + return chunkFail("cut", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false) + } + return chunkPostLoop("cut", statusAddr, "/chunk/cut", timeout, map[string]any{"volumeID": volumeID, "minLSN": minLSN}, stdout, stderr) +} + +func chunkSnapshot(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("snapshot", stderr) + var ( + volumeID, statusAddr, name, requestID, consistency, class string + expiresAtNs int64 + timeout, expires time.Duration + pin bool + noWait bool + ) + labels := labelFlags{} + fs.StringVar(&volumeID, "volume", "", "volume id") + fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") + fs.StringVar(&name, "name", "", "snapshot name") + fs.StringVar(&requestID, "request-id", "", "idempotency id; generated and printed when empty (reuse it to retry)") + fs.StringVar(&consistency, "consistency", "crash", "crash, or app when the guest was frozen by the caller") + fs.Int64Var(&expiresAtNs, "expires-at-ns", 0, "pins the snapshot until this time (unix ns); retention expires it afterwards") + fs.DurationVar(&expires, "expires", 0, "pins the snapshot for this long from now (sets --expires-at-ns)") + fs.StringVar(&class, "class", "", "retention class: semantic (an automatic checkpoint, expired by the policy) or pinned (kept until deleted)") + fs.BoolVar(&pin, "pin", false, "shorthand for --class pinned") + fs.BoolVar(&noWait, "no-wait", false, "return the durable snapshot operation handle without observing completion") + fs.Var(labels, "label", "key=value label (repeatable)") + fs.DurationVar(&timeout, "timeout", 60*time.Second, "admission and individual observation request bound; asynchronous observation has no overall deadline; interrupt or --no-wait preserves the operation ID for resume") + if err := fs.Parse(args); err != nil { + return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + if volumeID == "" || statusAddr == "" || name == "" { + return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume, --status-addr and --name are required", false) + } + if pin { + if class != "" && class != layout.ClassPinned { + return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--pin conflicts with --class "+class, false) + } + class = layout.ClassPinned + } + if expires < 0 || expires > 0 && expiresAtNs != 0 { + return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--expires must be positive and does not combine with --expires-at-ns", false) + } + if expires > 0 { + expiresAtNs = time.Now().Add(expires).UnixNano() + } + if requestID == "" { + requestID = newRequestID() + fmt.Fprintf(stderr, "sw-block ops chunk snapshot: request id %s (reuse it to retry)\n", requestID) + } + body := map[string]any{"volumeID": volumeID, "name": name, + "requestID": requestID, "labels": map[string]string(labels), "consistency": consistency, "expiresAtNs": expiresAtNs} + if class != "" { + body["class"] = class // only when set: the request otherwise keeps its spec fields + } + return chunkObserveSnapshot(statusAddr, timeout, body, noWait, stdout, stderr) +} + +func chunkDetach(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("detach", stderr) + var ( + volumeID, statusAddr string + timeout time.Duration + plain, frozen, allowOverBudget bool + freezeStartedAtNs int64 + ) + fs.StringVar(&volumeID, "volume", "", "volume id") + fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") + fs.DurationVar(&timeout, "timeout", 120*time.Second, chunkDetachTimeoutHelp) + fs.BoolVar(&plain, "plain", false, "seal an idle volume without pre-copy; prints JSON headGen as sealed HEAD generation on stderr") + fs.BoolVar(&frozen, "frozen", false, "not supported in this release: the server refuses a frozen detach (frozen_detach_unsupported)") + fs.Int64Var(&freezeStartedAtNs, "freeze-started-at-ns", 0, "not supported in this release; only valid with --frozen") + fs.BoolVar(&allowOverBudget, "allow-over-budget", false, "not supported in this release; only valid with --frozen") + if err := fs.Parse(args); err != nil { + return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + if volumeID == "" || statusAddr == "" { + return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false) + } + // M5 PlainStop -> Quiesce, INV-CUT-PLAIN-DETACH-001: an idle seal has + // its own finite caller bound and cannot encode frozen policy fields. + if plain && (timeout <= 0 || frozen || freezeStartedAtNs != 0 || allowOverBudget || fs.NArg() != 0) { + return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--plain requires positive --timeout, no extra arguments and no frozen options", false) + } + if (frozen && freezeStartedAtNs <= 0) || (!frozen && (freezeStartedAtNs != 0 || allowOverBudget)) { + return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--frozen requires --freeze-started-at-ns; --allow-over-budget requires --frozen", false) + } + body := map[string]any{"volumeID": volumeID} + if plain { + body["plain"] = true + return chunkPlainDetachPost(statusAddr, volumeID, timeout, body, stdout, stderr) + } + if frozen { + body["frozen"] = true + body["freezeStartedAtNs"] = freezeStartedAtNs + if allowOverBudget { + body["allowOverBudget"] = true + } + } + return chunkPostLoop("detach", statusAddr, "/chunk/detach", timeout, body, stdout, stderr) +} + +// chunkResult prints v as JSON, or err as ": ". +func chunkResult(name string, v any, err error, stdout, stderr io.Writer) int { + if err != nil { + var ce *chunkstore.CatalogError + switch { + case errors.As(err, &ce): + return chunkFail(name, stdout, stderr, chunkExitFailed, ce.Code, ce.Detail(), ce.Retryable) + case errors.Is(err, context.DeadlineExceeded): + return chunkFail(name, stdout, stderr, chunkExitFailed, chunkstore.CodeDeadlineExceeded, err.Error(), true) + case layoutCode(err) != "": + return chunkFail(name, stdout, stderr, chunkExitFailed, layoutCode(err), err.Error(), errors.Is(err, layout.ErrPrecondition) || errors.Is(err, layout.ErrQueueFull)) + default: + return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false) + } + } + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(v); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk %s: %v\n", name, err) + return chunkExitFailed + } + if err := writeAll(stdout, buf.Bytes()); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk %s: write the result: %v\n", name, err) + return chunkExitFailed + } + return ops.VolumeStatusExitOK +} + +// CLI-side error codes, the same as the routes' (B9 §2.2 and the rulings +// of 2026-11-15). +const ( + codeBadRequestCLI = "bad_request" + codeInternalCLI = "internal" + codeUnavailableCLI = "remote_unavailable" +) + +type chunkErrBody struct { + Code string `json:"code"` + Message string `json:"message"` + Retryable bool `json:"retryable"` +} + +// chunkFail reports a failure (B9 W2 appendix): the error body +// {code,message,retryable} on stdout, as the routes answer it, a log line on +// stderr, and the exit code. The message does not repeat the code. +func chunkFail(name string, stdout, stderr io.Writer, exit int, code, message string, retryable bool) int { + prefix := "sw-block ops chunk" + if name != "" { + prefix += " " + name + } + fmt.Fprintf(stderr, "%s: %s: %s\n", prefix, code, message) + body, _ := json.Marshal(chunkErrBody{Code: code, Message: message, Retryable: retryable}) + if err := writeAll(stdout, append(body, '\n')); err != nil { + fmt.Fprintf(stderr, "%s: write the error: %v\n", prefix, err) + } + return exit +} + +func chunkName(fs *flag.FlagSet) string { return strings.TrimPrefix(fs.Name(), "sw-block ops chunk ") } + +// writeAll writes p and fails on a failed or short write: a lost result +// must not exit 0. +func writeAll(w io.Writer, p []byte) error { + n, err := w.Write(p) + if err == nil && n != len(p) { + err = io.ErrShortWrite + } + return err +} diff --git a/seaweed-block/cmd/sw-block/chunk_b.go b/seaweed-block/cmd/sw-block/chunk_b.go new file mode 100644 index 0000000000..de258378ca --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_b.go @@ -0,0 +1,512 @@ +package main + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "flag" + "fmt" + "io" + "sort" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/retain" + "github.com/seaweedfs/seaweed-block/core/ops" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// restoreCreateRPC is the one master transition for a restore. Tests replace +// it with an in-process master; the CLI never creates a target in the filer. +var restoreCreateRPC = func(ctx context.Context, master string, req *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) { + conn, err := link.DialMasterFromEnv(master) + if err != nil { + return nil, err + } + defer conn.Close() + return control.NewLifecycleServiceClient(conn).CreateVolume(ctx, req) +} + +// bCatalog dials the filer and opens the volume catalog; a command that +// writes first passes the single-filer start check. It returns exit -1 on +// success, else the exit code after reporting. +func bCatalog(name, filer, base string, writes bool, timeout time.Duration, stdout, stderr io.Writer) (*chunkstore.BCatalog, func() error, int) { + if filer == "" { + return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false) + } + f, closeFn, err := dialChunkFiler(filer) + if err != nil { + return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + fail := func(msg string) (*chunkstore.BCatalog, func() error, int) { + _ = closeFn() + return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, msg, false) + } + if writes { + if exit := refuseUnlessSingleFiler(name, f, timeout, stdout, stderr); exit >= 0 { + _ = closeFn() + return nil, nil, exit + } + } + blobs, ok := f.(chunkstore.Blobs) + if !ok { + return fail("the filer client does not reach the volume servers") + } + cat, err := chunkstore.NewBCatalog(f, blobs, base) + if err != nil { + return fail(err.Error()) + } + return cat, closeFn, -1 +} + +// volumeFlags name a volume; its layout id is resolved through the +// master's volume record (never minted, never read from the filer). +type volumeFlags struct { + name string + cmd *bCommand +} + +// resolveVolumeID resolves a volume name to its layout id at the master. +// Tests replace it. +var resolveVolumeID = func(ctx context.Context, master, name string) (layout.VolumeID, error) { + conn, err := link.DialMasterFromEnv(master) + if err != nil { + return layout.VolumeID{}, err + } + defer conn.Close() + return lifecycleclient.ResolveVolume(ctx, control.NewLifecycleServiceClient(conn), name) +} + +func (c *bCommand) bindVolume(v *volumeFlags, flagName, what string) { + v.cmd = c + c.fs.StringVar(&v.name, flagName, "", what+" name") +} + +func (v volumeFlags) ref(flagName string) (chunkstore.VolumeRef, error) { + if v.name == "" { + return chunkstore.VolumeRef{}, errors.New("--" + flagName + " is required") + } + if v.cmd.master == "" { + return chunkstore.VolumeRef{}, errors.New("--master is required (it resolves the volume's layout id)") + } + ctx, cancel := context.WithTimeout(v.cmd.operationContext(), v.cmd.timeout) + defer cancel() + id, err := resolveVolumeID(ctx, v.cmd.master, v.name) + if err != nil { + return chunkstore.VolumeRef{}, fmt.Errorf("resolve --%s %q at the master: %w", flagName, v.name, err) + } + return chunkstore.VolumeRef{Name: v.name, ID: id}, nil +} + +// bCommand parses a catalog command's flags (with --chunk-filer, +// --chunk-path and --timeout) and opens the catalog. +type bCommand struct { + parent context.Context + growing bool // volume-delete bounds each sweep, not the whole growing operation + fs *flag.FlagSet + filer, base, master string + timeout time.Duration + stdout, stderr io.Writer +} + +func newBCommand(name string, timeout time.Duration, stdout, stderr io.Writer) *bCommand { + c := &bCommand{fs: chunkFlagSet(name, stderr), stdout: stdout, stderr: stderr} + c.fs.StringVar(&c.filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") + c.fs.StringVar(&c.base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") + c.fs.DurationVar(&c.timeout, "timeout", timeout, "filer timeout") + c.fs.StringVar(&c.master, "master", "", "blockmaster gRPC address (resolves each volume's layout id)") + return c +} + +// operationContext preserves the standalone commands' background context while +// allowing a composite read-only command to share its caller's deadline. +func (c *bCommand) operationContext() context.Context { + if c.parent != nil { + return c.parent + } + return context.Background() +} + +// run parses args, resolves the refs, opens the catalog and calls do. +func (c *bCommand) run(args []string, writes bool, refs func() error, do func(context.Context, *chunkstore.BCatalog) (any, error)) int { + name := chunkName(c.fs) + if err := c.fs.Parse(args); err != nil { + return chunkFail(name, c.stdout, c.stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + if err := refs(); err != nil { + if status.Code(err) == codes.NotFound { // the master does not know the volume + return chunkFail(name, c.stdout, c.stderr, chunkExitFailed, "volume_not_found", err.Error(), false) + } + return chunkFail(name, c.stdout, c.stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + cat, closeFn, exit := bCatalog(name, c.filer, c.base, writes, c.timeout, c.stdout, c.stderr) + if exit >= 0 { + return exit + } + defer closeFn() + ctx, cancel := context.WithCancel(c.operationContext()) + if !c.growing { + cancel() + ctx, cancel = context.WithTimeout(c.operationContext(), c.timeout) + } + defer cancel() + v, err := do(ctx, cat) + return chunkResult(name, v, err, c.stdout, c.stderr) +} + +// SnapshotEntry is one named snapshot of a volume's HEAD. +type SnapshotEntry struct { + Name string `json:"name"` + Root string `json:"root"` + Dependents []string `json:"dependents,omitempty"` +} + +// chunkSnapshots lists a volume's named snapshots, in name order. +func chunkSnapshots(args []string, stdout, stderr io.Writer) int { + c := newBCommand("snapshots", 30*time.Second, stdout, stderr) + var vol volumeFlags + var prefix string + c.bindVolume(&vol, "volume", "volume") + c.fs.StringVar(&prefix, "prefix", "", "only names with this prefix") + var ref chunkstore.VolumeRef + return c.run(args, false, func() (err error) { ref, err = vol.ref("volume"); return err }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) { + h, found, err := cat.ReadHead(ctx, ref) + if err != nil { + return nil, err + } + if !found { + return nil, layout.ErrHeadAbsent + } + out := []SnapshotEntry{} + for n, s := range h.Snapshots { + if !strings.HasPrefix(n, prefix) { + continue + } + e := SnapshotEntry{Name: n, Root: s.Root.String()} + for _, d := range s.Dependents { + e.Dependents = append(e.Dependents, layout.VolumeDir(d.Target, d.TargetID)) + } + out = append(out, e) + } + sort.Slice(out, func(a, b int) bool { return out[a].Name < out[b].Name }) + return out, nil + }) +} + +// readClusterFormatLevel reads the cluster's format level from the master +// (a test replaces it). +var readClusterFormatLevel = clusterFormatLevel + +// snapshotDeleteFormatLevel is the cluster format level a snapshot delete +// runs at: the master's answer, or 0 (v1.0 semantics, fail closed) without a +// master or when it cannot be read. +func snapshotDeleteFormatLevel(ctx context.Context, master string, stderr io.Writer) uint8 { + if master == "" { + return 0 + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + level, err := readClusterFormatLevel(ctx, master) + if err != nil { + fmt.Fprintf(stderr, "snapshot-delete: cluster format level unavailable (%v); running at level 0\n", err) + return 0 + } + if level > 1 { + level = 1 + } + return uint8(level) +} + +// newSnapshotDeleteRequestID is a fresh operation id, made once per +// invocation of snapshot-delete without --request-id. +func newSnapshotDeleteRequestID() (string, error) { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return "", err + } + return "cli-" + hex.EncodeToString(b[:]), nil +} + +// chunkSnapshotDelete removes a named snapshot; refused while a restore +// target depends on it. The route follows the HEAD's version at any format +// level: on a version-0 HEAD it is v1.0's name-only delete, chosen before +// any operation record is written (and as retry-unsafe as in v1.0). On a +// version-1 HEAD it is an operation delete: under --request-id, or else +// under an id made once +// for this invocation and printed for resume, with the incarnation it +// captured (name@gen); --gen pins that incarnation and always takes the +// operation route. Retries inside one invocation keep its id and its +// incarnation; a new invocation resolves the name again. Every HEAD write +// runs at the cluster's level (layout.WithFormatLevel). +func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int { + c := newBCommand("snapshot-delete", 30*time.Second, stdout, stderr) + var vol volumeFlags + var name, requestID, autoID string + var noWait bool + var pin uint64 + c.bindVolume(&vol, "volume", "volume") + c.fs.StringVar(&name, "name", "", "snapshot name") + c.fs.StringVar(&requestID, "request-id", "", "operation id for snapshot deletion; reuse on retry (made once per invocation when omitted)") + c.fs.Uint64Var(&pin, "gen", 0, "delete only this incarnation of the name (its publishing generation, shown as name@gen); refused if the name holds another") + c.fs.BoolVar(&noWait, "no-wait", false, "persist the delete operation without executing it; requires --request-id") + var ref chunkstore.VolumeRef + return c.run(args, true, func() (err error) { + if name == "" { + return errors.New("--name is required") + } + if noWait && requestID == "" { + return errors.New("--no-wait requires --request-id") + } + // An explicit --gen names one incarnation: 0 names none, and is + // refused here, before any read or write (it is not "no pin"). + explicitGen := false + c.fs.Visit(func(f *flag.Flag) { explicitGen = explicitGen || f.Name == "gen" }) + if explicitGen && pin == 0 { + return errors.New("--gen must name a publishing generation (name@gen, >= 1)") + } + if requestID == "" { + if autoID, err = newSnapshotDeleteRequestID(); err != nil { + return err + } + } + ref, err = vol.ref("volume") + return err + }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) { + level := snapshotDeleteFormatLevel(ctx, c.master, stderr) + ctx = layout.WithFormatLevel(ctx, level) + id := requestID + if id == "" && pin == 0 { + st, err := cat.Store(ref) + if err != nil { + return nil, err + } + h, found, err := st.ReadHead(ctx) + if err != nil { + return nil, err + } + if chunkstore.SnapshotDeleteByNameIsV10(h, found) { + if _, err := cat.DeleteSnapshot(ctx, ref, name); err != nil { + return nil, err + } + return map[string]string{"volume": ref.Dir(), "name": name, "state": "absent"}, nil + } + } + if id == "" { + id = autoID + } + return chunkAdmitCatalogSnapshotDelete(ctx, cat, ref, id, name, pin, noWait, stderr) + }) +} + +// chunkShow prints a volume's VOLUME record and HEAD. +func chunkShow(args []string, stdout, stderr io.Writer) int { + return chunkShowContext(context.Background(), args, stdout, stderr) +} + +func chunkShowContext(ctx context.Context, args []string, stdout, stderr io.Writer) int { + c := newBCommand("show", 30*time.Second, stdout, stderr) + c.parent = ctx + var vol volumeFlags + c.bindVolume(&vol, "volume", "volume") + var ref chunkstore.VolumeRef + return c.run(args, false, func() (err error) { ref, err = vol.ref("volume"); return err }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) { + s, err := cat.Store(ref) + if err != nil { + return nil, err + } + body := struct { + Volume *layout.Volume `json:"volume"` + Head *layout.Head `json:"head"` + }{} + if v, ok, err := s.ReadVolumeRecord(ctx); err != nil { + return nil, err + } else if ok { + body.Volume = &v + } + if h, ok, err := s.ReadHead(ctx); err != nil { + return nil, err + } else if ok { + body.Head = &h + } + return body, nil + }) +} + +// chunkUsage prints a volume's snapshots, dependents and the chunks its +// current image names. +func chunkUsage(args []string, stdout, stderr io.Writer) int { + c := newBCommand("usage", 60*time.Second, stdout, stderr) + var vol volumeFlags + c.bindVolume(&vol, "volume", "volume") + var ref chunkstore.VolumeRef + return c.run(args, false, func() (err error) { ref, err = vol.ref("volume"); return err }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) { + return cat.Usage(ctx, ref) + }) +} + +// chunkRestore creates a restore target from a source snapshot: the +// target reads the snapshot's chunks from the source's pool until its own +// writes replace them; the snapshot cannot be deleted while it depends on +// it. The target's layout id comes from its master record. +func chunkRestore(args []string, stdout, stderr io.Writer) int { + c := newBCommand("restore", 6*time.Minute, stdout, stderr) + var source, target, snapshot, requestID string + c.fs.StringVar(&source, "source", "", "source volume name") + c.fs.StringVar(&target, "target", "", "new volume name") + c.fs.StringVar(&snapshot, "snapshot", "", "source snapshot name") + c.fs.StringVar(&requestID, "request-id", "", "stable identity for retries of this restore") + if err := c.fs.Parse(args); err != nil { + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + if source == "" || target == "" || snapshot == "" || c.master == "" || source == target { + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--source, --target, --snapshot and --master are required; source and target must differ", false) + } + if requestID == "" { + sum := sha256.Sum256([]byte(target + "\x00" + source + "\x00" + snapshot)) + requestID = "restore-" + hex.EncodeToString(sum[:16]) + } + ctx, cancel := context.WithTimeout(context.Background(), c.timeout) + defer cancel() + resp, err := restoreCreateRPC(ctx, c.master, &control.CreateVolumeRequest{ + VolumeId: target, SourceVolume: source, SourceSnapshot: snapshot, CreateRequestId: requestID, + }) + if err != nil { + switch status.Code(err) { + case codes.NotFound: + return chunkFail("restore", stdout, stderr, chunkExitFailed, "snapshot_not_found", err.Error(), false) + case codes.AlreadyExists: + return chunkFail("restore", stdout, stderr, chunkExitFailed, "target_exists", err.Error(), false) + case codes.InvalidArgument: + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + case codes.FailedPrecondition: + if lifecycleclient.Reason(err) == lifecycleclient.ReasonRestoreSourceNotOwn { + return chunkFail("restore", stdout, stderr, chunkExitFailed, layoutCode(layout.ErrForeignSource), err.Error(), false) + } + return chunkFail("restore", stdout, stderr, chunkExitFailed, "not_admitted", err.Error(), false) + case codes.Unavailable, codes.DeadlineExceeded: + return chunkFail("restore", stdout, stderr, chunkExitFailed, codeUnavailableCLI, err.Error(), true) + default: + return chunkResult("restore", nil, err, stdout, stderr) + } + } + if resp.GetVolumeId() != target || !resp.GetStoreReady() { + return chunkFail("restore", stdout, stderr, chunkExitFailed, codeUnavailableCLI, "master did not confirm the restored target is store-ready", true) + } + id, err := layout.ParseVolumeID(resp.GetLayoutId()) + if err != nil { + return chunkResult("restore", nil, err, stdout, stderr) + } + return chunkResult("restore", map[string]string{"source": source, "snapshot": snapshot, "target": (chunkstore.VolumeRef{Name: target, ID: id}).Dir(), "request_id": requestID}, nil, stdout, stderr) +} + +// chunkRelease removes a restore target from its source snapshot's +// dependents once the target is deleted or no longer names the source's +// chunks; a target without HEAD (a restore that never finished) is +// tombstoned first so it can never be created later. +func chunkRelease(args []string, stdout, stderr io.Writer) int { + c := newBCommand("release", 30*time.Second, stdout, stderr) + var src, tgt volumeFlags + c.bindVolume(&src, "source", "source volume") + c.bindVolume(&tgt, "target", "restore target") + var sref, tref chunkstore.VolumeRef + return c.run(args, true, func() (err error) { + if sref, err = src.ref("source"); err != nil { + return err + } + tref, err = tgt.ref("target") + return err + }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) { + if _, err := cat.ReleaseTarget(ctx, sref, tref); err != nil { + return nil, err + } + return map[string]string{"source": sref.Dir(), "target": tref.Dir(), "state": "released"}, nil + }) +} + +// layoutCode is the error code of a layout kernel refusal ("" for any +// other error); a lost conditional update is the one retryable code. +func layoutCode(err error) string { + for _, c := range []struct { + err error + code string + }{ + {layout.ErrQueueFull, chunkstore.CodeQueueFull}, + {layout.ErrNoSnapshot, "snapshot_not_found"}, + {layout.ErrSnapshotDeleteNeedsOperation, "snapshot_delete_requires_operation"}, + {layout.ErrHasDependents, "snapshot_has_dependents"}, + {layout.ErrForeignSource, "restore_source_not_own"}, + {layout.ErrHeadAbsent, "volume_not_found"}, + {layout.ErrExists, "target_exists"}, + {layout.ErrVolumeDeleting, "volume_deleting"}, + {layout.ErrHolderActive, "not_admitted"}, + {chunkstore.ErrNotAdmitted, "not_admitted"}, + {layout.ErrTargetLive, "target_live"}, + {layout.ErrIdentity, "identity_mismatch"}, + {layout.ErrGeometryMismatch, "geometry_mismatch"}, + {layout.ErrPrecondition, "conflict"}, + {retain.ErrInvalidPolicy, "invalid_policy"}, + } { + if errors.Is(err, c.err) { + return c.code + } + } + return "" +} + +// chunkRetain: sw-block ops chunk retain --volume v --master m +// --chunk-filer host:port [--dry-run] applies the volume's retention policy: +// it deletes the expired snapshots by the automatic snapshot delete, which +// refuses a pinned snapshot or one a restore target depends on. With +// --set-policy it stores the policy given by the --keep-* flags in the +// volume's RETENTION entry instead; a policy change applies from the next +// pass. +func chunkRetain(args []string, stdout, stderr io.Writer) int { + c := newBCommand("retain", 5*time.Minute, stdout, stderr) + var vol volumeFlags + var keepYounger time.Duration + var dryRun, setPolicy bool + var keepNewest, keepHourly, keepDaily, keepWeekly int + c.bindVolume(&vol, "volume", "volume") + c.fs.BoolVar(&dryRun, "dry-run", false, "list what would be deleted; write nothing") + c.fs.BoolVar(&setPolicy, "set-policy", false, "store the --keep-* policy on the volume instead of applying it") + c.fs.IntVar(&keepNewest, "keep-newest", retain.DefaultKeepNewest, "with --set-policy: keep the newest N unpinned snapshots") + c.fs.DurationVar(&keepYounger, "keep-younger", retain.DefaultKeepYounger, "with --set-policy: keep every snapshot younger than this") + c.fs.IntVar(&keepHourly, "keep-hourly", 0, "with --set-policy: keep the newest snapshot of each of the last N hours") + c.fs.IntVar(&keepDaily, "keep-daily", 0, "with --set-policy: keep the newest snapshot of each of the last N days") + c.fs.IntVar(&keepWeekly, "keep-weekly", 0, "with --set-policy: keep the newest snapshot of each of the last N weeks") + var ref chunkstore.VolumeRef + // The start check runs only for a pass that writes. + writes := true + for _, a := range args { + if a == "--dry-run" || a == "-dry-run" || a == "--dry-run=true" { + writes = false + } + } + return c.run(args, writes, func() (err error) { + if setPolicy && dryRun { + return errors.New("--set-policy and --dry-run do not combine") + } + ref, err = vol.ref("volume") + return err + }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) { + if setPolicy { + p := retain.Policy{KeepNewest: keepNewest, KeepYoungerNs: int64(keepYounger), KeepHourly: keepHourly, KeepDaily: keepDaily, KeepWeekly: keepWeekly} + if err := cat.SetRetention(ctx, ref, p); err != nil { + return nil, err + } + return map[string]any{"volume": ref.Dir(), "policy": p, "policySet": true}, nil + } + return cat.Retain(ctx, ref, chunkRetainNow(), dryRun) + }) +} + +// chunkRetainNow is the wall clock retention decides by. Tests replace it. +var chunkRetainNow = time.Now diff --git a/seaweed-block/cmd/sw-block/chunk_b_test.go b/seaweed-block/cmd/sw-block/chunk_b_test.go new file mode 100644 index 0000000000..f3ad364b5b --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_b_test.go @@ -0,0 +1,447 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "net" + "strings" + "sync" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// memChunkStore is a filer with its volume servers: entries in memory, +// needle payloads by fid. +type memChunkStore struct { + *chunkstore.MemFiler + mu sync.Mutex + blobs map[string][]byte +} + +func newMemChunkStore() *memChunkStore { + return &memChunkStore{MemFiler: chunkstore.NewMemFiler(), blobs: map[string][]byte{}} +} + +func (m *memChunkStore) Put(_ context.Context, data []byte) (string, error) { + m.mu.Lock() + defer m.mu.Unlock() + fid := fmt.Sprintf("1,%x", len(m.blobs)+1) + m.blobs[fid] = append([]byte(nil), data...) + return fid, nil +} + +func (m *memChunkStore) Get(_ context.Context, fid string) ([]byte, error) { + m.mu.Lock() + defer m.mu.Unlock() + b, ok := m.blobs[fid] + if !ok { + return nil, chunkstore.ErrBlobNotFound + } + return append([]byte(nil), b...), nil +} + +// testIDs is the master's volume records the commands resolve against: +// every volume a test names through volArgs. +var testIDs sync.Map + +// useMemChunkStore makes every ops chunk command dial store and resolve +// names against testIDs. +func useMemChunkStore(t *testing.T, store *memChunkStore) { + t.Helper() + assumeSingleFilerFixture(t) + prev, prevResolve, prevRestore, prevLevel := dialChunkFiler, resolveVolumeID, restoreCreateRPC, readClusterFormatLevel + readClusterFormatLevel = func(context.Context, string) (uint32, error) { return 0, nil } // a test sets its own level + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil } + resolveVolumeID = testResolve + restoreCreateRPC = func(ctx context.Context, _ string, req *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) { + sid, err := testResolve(ctx, "", req.GetSourceVolume()) + if err != nil { + return nil, err + } + tid, err := testResolve(ctx, "", req.GetVolumeId()) + if err != nil { + return nil, err + } + cat, err := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + if err != nil { + return nil, err + } + _, err = cat.Restore(ctx, chunkstore.VolumeRef{Name: req.GetSourceVolume(), ID: sid}, req.GetSourceSnapshot(), chunkstore.VolumeRef{Name: req.GetVolumeId(), ID: tid}) + if err != nil { + return nil, err + } + return &control.CreateVolumeResponse{VolumeId: req.GetVolumeId(), LayoutId: tid.String(), StoreReady: true}, nil + } + t.Cleanup(func() { + dialChunkFiler, resolveVolumeID, restoreCreateRPC, readClusterFormatLevel = prev, prevResolve, prevRestore, prevLevel + }) +} + +func testResolve(_ context.Context, _ string, name string) (layout.VolumeID, error) { + if id, ok := testIDs.Load(name); ok { + return id.(layout.VolumeID), nil + } + return layout.VolumeID{}, status.Error(codes.NotFound, "volume not found") +} + +type okLease struct{} + +func (okLease) OldLeaseEnded(context.Context, uint64) error { return nil } + +// cliVolume creates v with one chunk and a snapshot named snap of it, +// through the layout kernel's own steps. +func cliVolume(t *testing.T, store *memChunkStore, name, snap string) chunkstore.VolumeRef { + t.Helper() + ctx := context.Background() + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + v := chunkstore.VolumeRef{Name: name, ID: id} + cat, err := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + if _, err := cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + s, _ := cat.Store(v) + me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + if _, err := layout.Start(ctx, s, okLease{}, layout.HolderID{Epoch: 1, Holder: "s/r"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k", Fresh: true, CanStartFrom: anyStart}); err != nil { + t.Fatal(err) + } + if _, err := layout.RunBegin(ctx, s, me, "s1"); err != nil { + t.Fatal(err) + } + data := []byte("chunk of " + name) + ch := layout.NameChunk(1, data) + next := map[uint64]layout.Ref{1: {Owner: name, OwnerID: id, Chunk: ch}} + root, segs, _ := layout.Build(next) + rn, rb, _ := layout.NameRoot(root) + objs := map[string][]byte{ch.Path(): data, rn.Path(): rb} + for n, b := range segs { + objs[n.Path()] = b + } + for rel, b := range objs { + if err := layout.EnsureObject(ctx, s, rel, b, "s1"); err != nil { + t.Fatal(err) + } + } + if _, err := layout.RunCommit(ctx, s, s, name, me, layout.CommitRequest{Session: "s1", Next: next, Position: 1, Snapshot: snap}, layout.CauseCommit); err != nil { + t.Fatal(err) + } + return v +} + +func volArgs(flag string, v chunkstore.VolumeRef) []string { + testIDs.Store(v.Name, v.ID) + return []string{"--" + flag, v.Name} +} + +func cliArgs(cmd string, parts ...[]string) []string { + out := []string{cmd, "--chunk-filer", "filer:18888", "--master", "m:1"} + for _, p := range parts { + out = append(out, p...) + } + return out +} + +// The catalog commands on the layout: list, show, usage, restore, release +// refused while the target names the source, snapshot delete refused while +// depended on, and their error codes. +func TestOpsChunk_CatalogCommands(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + src := cliVolume(t, store, "src", "daily") + tid, _ := layout.NewVolumeID() + tgt := chunkstore.VolumeRef{Name: "t", ID: tid} + + code, out, errs := runChunk(cliArgs("snapshots", volArgs("volume", src))...) + var list []SnapshotEntry + if code != 0 || json.Unmarshal([]byte(out), &list) != nil || len(list) != 1 || list[0].Name != "daily" { + t.Fatalf("snapshots: %d %q %q", code, out, errs) + } + if code, out, _ := runChunk(cliArgs("show", volArgs("volume", src))...); code != 0 || !strings.Contains(out, `"Name":"src"`) || !strings.Contains(out, `"Epoch":1`) { + t.Fatalf("show: %d %q", code, out) + } + if code, out, errs := runChunk(cliArgs("restore", volArgs("source", src), volArgs("target", tgt), []string{"--snapshot", "daily"})...); code != 0 || !strings.Contains(out, tgt.Dir()) { + t.Fatalf("restore: %d %q %q", code, out, errs) + } + if code, out, _ := runChunk(cliArgs("usage", volArgs("volume", tgt))...); code != 0 || !strings.Contains(out, `"foreign_chunks":1`) { + t.Fatalf("target usage: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("snapshot-delete", volArgs("volume", src), []string{"--name", "daily"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "snapshot_has_dependents" { + t.Fatalf("delete a depended-on snapshot: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("release", volArgs("source", src), volArgs("target", tgt))...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "target_live" { + t.Fatalf("release of a target still naming the source: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("restore", volArgs("source", src), volArgs("target", tgt), []string{"--snapshot", "weekly"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "snapshot_not_found" { + t.Fatalf("restore of a missing snapshot: %d %q", code, out) + } + if code, out, _ := runChunk("snapshots", "--chunk-filer", "f:1", "--volume", "src"); code != 2 || !strings.Contains(out, "--master is required") { + t.Fatalf("snapshots without --master: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("snapshots", []string{"--volume", "unknown-to-the-master"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "volume_not_found" || !strings.Contains(out, "resolve --volume") { + t.Fatalf("snapshots of a volume the master does not know: %d %q", code, out) + } +} + +// fakeLifecycle is the blockmaster's delete authority: the reservation is +// refused while held (a live line); leaseAfterReserve grants a lease right +// after the reservation is committed (a grant racing the admission), which +// the master's check then reports; every call is recorded. +type fakeLifecycle struct { + control.UnimplementedLifecycleServiceServer + mu sync.Mutex + held bool + leaseAfterReserve bool + reserved, leased bool + calls []string +} + +func (f *fakeLifecycle) record(name string) { + f.mu.Lock() + defer f.mu.Unlock() + f.calls = append(f.calls, name) +} + +func (f *fakeLifecycle) ReserveVolumeDeletion(_ context.Context, r *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) { + f.record("reserve") + if f.held { + return nil, status.Error(codes.FailedPrecondition, "volume has a live authority line") + } + f.reserved = true + if f.leaseAfterReserve { + f.leased = true + } + return &control.MarkVolumeDeletingResponse{Known: true}, nil +} + +func (f *fakeLifecycle) CheckVolumeNoLiveLease(context.Context, *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) { + f.record("check") + if !f.reserved || f.leased { + return nil, status.Error(codes.FailedPrecondition, "a line of the volume holds a live lease") + } + return &control.MarkVolumeDeletingResponse{Known: true}, nil +} + +func startFakeLifecycle(t *testing.T, f *fakeLifecycle) string { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + control.RegisterLifecycleServiceServer(srv, f) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + return lis.Addr().String() +} + +// volume-delete: refused while the master holds the volume (nothing +// written); a volume whose snapshot has a dependent is refused and the +// permanent reservation retained; a restore target deletes and releases its source. +func TestOpsChunk_VolumeDeleteOnTheLayout(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + src := cliVolume(t, store, "src", "daily") + tid, _ := layout.NewVolumeID() + tgt := chunkstore.VolumeRef{Name: "t", ID: tid} + if code, out, errs := runChunk(cliArgs("restore", volArgs("source", src), volArgs("target", tgt), []string{"--snapshot", "daily"})...); code != 0 { + t.Fatalf("restore: %d %q %q", code, out, errs) + } + del := func(lc *fakeLifecycle, v chunkstore.VolumeRef) (int, string) { + addr := startFakeLifecycle(t, lc) + code, out, _ := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "r1"})...) + return code, out + } + objects := func(v chunkstore.VolumeRef) int { + cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + u, err := cat.Usage(context.Background(), v) + if err != nil { + return -1 + } + return u.OwnChunks + u.ForeignChunks + } + held := &fakeLifecycle{held: true} + if code, out := del(held, tgt); code != chunkExitFailed || chunkErrorOut(t, out).Code != "not_admitted" || strings.Join(held.calls, ",") != "reserve" { + t.Fatalf("delete of a held volume: %d %q calls %v", code, out, held.calls) + } + // A grant racing the reservation: the master's check between the HEAD + // read and the update refuses, and nothing is deleted. + race := &fakeLifecycle{leaseAfterReserve: true} + if code, out := del(race, tgt); code != chunkExitFailed || chunkErrorOut(t, out).Code != "not_admitted" || strings.Join(race.calls, ",") != "reserve,check" || objects(tgt) != 1 { + t.Fatalf("delete with a lease granted after the reservation: %d %q calls %v objects %d; want refused by the check, nothing deleted", code, out, race.calls, objects(tgt)) + } + if h, _, _ := func() (layout.Head, bool, error) { + cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + return cat.ReadHead(context.Background(), tgt) + }(); h.State != layout.StateLive { + t.Fatalf("HEAD after the refused delete: %s; want live", h.State) + } + if code, out := del(&fakeLifecycle{}, src); code != chunkExitFailed || chunkErrorOut(t, out).Code != "snapshot_has_dependents" { + t.Fatalf("delete of a depended-on source: %d %q", code, out) + } + ok := &fakeLifecycle{} + if code, out := del(ok, tgt); code != 0 || !strings.Contains(out, `"state":"deleted"`) || strings.Join(ok.calls, ",") != "reserve,check" { + t.Fatalf("delete of the target: %d %q calls %v", code, out, ok.calls) + } + if code, out, _ := runChunk(cliArgs("snapshot-delete", volArgs("volume", src), []string{"--name", "daily"})...); code != 0 { + t.Fatalf("delete the released snapshot: %d %q", code, out) + } +} + +// A volume never created: snapshots refuses volume_not_found, show prints +// a null head, volume-delete refuses before asking the master. +func TestOpsChunk_AbsentVolume(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + id, _ := layout.NewVolumeID() + v := chunkstore.VolumeRef{Name: "never", ID: id} + if code, out, _ := runChunk(cliArgs("snapshots", volArgs("volume", v))...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "volume_not_found" { + t.Fatalf("snapshots of an absent volume: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("snapshot-delete", volArgs("volume", v), []string{"--name", "daily"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "volume_not_found" { + t.Fatalf("snapshot-delete by name of an absent volume: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("show", volArgs("volume", v))...); code != 0 || !strings.Contains(out, `"head":null`) { + t.Fatalf("show of an absent volume: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("retain", volArgs("volume", v))...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "volume_not_found" { + t.Fatalf("retain of an absent volume: %d %q", code, out) + } + lc := &fakeLifecycle{} + addr := startFakeLifecycle(t, lc) + if code, out, _ := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "r"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "volume_not_found" || len(lc.calls) != 0 { + t.Fatalf("delete of an absent volume: %d %q calls %v; want volume_not_found before any admission", code, out, lc.calls) + } +} + +// addSnapshot names v's current image again as snapshot name (a new +// snapshot transaction with no new chunks). +func addSnapshot(t *testing.T, store *memChunkStore, v chunkstore.VolumeRef, name string, meta layout.SnapshotMeta, session string, position uint64) { + t.Helper() + ctx := context.Background() + cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + s, _ := cat.Store(v) + me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"} + h, _, _ := s.ReadHead(ctx) + r, _ := layout.NewReader(defaultChunkPathCLI, v.Dir(), s.Fetch) + img, err := r.Open(ctx, *h.Current) + if err != nil { + t.Fatal(err) + } + ref, _, _ := img.Resolve(ctx, 1) + m := map[uint64]layout.Ref{1: ref} + if _, err := layout.RunBegin(ctx, s, me, session); err != nil { + t.Fatal(err) + } + root, segs, _ := layout.Build(m) + rn, rb, _ := layout.NameRoot(root) + objs := map[string][]byte{rn.Path(): rb} + for n, b := range segs { + objs[n.Path()] = b + } + for rel, b := range objs { + if err := layout.EnsureObject(ctx, s, rel, b, session); err != nil { + t.Fatal(err) + } + } + if _, err := layout.RunCommit(ctx, s, s, v.Name, me, layout.CommitRequest{Session: session, Prev: m, Next: m, Position: position, Snapshot: name, Meta: meta}, layout.CauseCommit); err != nil { + t.Fatal(err) + } +} + +// retain stores a policy with --set-policy and applies it: the newest +// unpinned snapshots by creation time are kept, the expired ones deleted, +// a pinned one kept, one a restore target depends on refused and +// reported; --dry-run writes nothing. +func TestOpsChunk_Retain(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "v", "") + now := time.Unix(20_000_000, 0) + prevNow := chunkRetainNow + chunkRetainNow = func() time.Time { return now } + t.Cleanup(func() { chunkRetainNow = prevNow }) + for i, f := range []struct { + name string + hours int + class string + }{{"n1", 1, layout.ClassSemantic}, {"n2", 2, layout.ClassSemantic}, {"n3", 3, layout.ClassSemantic}, {"n4", 4, layout.ClassSemantic}, {"keep", 9, layout.ClassPinned}} { + addSnapshot(t, store, v, f.name, layout.SnapshotMeta{CreatedNs: now.Add(-time.Duration(f.hours) * time.Hour).UnixNano(), Class: f.class}, fmt.Sprintf("s%d", i+2), uint64(i+2)) + } + tid, _ := layout.NewVolumeID() + if code, out, errs := runChunk(cliArgs("restore", volArgs("source", v), volArgs("target", chunkstore.VolumeRef{Name: "t", ID: tid}), []string{"--snapshot", "n4"})...); code != 0 { + t.Fatalf("restore: %d %q %q", code, out, errs) + } + if code, out, errs := runChunk(cliArgs("retain", volArgs("volume", v), []string{"--set-policy", "--keep-newest", "2", "--keep-younger", "0s"})...); code != 0 || !strings.Contains(out, `"policySet":true`) { + t.Fatalf("set policy: %d %q %q", code, out, errs) + } + run := func(extra ...string) chunkstore.RetainResult { + t.Helper() + code, out, errs := runChunk(cliArgs("retain", volArgs("volume", v), extra)...) + var r chunkstore.RetainResult + if code != 0 || json.Unmarshal([]byte(out), &r) != nil { + t.Fatalf("retain %v: %d %q %q", extra, code, out, errs) + } + return r + } + if dry := run("--dry-run"); strings.Join(dry.Deleted, ",") != "n3,n4" { + t.Fatalf("dry run: %+v", dry) + } + got := run() + if strings.Join(got.Deleted, ",") != "n3" || strings.Join(got.Refused, ",") != "n4" { + t.Fatalf("retain: deleted %v refused %v; want n3 and n4 refused", got.Deleted, got.Refused) + } + code, out, _ := runChunk(cliArgs("snapshots", volArgs("volume", v))...) + var list []SnapshotEntry + if code != 0 || json.Unmarshal([]byte(out), &list) != nil || len(list) != 4 { + t.Fatalf("after retain: %d %q; want keep,n1,n2,n4", code, out) + } + if code, out, _ := runChunk(cliArgs("retain", volArgs("volume", v), []string{"--set-policy", "--dry-run"})...); code != 2 { + t.Fatalf("--set-policy with --dry-run: %d %q", code, out) + } + if code, out, _ := runChunk(cliArgs("retain", volArgs("volume", v), []string{"--set-policy", "--keep-newest", "-1"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "invalid_policy" { + t.Fatalf("negative policy: %d %q", code, out) + } +} + +func TestOpsChunkVolumeDeleteRequiresTheMastersLeaseProof(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "leased", "daily") + lc := &fakeLifecycle{leased: true} + addr := startFakeLifecycle(t, lc) + code, out, _ := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "delete-v"})...) + if code == 0 { + t.Fatalf("deleted a volume with live lease: %q calls=%v", out, lc.calls) + } + if got := strings.Join(lc.calls, ","); got != "reserve,check" { + t.Fatalf("authority path=%s", got) + } + cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + h, found, err := cat.ReadHead(context.Background(), v) + if err != nil || !found || h.State != layout.StateLive { + t.Fatalf("HEAD changed despite refused proof: %+v %v %v", h, found, err) + } +} + +// Catalog fixtures model one in-memory namespace; inject that census result +// explicitly. Production clients must perform the live SWFS group census. +func assumeSingleFilerFixture(t *testing.T) { + t.Helper() + prev := checkSingleFiler + checkSingleFiler = func(context.Context, chunkstore.Filer) error { return nil } + t.Cleanup(func() { checkSingleFiler = prev }) +} diff --git a/seaweed-block/cmd/sw-block/chunk_delete_authority_guard_test.go b/seaweed-block/cmd/sw-block/chunk_delete_authority_guard_test.go new file mode 100644 index 0000000000..e832c2956b --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_delete_authority_guard_test.go @@ -0,0 +1,53 @@ +package main + +import ( + "go/ast" + "go/parser" + "go/token" + "testing" +) + +// The operator must never replace the master's proof with local admission. +func TestChunkVolumeDeleteAuthorityRPCSites(t *testing.T) { + for _, tc := range []struct { + file string + want map[string]int + }{ + {"chunk_volume_delete.go", map[string]int{"ReserveVolumeDeletion": 1, "CheckVolumeNoLiveLease": 1, "DialMasterFromEnv": 1}}, + // resolveVolumeID reads the name binding; restoreCreateRPC makes the + // restore's one master CreateVolume call (TestOpsChunkRestoreUsesOnlyMasterCreate). + {"chunk_b.go", map[string]int{"DialMasterFromEnv": 2}}, + {"../../core/host/master/volume_delete_authority.go", map[string]int{"VolumeDeleteAuthority": 2, "Reserve": 1, "NoLiveLease": 1}}, + } { + f, err := parser.ParseFile(token.NewFileSet(), tc.file, nil, 0) + if err != nil { + t.Fatal(err) + } + got := map[string]int{} + ast.Inspect(f, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return true + } + switch sel.Sel.Name { + case "Dial", "DialMasterFromEnv", "ReserveVolumeDeletion", "CheckVolumeNoLiveLease", "MarkVolumeDeleting", "AbortVolumeDeleting", "CommitVolumeDeleting", "VolumeDeleteAuthority", "Reserve", "NoLiveLease": + got[sel.Sel.Name]++ + } + return true + }) + for site, n := range got { + if tc.want[site] != n { + t.Errorf("%s: authority site %s=%d, want %d", tc.file, site, n, tc.want[site]) + } + } + for site, n := range tc.want { + if got[site] != n { + t.Errorf("%s: missing authority site %s=%d, want %d", tc.file, site, got[site], n) + } + } + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_diag.go b/seaweed-block/cmd/sw-block/chunk_diag.go new file mode 100644 index 0000000000..04ff21fb09 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_diag.go @@ -0,0 +1,75 @@ +package main + +import ( + "io" + "sync" + "sync/atomic" + "time" +) + +// diagWriter is a command's stderr, best effort: Write never blocks. One +// goroutine owns the writes to the real stderr, in order; a line that finds +// the queue full is dropped. A slow or stuck stderr therefore delays neither +// the work, nor its answer on stdout, nor the exit. +// +// close (after the answer is on stdout) waits at most diagDrain for the queued +// lines; a writer still stuck then is abandoned, and nothing more is written +// by the command: later lines and the rest of the queue are dropped. All of +// the command's stderr goes through one diagWriter, so its writes never +// overlap, and a stderr need not be safe for concurrent use. +type diagWriter struct { + mu sync.Mutex // orders Write against close + closed bool + lines chan []byte + done chan struct{} + abandoned atomic.Bool +} + +const diagQueue = 64 + +var diagDrain = 200 * time.Millisecond + +func newDiagWriter(w io.Writer) *diagWriter { + d := &diagWriter{lines: make(chan []byte, diagQueue), done: make(chan struct{})} + go func() { + defer close(d.done) + for l := range d.lines { + if !d.abandoned.Load() { + _, _ = w.Write(l) + } + } + }() + return d +} + +// Write queues p, or drops it when the queue is full or the writer is closed; +// it reports every byte written either way (a diagnostic is never an error). +func (d *diagWriter) Write(p []byte) (int, error) { + d.mu.Lock() + defer d.mu.Unlock() + if !d.closed { + select { + case d.lines <- append([]byte(nil), p...): + default: + } + } + return len(p), nil +} + +// close takes no more lines, waits at most diagDrain for the queued ones, and +// then abandons a writer that is still stuck. +func (d *diagWriter) close() { + d.mu.Lock() + if !d.closed { + d.closed = true + close(d.lines) + } + d.mu.Unlock() + t := time.NewTimer(diagDrain) + defer t.Stop() + select { + case <-d.done: + case <-t.C: + d.abandoned.Store(true) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_frozen_test.go b/seaweed-block/cmd/sw-block/chunk_frozen_test.go new file mode 100644 index 0000000000..f2e30173b1 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_frozen_test.go @@ -0,0 +1,19 @@ +package main + +import ( + "testing" +) + +func TestOpsChunkFrozenDetachFlags(t *testing.T) { + srv, got := chunkServer(t, 200, `{"volumeID":"v1"}`) + code, _, errs := runChunk("detach", "--volume=v1", "--status-addr="+srv.URL, "--frozen", "--freeze-started-at-ns=1234567", "--allow-over-budget") + if code != 0 || len(*got) != 1 || (*got)[0].body["frozen"] != true || (*got)[0].body["freezeStartedAtNs"] != float64(1234567) || (*got)[0].body["allowOverBudget"] != true { + t.Fatalf("frozen request lost budget: %d %s %+v", code, errs, *got) + } + for _, flags := range [][]string{{"--frozen"}, {"--allow-over-budget"}, {"--freeze-started-at-ns=123"}} { + args := append([]string{"detach", "--volume=v1", "--status-addr=" + srv.URL}, flags...) + if code, _, _ := runChunk(args...); code == 0 || len(*got) != 1 { + t.Fatalf("invalid flags sent request: %v", flags) + } + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_loop.go b/seaweed-block/cmd/sw-block/chunk_loop.go new file mode 100644 index 0000000000..0de1b072bd --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_loop.go @@ -0,0 +1,214 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// chunkTimeoutHelp is the --timeout text of the commands that use chunkPostLoop. +const chunkTimeoutHelp = "operation bound; above the server's 5m bound on one request, requests are repeated with the same body (for a snapshot the same name) until one answers, a non-retryable refusal ends them, or this passes" + +// chunkDetachTimeoutHelp adds what a long bound means for a detach. +const chunkDetachTimeoutHelp = chunkTimeoutHelp + "; a detach stops guest I/O while it runs, and after an outcome_unknown answer until the holder settles it, so a long --timeout can mean a guest stop that long" + +var ( + // chunkHTTPClient is the one client of the /chunk/* requests and the progress reads. + chunkHTTPClient = http.DefaultClient + // The pause after a request the store ended early: it starts here and doubles to the cap. + // Vars only so tests can shorten them. + chunkPauseStart = time.Second + chunkPauseMax = 30 * time.Second +) + +// chunkCushion is how long the client waits past a request's own bound for +// its answer (5 s, as chunkPost; less when the bound is short, as in tests). +func chunkCushion() time.Duration { return min(5*time.Second, chunkRequestBound/4) } + +// chunkMinRequest is the shortest request the loop sends: with less time left +// it ends instead. +func chunkMinRequest() time.Duration { return min(time.Second, chunkRequestBound/2) } + +// chunkReadBound bounds one progress read, so a holder that holds the read +// cannot take a request's time (2 s; less when the bound is short, as in tests). +func chunkReadBound() time.Duration { return min(2*time.Second, chunkRequestBound/10) } + +// chunkPostLoop is the cut budget's request loop (v1.0.1): a cut, +// snapshot or detach whose work outlasts the server's bound on one request +// (chunkRequestBound) finishes across requests. Each request carries the same +// body; the server answers a snapshot name it already holds from HEAD, so a +// snapshot that committed during a timed-out request is found by the next one, +// not taken again. The holder keeps an unfinished cut's uploads between +// requests, so each request sends only what is missing. +// +// One deadline, now + timeout, bounds everything the loop does: each request's +// own bound and the client's wait for its answer end inside it, the progress +// read and the pause are cut at it, and a request is sent only while at least +// chunkMinRequest is left (never with a zero or negative bound). The loop ends +// on the first answer, on a non-retryable refusal, or at the deadline, and +// relays the answer it ends on as chunkPost relays one. +// +// Between requests it prints how the request ended and, when the holder +// answers GET /status/durable, the chunks it staged since the first request. +// A request that ended before its bound (the store refused at once) is +// followed by a pause, doubling to chunkPauseMax, so a store that is down is +// not asked in a busy loop. After an outcome_unknown detach the holder has +// stopped guest I/O until it settles the detach in the background; the line +// says so, and a repeat answers from the settled HEAD. A timeout within the +// bound sends exactly one request, as before. +func chunkPostLoop(name, statusAddr, route string, timeout time.Duration, body map[string]any, stdout, stderr io.Writer, admission ...*snapshotCLIAdmission) int { + if timeout <= 0 { // INV-CLI-CHUNK-LOOP-001: a non-positive --timeout is refused, never sent as the server's default + return chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--timeout must be positive", false) + } + if timeout <= chunkRequestBound { + return chunkPost(name, statusAddr, route, timeout, body, stdout, stderr, admission...) + } + deadline := time.Now().Add(timeout) + cushion := chunkCushion() + pause := chunkPauseStart + volumeID, _ := body["volumeID"].(string) + first, haveBase := chunkStats(statusAddr, volumeID, deadline) // StagedChunks counts from process start: report the change + base := first.StagedChunks + var ( + last chunkErrBody + lastCode int + lastOut, lastE bytes.Buffer + ) + relay := func(code int, out, errb *bytes.Buffer) int { + _, _ = stderr.Write(errb.Bytes()) + if err := writeAll(stdout, out.Bytes()); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk %s: write the result: %v\n", name, err) + return chunkExitFailed + } + return code + } + for n := 1; ; n++ { + per := min(chunkRequestBound, time.Until(deadline)-cushion) + if n == 1 && per < chunkMinRequest() { // not reachable with the bounded first read; never send a request without time for its work + return chunkFail(name, stdout, stderr, chunkExitFailed, codeBadRequestCLI, fmt.Sprintf("--timeout %s left no time for a request", timeout), false) + } + if per < chunkMinRequest() { + fmt.Fprintf(stderr, "sw-block ops chunk %s: request %d ended: %s; --timeout %s passed after %d requests\n", name, n-1, last.Code, timeout, n-1) + if name == "detach" && last.Code == chunkstore.CodeOutcomeUnknown { + fmt.Fprintf(stderr, "sw-block ops chunk %s: the volume stays stopped until the holder settles this detach; repeat the detach to read the settled answer\n", name) + } + return relay(lastCode, &lastOut, &lastE) + } + sent := time.Now() + var out, errb bytes.Buffer + // the client's wait never reaches past the deadline, however late after computing per the request is sent + code := chunkPostUntil(name, statusAddr, route, per, minTime(deadline, sent.Add(per+cushion)), body, &out, &errb, admission...) + var e chunkErrBody + // repeated only after a retryable or outcome_unknown answer (INV-CLI-CHUNK-LOOP-001) + retry := code != ops.VolumeStatusExitOK && json.Unmarshal(out.Bytes(), &e) == nil && e.Code != "" && + (e.Retryable || e.Code == chunkstore.CodeOutcomeUnknown) + if !retry { + return relay(code, &out, &errb) // an answer, or a refusal a repeat cannot change + } + last, lastCode = e, code + lastOut.Reset() + lastOut.Write(out.Bytes()) + lastE.Reset() + lastE.Write(errb.Bytes()) + took := time.Since(sent) + wait := time.Duration(0) + if took < per*9/10 { + wait = pause + pause = min(2*pause, chunkPauseMax) + } + stopped := "" + if name == "detach" && e.Code == chunkstore.CodeOutcomeUnknown { + stopped = "; the volume has stopped guest I/O until this detach settles" + } + fmt.Fprintf(stderr, "sw-block ops chunk %s: request %d ended: %s (%s) after %s%s; next request%s, %s left%s\n", + name, n, e.Code, chunkShort(e.Message), took.Round(time.Millisecond), stopped, waitNote(wait), + time.Until(deadline).Round(time.Second), chunkProgress(statusAddr, volumeID, base, haveBase, deadline)) + if d := min(wait, time.Until(deadline)); d > 0 { + time.Sleep(d) + } + } +} + +func waitNote(d time.Duration) string { + if d <= 0 { + return "" + } + return " in " + d.Round(time.Millisecond).String() +} + +func chunkShort(s string) string { + if s = strings.TrimSpace(s); len(s) > 160 { + return s[:160] + "..." + } + return s +} + +// chunkProgress is the progress part of a line: the chunks the holder staged +// since the first request (its counter runs from process start) and how many +// are dirty; empty when the holder does not answer before the deadline. +func chunkProgress(statusAddr, volumeID string, base uint64, haveBase bool, deadline time.Time) string { + s, ok := chunkStats(statusAddr, volumeID, deadline) + if !ok { + return "" + } + if !haveBase || s.StagedChunks < base { + return fmt.Sprintf(" (holder: %d chunks dirty)", s.DirtyChunks) + } + return fmt.Sprintf(" (holder: %d chunks staged since the first request, %d dirty)", s.StagedChunks-base, s.DirtyChunks) +} + +type chunkStagedStats struct { + StagedChunks uint64 + DirtyChunks int +} + +// chunkStats reads Volumes[0].Chunk.Stats from GET /status/durable?volume=, +// with the requests' own client, for at most chunkReadBound and never past deadline. +func chunkStats(statusAddr, volumeID string, deadline time.Time) (chunkStagedStats, bool) { + if volumeID == "" { + return chunkStagedStats{}, false + } + base := statusAddr + if !strings.Contains(base, "://") { + base = "http://" + base + } + ctx, cancel := context.WithDeadline(context.Background(), minTime(time.Now().Add(chunkReadBound()), deadline)) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(base, "/")+"/status/durable?volume="+url.QueryEscape(volumeID), nil) + if err != nil { + return chunkStagedStats{}, false + } + resp, err := chunkHTTPClient.Do(req) + if err != nil { + return chunkStagedStats{}, false + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return chunkStagedStats{}, false + } + var st struct { + Volumes []struct { + Chunk *struct{ Stats chunkStagedStats } + } + } + if json.NewDecoder(io.LimitReader(resp.Body, chunkResponseLimit)).Decode(&st) != nil || len(st.Volumes) == 0 || st.Volumes[0].Chunk == nil { + return chunkStagedStats{}, false + } + return st.Volumes[0].Chunk.Stats, true +} + +func minTime(a, b time.Time) time.Time { + if a.Before(b) { + return a + } + return b +} diff --git a/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go new file mode 100644 index 0000000000..99044cebdb --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go @@ -0,0 +1,37 @@ +package main + +import ( + "context" + "fmt" + "sync" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" +) + +type manifestFixtureFiler struct { + chunkstore.Filer + mu sync.Mutex + blobs map[string][]byte +} + +func newManifestFixtureFiler(f chunkstore.Filer) *manifestFixtureFiler { + return &manifestFixtureFiler{Filer: f, blobs: map[string][]byte{}} +} + +func (f *manifestFixtureFiler) Put(_ context.Context, b []byte) (string, error) { + f.mu.Lock() + defer f.mu.Unlock() + id := fmt.Sprintf("fixture-%d", len(f.blobs)) + f.blobs[id] = append([]byte(nil), b...) + return id, nil +} + +func (f *manifestFixtureFiler) Get(_ context.Context, id string) ([]byte, error) { + f.mu.Lock() + defer f.mu.Unlock() + b, ok := f.blobs[id] + if !ok { + return nil, fmt.Errorf("%w: %w", chunkstore.ErrBlobNotFound, chunkstore.ErrNotFound) + } + return append([]byte(nil), b...), nil +} diff --git a/seaweed-block/cmd/sw-block/chunk_output_test.go b/seaweed-block/cmd/sw-block/chunk_output_test.go new file mode 100644 index 0000000000..7badc1e765 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_output_test.go @@ -0,0 +1,80 @@ +package main + +// The CLI never exits 0 with its result lost (review of #116): an HTTP body +// over the limit is refused rather than truncated, and a failed or short +// write of the result fails the command. + +import ( + "bytes" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + +) + +type failWriter struct{} + +func (failWriter) Write([]byte) (int, error) { return 0, errors.New("stdout closed") } + +type shortWriter struct{} + +func (shortWriter) Write(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + return len(p) - 1, nil +} + +func sizedServer(t *testing.T, n int) *httptest.Server { + t.Helper() + body := bytes.Repeat([]byte("a"), n) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(body) + })) + t.Cleanup(srv.Close) + return srv +} + +func TestOpsChunk_OversizedResponseIsRefused(t *testing.T) { + var out, errb bytes.Buffer + code := run([]string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", sizedServer(t, chunkResponseLimit+1).URL}, &out, &errb) + if code != chunkExitFailed || out.Len() > 1024 || !strings.Contains(errb.String(), "exceeds") { + t.Fatalf("200 body one byte over the limit: exit %d, %d bytes on stdout, stderr %q; want a refusal, not the body", code, out.Len(), errb.String()) + } + if e := chunkErrorOut(t, out.String()); e.Code != "internal" { + t.Fatalf("200 body one byte over the limit: %+v, want the internal error body", e) + } + out.Reset() + errb.Reset() + if code := run([]string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", sizedServer(t, chunkResponseLimit).URL}, &out, &errb); code != 0 || out.Len() != chunkResponseLimit { + t.Fatalf("200 body at the limit: exit %d, %d bytes relayed, stderr %q; want it relayed whole", code, out.Len(), errb.String()) + } +} + +func TestOpsChunk_LostResultFailsTheCommand(t *testing.T) { + srv, _ := chunkServer(t, 200, `{"volumeID":"v1","cutLSN":9}`) + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "v1", "s1") + commands := map[string][]string{ + "cut (HTTP)": {"ops", "chunk", "cut", "--volume", "v1", "--status-addr", srv.URL}, + "snapshots (filer)": append([]string{"ops"}, append([]string{"chunk"}, cliArgs("snapshots", volArgs("volume", v))...)...), + } + for name, args := range commands { + for wname, w := range map[string]io.Writer{"failing": failWriter{}, "short": shortWriter{}} { + var errb bytes.Buffer + if code := run(args, w, &errb); code != chunkExitFailed || !strings.Contains(errb.String(), "write the result") { + t.Errorf("%s to a %s stdout: exit %d, stderr %q; want a failure", name, wname, code, errb.String()) + } + } + var out, errb bytes.Buffer + if code := run(args, &out, &errb); code != 0 || out.Len() == 0 { + t.Errorf("%s to a working stdout: exit %d, %q, stderr %q", name, code, out.String(), errb.String()) + } + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_plain.go b/seaweed-block/cmd/sw-block/chunk_plain.go new file mode 100644 index 0000000000..b8b38dcf73 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_plain.go @@ -0,0 +1,37 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// M5 PlainStop -> Quiesce, INV-CUT-PLAIN-DETACH-001. Keep stdout JSON +// unchanged; the separate human readout identifies the seal to the operator. +func chunkPlainDetachPost(addr, volume string, timeout time.Duration, body map[string]any, stdout, stderr io.Writer) int { + var out bytes.Buffer + code := chunkPostLoop("detach", addr, "/chunk/detach", timeout, body, &out, stderr) + if code != ops.VolumeStatusExitOK { + if err := writeAll(stdout, out.Bytes()); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk detach: write result: %v\n", err) + } + return code + } + var seal struct { + VolumeID string `json:"volumeID"` + HeadGen uint64 `json:"headGen"` + } + if err := json.Unmarshal(out.Bytes(), &seal); err != nil || seal.VolumeID != volume || seal.HeadGen == 0 { + return chunkFail("detach", stdout, stderr, chunkExitFailed, codeInternalCLI, "plain detach outcome unknown: reply has no matching volume and sealed HEAD generation", false) + } + if err := writeAll(stdout, out.Bytes()); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk detach: write result: %v\n", err) + return chunkExitFailed + } + fmt.Fprintf(stderr, "sealed HEAD generation: %d\n", seal.HeadGen) + return ops.VolumeStatusExitOK +} diff --git a/seaweed-block/cmd/sw-block/chunk_plain_test.go b/seaweed-block/cmd/sw-block/chunk_plain_test.go new file mode 100644 index 0000000000..09d9befd25 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_plain_test.go @@ -0,0 +1,52 @@ +package main + +import ( + "net/http" + "strings" + "testing" +) + +// M5 PlainStop -> Quiesce, INV-CUT-PLAIN-DETACH-001: encode the existing +// idle seal request; preserve JSON stdout for existing operator tooling. +func TestOpsChunkPlainDetachSendsTheExistingRequest(t *testing.T) { + const reply = `{"volumeID":"vol","headGen":11}` + srv, got := chunkServer(t, http.StatusOK, reply) + code, out, errOut := runChunk("detach", "--plain", "--volume", "vol", "--status-addr", srv.URL, "--timeout", "2s") + if code != 0 || out != reply || !strings.Contains(errOut, "sealed HEAD generation: 11\n") { + t.Fatalf("exit=%d stdout=%q stderr=%q", code, out, errOut) + } + if len(*got) != 1 || (*got)[0].path != "/chunk/detach" || (*got)[0].body["plain"] != true || (*got)[0].body["volumeID"] != "vol" || (*got)[0].body["timeoutMs"] != float64(2000) { + t.Fatalf("plain request=%+v", *got) + } + for _, key := range []string{"frozen", "freezeStartedAtNs", "allowOverBudget"} { + if _, ok := (*got)[0].body[key]; ok { + t.Fatalf("plain request contains %s", key) + } + } +} + +func TestOpsChunkPlainDetachRefusesInvalidMixBeforeHTTP(t *testing.T) { + srv, got := chunkServer(t, http.StatusOK, `{}`) + for _, extra := range [][]string{ + {"--frozen", "--freeze-started-at-ns", "1"}, {"--freeze-started-at-ns", "1"}, {"--allow-over-budget"}, + {"--timeout", "0s"}, {"--timeout", "-1s"}, {"unexpected"}, + } { + args := append([]string{"detach", "--plain", "--volume", "vol", "--status-addr", srv.URL}, extra...) + if code, _, _ := runChunk(args...); code != 2 || len(*got) != 0 { + t.Fatalf("%v: exit=%d requests=%d", extra, code, len(*got)) + } + } +} + +func TestOpsChunkPlainDetachPreservesTypedFailure(t *testing.T) { + for _, reason := range []string{"busy", "fenced", "outcome_unknown"} { + t.Run(reason, func(t *testing.T) { + reply := `{"code":"` + reason + `","message":"seal refused","retryable":true}` + srv, got := chunkServer(t, http.StatusConflict, reply) + code, out, errOut := runChunk("detach", "--plain", "--volume", "vol", "--status-addr", srv.URL) + if code != 1 || out != reply || len(*got) != 1 || strings.Contains(errOut, "sealed HEAD generation:") { + t.Fatalf("exit=%d stdout=%q stderr=%q requests=%d", code, out, errOut, len(*got)) + } + }) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_queue_test.go b/seaweed-block/cmd/sw-block/chunk_queue_test.go new file mode 100644 index 0000000000..cbf73de87e --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_queue_test.go @@ -0,0 +1,22 @@ +package main + +import ( + "bytes" + "fmt" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +func TestLayoutQueueFullHasItsOwnRetryableCode(t *testing.T) { + err := fmt.Errorf("publish: %w", layout.ErrQueueFull) + if got := layoutCode(err); got != "queue_full" { + t.Fatalf("code=%q, want queue_full", got) + } + var out, diag bytes.Buffer + exit := chunkResult("snapshot-delete", nil, err, &out, &diag) + body := chunkErrorOut(t, out.String()) + if exit != chunkExitFailed || body.Code != "queue_full" || !body.Retryable { + t.Fatalf("exit=%d body=%+v", exit, body) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_request_loop_test.go b/seaweed-block/cmd/sw-block/chunk_request_loop_test.go new file mode 100644 index 0000000000..88d60aad3f --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_request_loop_test.go @@ -0,0 +1,455 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "sync" + "testing" + "time" +) + +type scriptedReply struct { + status int + body string +} + +type postRecord struct { + at time.Time + body map[string]any +} + +// scriptedChunkServer answers the i-th POST with replies[i] (the last one repeats) after holding it for hold, records +// every POST and when it arrived, and answers GET /status/durable with status(n) for the n-th read (404 when nil). +type scripted struct { + replies []scriptedReply + hold time.Duration + status func(n int, volume string) (int, string, time.Duration) + + mu sync.Mutex + posts []postRecord + gets int +} + +func (s *scripted) start(t *testing.T) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + s.mu.Lock() + n := s.gets + s.gets++ + s.mu.Unlock() + if s.status == nil || r.URL.Path != "/status/durable" { + http.NotFound(w, r) + return + } + code, body, delay := s.status(n, r.URL.Query().Get("volume")) + select { + case <-time.After(delay): + case <-r.Context().Done(): + return + } + w.WriteHeader(code) + _, _ = io.WriteString(w, body) + return + } + b, _ := io.ReadAll(r.Body) + var m map[string]any + _ = json.Unmarshal(b, &m) + s.mu.Lock() + i := len(s.posts) + s.posts = append(s.posts, postRecord{at: time.Now(), body: m}) + s.mu.Unlock() + rep := s.replies[len(s.replies)-1] + if i < len(s.replies) { + rep = s.replies[i] + } + select { + case <-time.After(s.hold): + case <-r.Context().Done(): + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(rep.status) + _, _ = io.WriteString(w, rep.body) + })) + t.Cleanup(srv.Close) + return srv +} + +func (s *scripted) recorded() []postRecord { + s.mu.Lock() + defer s.mu.Unlock() + return append([]postRecord(nil), s.posts...) +} + +// shortLoop makes the per-request bound (the server's OpDeadline, 5 min in production) and the pause small for a test. +func shortLoop(t *testing.T, bound, pauseStart, pauseMax time.Duration) { + t.Helper() + ob, os, om := chunkRequestBound, chunkPauseStart, chunkPauseMax + chunkRequestBound, chunkPauseStart, chunkPauseMax = bound, pauseStart, pauseMax + t.Cleanup(func() { chunkRequestBound, chunkPauseStart, chunkPauseMax = ob, os, om }) +} + +const ( + timedOut = `{"code":"remote_unavailable","message":"storage: capture upload: storage: chunk remote unavailable","retryable":true}` + refused = `{"code":"snapshot_limit","message":"volume v1 holds the maximum number of snapshots","retryable":false}` + published = `{"volumeID":"v1","name":"s1","headGen":4,"headEpoch":1,"cutLSN":65536}` + // the holder's answers around a detach that ran out (core/host/volume chunkErrorCode) + detachUnknown = `{"code":"outcome_unknown","message":"durable: detach outcome unknown; I/O stays stopped: context deadline exceeded","retryable":true}` + detachAborted = `{"code":"detach_aborted","message":"durable: detach aborted; the volume keeps serving on this host","retryable":true}` + detachFenced = `{"code":"fenced","message":"HEAD belongs to a newer epoch or another holder","retryable":false}` + sealed = `{"volumeID":"v1","cutLSN":9,"headGen":5,"headEpoch":1,"lastWrittenLSN":9}` + cutUnknown = `{"code":"outcome_unknown","message":"storage: chunk HEAD CAS outcome unknown","retryable":true}` +) + +// The request loop: a snapshot whose work outlasts one request finishes across requests, every request carrying +// the same body. The server answers a name it already holds from HEAD (TestLayoutProviderSnapshotVolume in +// core/frontend/durable: a repeat of "daily" keeps the first CreatedNs), so a snapshot committed during a timed-out +// request is found by the next one, not taken again. +func TestChunkSnapshotRepeatsTimedOutRequestsWithTheSameBody(t *testing.T) { + shortLoop(t, 200*time.Millisecond, 20*time.Millisecond, 20*time.Millisecond) + s := &scripted{replies: []scriptedReply{{503, timedOut}, {503, timedOut}, {200, published}}} + srv := s.start(t) + code, out, errs := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", "rid-1", "--timeout", "5s") + if code != 0 || out != published { + t.Fatalf("exit %d stdout %q (want 0 and only the final answer) stderr %q", code, out, errs) + } + p := s.recorded() + if len(p) != 3 { + t.Fatalf("%d requests, want 3", len(p)) + } + for i, r := range p { + if r.body["name"] != "s1" || r.body["requestID"] != "rid-1" { + t.Fatalf("request %d: name %v request id %v, want s1 / rid-1 in every request", i+1, r.body["name"], r.body["requestID"]) + } + if ms, _ := r.body["timeoutMs"].(float64); ms <= 0 || ms > 200 { + t.Fatalf("request %d: timeoutMs %v, want 0 < t <= the per-request bound (200)", i+1, r.body["timeoutMs"]) + } + } + for _, want := range []string{"request 1 ended: remote_unavailable (storage: capture upload", "request 2 ended: remote_unavailable"} { + if !strings.Contains(errs, want) { + t.Fatalf("stderr %q: want %q", errs, want) + } + } + if strings.Contains(errs, "stopped guest I/O") { + t.Fatalf("stderr %q: a snapshot does not stop guest I/O", errs) + } +} + +// A generated request id is printed once, and every request of the loop carries exactly that id. +func TestChunkSnapshotLoopReusesTheGeneratedRequestID(t *testing.T) { + shortLoop(t, 200*time.Millisecond, 20*time.Millisecond, 20*time.Millisecond) + s := &scripted{replies: []scriptedReply{{503, timedOut}, {200, published}}} + srv := s.start(t) + code, _, errs := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--timeout", "5s") + if code != 0 { + t.Fatalf("exit %d: %q", code, errs) + } + m := regexp.MustCompile(`request id ([0-9a-f]{32}) `).FindAllStringSubmatch(errs, -1) + if len(m) != 1 { + t.Fatalf("stderr %q: the generated request id is printed %d times, want once", errs, len(m)) + } + p := s.recorded() + if len(p) != 2 { + t.Fatalf("%d requests, want 2", len(p)) + } + for i, r := range p { + if id, ok := r.body["requestID"].(string); !ok || id != m[0][1] { + t.Fatalf("request %d: requestID %#v, want the printed %s", i+1, r.body["requestID"], m[0][1]) + } + } +} + +// The loop ends on the first non-retryable refusal and relays it. +func TestChunkLoopStopsOnANonRetryableRefusal(t *testing.T) { + shortLoop(t, 200*time.Millisecond, 20*time.Millisecond, 20*time.Millisecond) + s := &scripted{replies: []scriptedReply{{409, refused}, {200, published}}} + srv := s.start(t) + code, out, _ := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", "rid-1", "--timeout", "5s") + if code == 0 || len(s.recorded()) != 1 || out != refused { + t.Fatalf("exit %d, %d requests, stdout %q: want one request and its refusal relayed", code, len(s.recorded()), out) + } +} + +// A --timeout within the per-request bound sends one request, as before the loop. +func TestChunkTimeoutWithinTheBoundSendsOneRequest(t *testing.T) { + shortLoop(t, 10*time.Second, 20*time.Millisecond, 20*time.Millisecond) + s := &scripted{replies: []scriptedReply{{503, timedOut}, {200, published}}} + srv := s.start(t) + code, out, _ := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", "rid-1", "--timeout", "2s") + if code == 0 || len(s.recorded()) != 1 || out != timedOut { + t.Fatalf("exit %d, %d requests, stdout %q: want exactly one request, as before", code, len(s.recorded()), out) + } + if ms := s.recorded()[0].body["timeoutMs"]; ms != float64(2000) { + t.Fatalf("timeoutMs %v, want 2000", ms) + } +} + +// runChunkWithin runs the command and fails the test if it has not returned within limit: a loop that misses its +// own --timeout fails here at once, not at the test binary's timeout. +func runChunkWithin(t *testing.T, limit time.Duration, args ...string) (int, string, string) { + t.Helper() + type res struct { + code int + out, err string + } + done := make(chan res, 1) + go func() { + c, o, e := runChunk(args...) + done <- res{c, o, e} + }() + select { + case r := <-done: + return r.code, r.out, r.err + case <-time.After(limit): + // join the command (bounded) before the earlier cleanups restore the package globals it reads; cleanups run + // last-registered first + t.Cleanup(func() { + select { + case <-done: + case <-time.After(10 * time.Second): + } + }) + t.Fatalf("the command did not return within %v: the loop does not end at its --timeout", limit) + return 0, "", "" + } +} + +// checkInsideT: no request starts after T, none carries a non-positive bound, and the command returns by T + slack. +func checkInsideT(t *testing.T, s *scripted, start time.Time, timeout, took time.Duration) { + t.Helper() + if took > timeout+300*time.Millisecond { + t.Fatalf("the command took %v for --timeout %v", took, timeout) + } + for i, r := range s.recorded() { + if at := r.at.Sub(start); at > timeout { + t.Fatalf("request %d started %v after the start, past --timeout %v", i+1, at, timeout) + } + if ms, _ := r.body["timeoutMs"].(float64); ms <= 0 { + t.Fatalf("request %d: timeoutMs %v, want a positive bound", i+1, r.body["timeoutMs"]) + } + } +} + +// The loop ends at --timeout, relays the last answer, and does not ask a store that refuses at once in a busy loop. +func TestChunkLoopEndsAtTheTimeout(t *testing.T) { + shortLoop(t, 100*time.Millisecond, 50*time.Millisecond, 50*time.Millisecond) + s := &scripted{replies: []scriptedReply{{503, timedOut}}} + srv := s.start(t) + start := time.Now() + code, out, errs := runChunkWithin(t, 5*time.Second, "snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", "rid-1", "--timeout", "500ms") + took := time.Since(start) + if code == 0 || out != timedOut || !strings.Contains(errs, "--timeout 500ms passed") { + t.Fatalf("exit %d stdout %q stderr %q: want the last answer relayed and the end named", code, out, errs) + } + checkInsideT(t, s, start, 500*time.Millisecond, took) + if n := len(s.recorded()); n < 2 || n > 11 { + t.Fatalf("%d requests in 500 ms with a 50 ms pause: want 2..11 (paused, not a busy loop)", n) + } +} + +// A progress read the holder does not answer cannot push a request past --timeout (it is cut at the deadline). +func TestChunkLoopHeldProgressReadSendsNoRequestAfterTheTimeout(t *testing.T) { + shortLoop(t, 100*time.Millisecond, 10*time.Millisecond, 10*time.Millisecond) + s := &scripted{replies: []scriptedReply{{503, timedOut}}, + status: func(int, string) (int, string, time.Duration) { return 200, `{}`, 3 * time.Second }} + srv := s.start(t) + start := time.Now() + code, out, _ := runChunkWithin(t, 5*time.Second, "snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", "rid-1", "--timeout", "500ms") + took := time.Since(start) + if code == 0 || out != timedOut { + t.Fatalf("exit %d stdout %q: want the last answer relayed", code, out) + } + checkInsideT(t, s, start, 500*time.Millisecond, took) +} + +// A holder that answers late cannot hold the command past --timeout: the client's wait for each answer (the bound +// plus a cushion) ends inside it. +func TestChunkLoopSlowAnswersAreBoundedByTheTimeout(t *testing.T) { + shortLoop(t, 200*time.Millisecond, 10*time.Millisecond, 10*time.Millisecond) + s := &scripted{replies: []scriptedReply{{503, timedOut}}, hold: 2 * time.Second} + srv := s.start(t) + start := time.Now() + code, _, errs := runChunkWithin(t, 5*time.Second, "snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", "rid-1", "--timeout", "600ms") + took := time.Since(start) + if code == 0 || !strings.Contains(errs, "--timeout 600ms passed") { + t.Fatalf("exit %d stderr %q: want the loop to end at --timeout", code, errs) + } + checkInsideT(t, s, start, 600*time.Millisecond, took) +} + +// The pause after an early end doubles up to its cap (a constant pause does not pass). +func TestChunkLoopPauseDoublesToItsCap(t *testing.T) { + shortLoop(t, 2*time.Second, 40*time.Millisecond, 160*time.Millisecond) + s := &scripted{replies: []scriptedReply{{503, timedOut}, {503, timedOut}, {503, timedOut}, {503, timedOut}, {503, timedOut}, {200, published}}} + srv := s.start(t) + if code, _, errs := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", "rid-1", "--timeout", "10s"); code != 0 { + t.Fatalf("exit %d: %q", code, errs) + } + p := s.recorded() + if len(p) != 6 { + t.Fatalf("%d requests, want 6", len(p)) + } + var gap []time.Duration + for i := 1; i < len(p); i++ { + gap = append(gap, p[i].at.Sub(p[i-1].at)) + } + // want about 40, 80, 160, 160, 160 ms + if !(gap[1] > gap[0]*3/2 && gap[2] > gap[1]*3/2) { + t.Fatalf("gaps %v: want the pause to double (40, 80, 160 ms)", gap) + } + if gap[3] > 240*time.Millisecond || gap[4] > 240*time.Millisecond || gap[3] < 120*time.Millisecond { + t.Fatalf("gaps %v: want the pause held at its 160 ms cap", gap) + } +} + +// Between requests the holder's staged chunks are reported as the change since the first request, read with the +// volume's id; a holder that does not answer the read (the other tests: 404) leaves the progress part out. +func TestChunkLoopReportsTheHolderProgressSinceTheFirstRequest(t *testing.T) { + shortLoop(t, 200*time.Millisecond, 10*time.Millisecond, 10*time.Millisecond) + staged := []uint64{1000, 1050, 1400} + var asked []string + var mu sync.Mutex + s := &scripted{replies: []scriptedReply{{503, timedOut}, {503, timedOut}, {200, published}}, + status: func(n int, volume string) (int, string, time.Duration) { + mu.Lock() + asked = append(asked, volume) + mu.Unlock() + v := staged[min(n, len(staged)-1)] + return 200, fmt.Sprintf(`{"VolumeID":"v1","Volumes":[{"Chunk":{"Stats":{"StagedChunks":%d,"DirtyChunks":7}}}]}`, v), 0 + }} + srv := s.start(t) + code, _, errs := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", "rid-1", "--timeout", "5s") + if code != 0 { + t.Fatalf("exit %d: %q", code, errs) + } + for _, want := range []string{"50 chunks staged since the first request, 7 dirty", "400 chunks staged since the first request, 7 dirty"} { + if !strings.Contains(errs, want) { + t.Fatalf("stderr %q: want %q", errs, want) + } + } + mu.Lock() + defer mu.Unlock() + for _, v := range asked { + if v != "v1" { + t.Fatalf("progress read for volume %q, want v1", v) + } + } +} + +// cut and the plain detach loop the same way; the sealed generation is printed once. +func TestChunkCutAndPlainDetachRepeatTimedOutRequests(t *testing.T) { + shortLoop(t, 200*time.Millisecond, 10*time.Millisecond, 10*time.Millisecond) + s := &scripted{replies: []scriptedReply{{503, cutUnknown}, {200, `{"volumeID":"v1","cutLSN":9}`}}} + srv := s.start(t) + code, out, errs := runChunk("cut", "--volume", "v1", "--status-addr", srv.URL, "--timeout", "5s") + if code != 0 || out != `{"volumeID":"v1","cutLSN":9}` || len(s.recorded()) != 2 { + t.Fatalf("cut: exit %d stdout %q stderr %q, %d requests", code, out, errs, len(s.recorded())) + } + if strings.Contains(errs, "stopped guest I/O") { + t.Fatalf("cut stderr %q: an outcome_unknown cut does not stop guest I/O", errs) + } + s2 := &scripted{replies: []scriptedReply{{503, timedOut}, {200, sealed}}} + srv2 := s2.start(t) + code, out, errs = runChunk("detach", "--plain", "--volume", "v1", "--status-addr", srv2.URL, "--timeout", "5s") + if code != 0 || out != sealed || len(s2.recorded()) != 2 { + t.Fatalf("plain detach: exit %d stdout %q stderr %q, %d requests", code, out, errs, len(s2.recorded())) + } + if n := strings.Count(errs, "sealed HEAD generation: 5"); n != 1 { + t.Fatalf("stderr %q: the sealed generation is printed %d times, want once", errs, n) + } +} + +// A detach that ends outcome_unknown has stopped guest I/O until the holder settles it in the background. The holder +// answers outcome_unknown again while it settles (detachVolume: h.settling), then from the settled HEAD: sealed (an +// applied detach repeats as its answer, TestChunkDetach_RepeatedDetachSettlesAppliedDetach), aborted (serving resumed; +// the next request detaches anew), or fenced (non-retryable). The loop says the volume is stopped, ends on the settled +// answer, and an already detached volume is a success. +func TestChunkDetachOutcomeUnknownSettles(t *testing.T) { + shortLoop(t, 200*time.Millisecond, 10*time.Millisecond, 10*time.Millisecond) + for _, tc := range []struct { + name string + replies []scriptedReply + code int + out string + }{ + {"applied", []scriptedReply{{503, detachUnknown}, {503, detachUnknown}, {200, sealed}}, 0, sealed}, + {"not published, then detached anew", []scriptedReply{{503, detachUnknown}, {503, detachUnknown}, {409, detachAborted}, {200, sealed}}, 0, sealed}, + {"fenced", []scriptedReply{{503, detachUnknown}, {409, detachFenced}}, chunkExitFailed, detachFenced}, + } { + t.Run(tc.name, func(t *testing.T) { + for _, plain := range []bool{false, true} { + s := &scripted{replies: tc.replies} + srv := s.start(t) + args := []string{"detach", "--volume", "v1", "--status-addr", srv.URL, "--timeout", "5s"} + if plain { + args = append(args, "--plain") + } + code, out, errs := runChunk(args...) + if code != tc.code || out != tc.out || len(s.recorded()) != len(tc.replies) { + t.Fatalf("plain=%v: exit %d stdout %q (want %d %q), %d requests (want %d); stderr %q", plain, code, out, tc.code, tc.out, len(s.recorded()), len(tc.replies), errs) + } + if !strings.Contains(errs, "request 1 ended: outcome_unknown") || !strings.Contains(errs, "the volume has stopped guest I/O until this detach settles") { + t.Fatalf("plain=%v stderr %q: want the stopped-I/O line after the unknown answer", plain, errs) + } + } + }) + } +} + +// A detach still unknown at --timeout says the volume stays stopped and how to read the settled answer. +func TestChunkDetachStillUnknownAtTheTimeoutSaysTheVolumeIsStopped(t *testing.T) { + shortLoop(t, 100*time.Millisecond, 50*time.Millisecond, 50*time.Millisecond) + s := &scripted{replies: []scriptedReply{{503, detachUnknown}}} + srv := s.start(t) + code, out, errs := runChunkWithin(t, 5*time.Second, "detach", "--volume", "v1", "--status-addr", srv.URL, "--timeout", "500ms") + if code == 0 || out != detachUnknown || !strings.Contains(errs, "the volume stays stopped until the holder settles this detach; repeat the detach") { + t.Fatalf("exit %d stdout %q stderr %q", code, out, errs) + } +} + +// INV-CLI-CHUNK-LOOP-001: an outcome_unknown answer is repeated even when it is not marked retryable. +func TestChunkLoopRepeatsAnOutcomeUnknownNotMarkedRetryable(t *testing.T) { + shortLoop(t, 200*time.Millisecond, 10*time.Millisecond, 10*time.Millisecond) + unknown := `{"code":"outcome_unknown","message":"storage: chunk HEAD CAS outcome unknown","retryable":false}` + s := &scripted{replies: []scriptedReply{{503, unknown}, {200, published}}} + srv := s.start(t) + code, out, errs := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", "rid-1", "--timeout", "5s") + if code != 0 || out != published || len(s.recorded()) != 2 { + t.Fatalf("exit %d stdout %q stderr %q, %d requests: want the unknown answer repeated and the second answer relayed", code, out, errs, len(s.recorded())) + } +} + +// INV-CLI-CHUNK-LOOP-001: a non-positive --timeout is refused before any request, for snapshot, cut and detach. +func TestChunkNonPositiveTimeoutIsRefused(t *testing.T) { + s := &scripted{replies: []scriptedReply{{200, published}}} + srv := s.start(t) + for _, cmd := range [][]string{ + {"snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", "rid-1"}, + {"cut", "--volume", "v1", "--status-addr", srv.URL}, + {"detach", "--volume", "v1", "--status-addr", srv.URL}, + } { + for _, tmo := range []string{"0s", "-1s"} { + code, out, _ := runChunk(append(cmd, "--timeout", tmo)...) + if code == 0 || !strings.Contains(out, `"code":"bad_request"`) { + t.Fatalf("%s --timeout %s: exit %d stdout %q, want a bad_request refusal", cmd[0], tmo, code, out) + } + } + } + if n := len(s.recorded()); n != 0 { + t.Fatalf("%d requests sent for a non-positive --timeout, want none", n) + } +} + +// The detach's --timeout help says a long bound can mean a long guest stop. +func TestChunkDetachTimeoutHelpNamesTheGuestStop(t *testing.T) { + _, _, errs := runChunk("detach", "-h") + if !strings.Contains(errs, "a long --timeout can mean a guest stop that long") { + t.Fatalf("detach help %q", errs) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_single_filer_unanswered_test.go b/seaweed-block/cmd/sw-block/chunk_single_filer_unanswered_test.go new file mode 100644 index 0000000000..b158aaae85 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_single_filer_unanswered_test.go @@ -0,0 +1,77 @@ +package main + +import ( + "bytes" + "context" + "net" + "strings" + "testing" + "time" + + "google.golang.org/grpc" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb" + "github.com/seaweedfs/seaweed-block/core/ops" +) + +type unansweredFiler struct { + filerpb.UnimplementedSeaweedFilerServer + masters []string +} + +func (f *unansweredFiler) GetFilerConfiguration(context.Context, *filerpb.GetFilerConfigurationRequest) (*filerpb.GetFilerConfigurationResponse, error) { + return &filerpb.GetFilerConfigurationResponse{Masters: f.masters}, nil +} + +type listingMaster struct { + masterpb.UnimplementedSeaweedServer + filer string + leader string +} + +func (m *listingMaster) GetMasterConfiguration(context.Context, *masterpb.GetMasterConfigurationRequest) (*masterpb.GetMasterConfigurationResponse, error) { + return &masterpb.GetMasterConfigurationResponse{Leader: m.leader}, nil +} + +func (m *listingMaster) ListClusterNodes(context.Context, *masterpb.ListClusterNodesRequest) (*masterpb.ListClusterNodesResponse, error) { + return &masterpb.ListClusterNodesResponse{ClusterNodes: []*masterpb.ListClusterNodesResponse_ClusterNode{{Address: m.filer}}}, nil +} + +// The shell's single-filer start check is the census's: a master address of +// the filer that does not parse is a master that did not answer, so one +// favourable master does not pass alone; the command is refused as invalid, +// naming that master and saying to rerun when it answers. +func TestOpsChunk_StartCheckRefusesAnUnparsableMaster(t *testing.T) { + flis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + filer := flis.Addr().String() + _, fport, _ := net.SplitHostPort(filer) + mlis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + _, mport, _ := net.SplitHostPort(mlis.Addr().String()) + ms := grpc.NewServer() + masterpb.RegisterSeaweedServer(ms, &listingMaster{filer: "127.0.0.1:8888." + fport, leader: "127.0.0.1:9333." + mport}) + go func() { _ = ms.Serve(mlis) }() + t.Cleanup(ms.Stop) + fs := grpc.NewServer() + filerpb.RegisterSeaweedFilerServer(fs, &unansweredFiler{masters: []string{"127.0.0.1:9333." + mport, "m1:9333.notaport"}}) + go func() { _ = fs.Serve(flis) }() + t.Cleanup(fs.Stop) + + f, closeFiler, err := dialChunkFiler(filer) + if err != nil { + t.Fatal(err) + } + defer closeFiler() + var stdout, stderr bytes.Buffer + code := refuseUnlessSingleFiler("snapshot-delete", f, 2*time.Second, &stdout, &stderr) + out := stdout.String() + stderr.String() + if code != ops.VolumeStatusExitInvalid || !strings.Contains(out, "m1:9333.notaport") || !strings.Contains(out, "rerun when they answer") { + t.Fatalf("one favourable master and one unparsable: exit %d, %q; want exit %d naming m1:9333.notaport, rerun when they answer", code, out, ops.VolumeStatusExitInvalid) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_start_check_test.go b/seaweed-block/cmd/sw-block/chunk_start_check_test.go new file mode 100644 index 0000000000..dcf835144a --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_start_check_test.go @@ -0,0 +1,185 @@ +package main + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// Every ops chunk command that writes chunk metadata runs the +// single-filer start check before it reads or writes anything, and refuses +// when the filer is not the only one of its group; read-only commands (and +// read-only modes) do not run it. +func TestOpsChunk_WritingCommandsRunTheSingleFilerCheck(t *testing.T) { + mem := newMemChunkStore() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + prevResolve := resolveVolumeID + t.Cleanup(func() { resolveVolumeID = prevResolve }) + resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{1}, nil } + id := []string{"--master", "m:1"} + src := []string{"--source", "v1", "--master", "m:1"} + tgt := []string{"--target", "v2"} + checks := 0 + checkSingleFiler = func(context.Context, chunkstore.Filer) error { + checks++ + return chunkstore.ErrNotSingleFiler + } + filer := []string{"--chunk-filer", "filer:18888"} + writing := map[string][]string{ + "snapshot-delete": append(append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--name", "s1"}, id...), filer...), + "release": append(append(append([]string{"ops", "chunk", "release"}, src...), tgt...), filer...), + "retain": append(append([]string{"ops", "chunk", "retain", "--volume", "v1"}, id...), filer...), + "volume-delete": append(append([]string{"ops", "chunk", "volume-delete", "--volume", "v1", "--master", "m:1", "--request-id", "r"}, id...), filer...), + } + for name, args := range writing { + before := checks + var out, errb bytes.Buffer + code := run(args, &out, &errb) + if checks != before+1 { + t.Errorf("%s: start check ran %d times; want once", name, checks-before) + } + if code == 0 || !strings.Contains(out.String()+errb.String(), "exactly one filer") { + t.Errorf("%s: exit %d, out %q err %q; want the single-filer refusal", name, code, out.String(), errb.String()) + } + } + readOnly := map[string][]string{ + "snapshots": append(append([]string{"ops", "chunk", "snapshots", "--volume", "v1"}, id...), filer...), + "show": append(append([]string{"ops", "chunk", "show", "--volume", "v1"}, id...), filer...), + "usage": append(append([]string{"ops", "chunk", "usage", "--volume", "v1"}, id...), filer...), + "retain --dry-run": append(append([]string{"ops", "chunk", "retain", "--volume", "v1", "--dry-run"}, id...), filer...), + } + for name, args := range readOnly { + before := checks + var out, errb bytes.Buffer + run(args, &out, &errb) + if checks != before { + t.Errorf("%s: a read-only command ran the start check", name) + } + } +} + +// Restore has one master authority call. The master owns the filer check +// and target creation; the CLI must never write the filer independently. +func TestOpsChunkRestoreUsesOnlyMasterCreate(t *testing.T) { + prevDial, prevRestore := dialChunkFiler, restoreCreateRPC + t.Cleanup(func() { dialChunkFiler, restoreCreateRPC = prevDial, prevRestore }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + t.Fatal("restore CLI contacted the filer") + return nil, nil, nil + } + calls := 0 + var firstID string + restoreCreateRPC = func(_ context.Context, master string, req *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) { + calls++ + if master != "m:1" || req.GetVolumeId() != "v2" || req.GetSourceVolume() != "v1" || req.GetSourceSnapshot() != "s1" || req.GetCreateRequestId() == "" { + t.Fatalf("restore RPC: master=%q req=%+v", master, req) + } + if firstID == "" { + firstID = req.GetCreateRequestId() + } + if req.GetCreateRequestId() != firstID { + t.Fatal("retry changed request id") + } + return &control.CreateVolumeResponse{VolumeId: "v2", LayoutId: (layout.VolumeID{1}).String(), StoreReady: true}, nil + } + args := []string{"ops", "chunk", "restore", "--master", "m:1", "--source", "v1", "--target", "v2", "--snapshot", "s1"} + for i := 0; i < 2; i++ { + var out, errs bytes.Buffer + if code := run(args, &out, &errs); code != 0 { + t.Fatalf("restore replay: code=%d out=%q err=%q", code, out.String(), errs.String()) + } + } + if calls != 2 { + t.Fatalf("restore made %d RPCs; want one per invocation", calls) + } + restoreCreateRPC = func(context.Context, string, *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) { + return nil, status.Error(codes.Unavailable, "filer unreachable") + } + var out, errs bytes.Buffer + if code := run(args, &out, &errs); code != chunkExitFailed || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), codeUnavailableCLI) { + t.Fatalf("uncertain restore must be retryable: code=%d out=%q err=%q", code, out.String(), errs.String()) + } +} + +// The start check runs within the command's own --timeout: a check stalled +// on its filer or master (here one that blocks until its context ends) ends +// the command at the timeout, as a retryable refusal. +func TestOpsChunk_StartCheckIsBoundedByTheTimeout(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck, prevResolve := dialChunkFiler, checkSingleFiler, resolveVolumeID + t.Cleanup(func() { dialChunkFiler, checkSingleFiler, resolveVolumeID = prevDial, prevCheck, prevResolve }) + resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{1}, nil } + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checkSingleFiler = func(ctx context.Context, _ chunkstore.Filer) error { + <-ctx.Done() + return ctx.Err() + } + filer := []string{"--chunk-filer", "filer:18888", "--timeout", "200ms"} + for name, args := range map[string][]string{ + "snapshot-delete": append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--master", "m:1", "--name", "s1"}, filer...), + } { + done := make(chan struct{}) + var out, errb bytes.Buffer + var code int + go func() { code = run(args, &out, &errb); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatalf("%s: a stalled start check held the command past its 200ms --timeout", name) + } + if code == 0 || !strings.Contains(out.String(), "remote_unavailable") || !strings.Contains(out.String(), `"retryable":true`) { + t.Errorf("%s: exit %d, out %q; want a retryable remote_unavailable refusal", name, code, out.String()) + } + } +} + +// A filer implementation that cannot run the real group census must never +// be mistaken for a successful single-filer observation. +func TestSingleFilerCheckRefusesUnsupportedClients(t *testing.T) { + for _, tc := range []struct { + name string + filer chunkstore.Filer + }{ + {"memory", chunkstore.NewMemFiler()}, + {"nil", nil}, + {"typed nil", (*chunkstore.SWFS)(nil)}, + } { + t.Run(tc.name, func(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Fatalf("start check panicked instead of refusing: %v", r) + } + }() + if err := checkSingleFiler(context.Background(), tc.filer); !errors.Is(err, chunkstore.ErrNotSingleFiler) { + t.Fatalf("unsupported filer start check: %v; want typed refusal", err) + } + }) + } +} + +func TestOpsChunkWritingRefusesUnsupportedFilerBeforeCatalogAccess(t *testing.T) { + mem := newMemChunkStore() + prevDial, prevResolve := dialChunkFiler, resolveVolumeID + t.Cleanup(func() { dialChunkFiler, resolveVolumeID = prevDial, prevResolve }) + closed := false + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return mem, func() error { closed = true; return nil }, nil + } + resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{1}, nil } + code, out, errs := runChunk("retain", "--volume", "v1", "--master", "master:1", "--chunk-filer", "filer:18888") + answer := chunkErrorOut(t, out) + if code != 2 || answer.Code != codeBadRequestCLI || answer.Retryable || !strings.Contains(answer.Message, "SWFS") || !closed || len(mem.blobs) != 0 { + t.Fatalf("unsupported filer was not refused before catalog work: exit=%d out=%s err=%s closed=%v blobs=%d", code, out, errs, closed, len(mem.blobs)) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_test.go b/seaweed-block/cmd/sw-block/chunk_test.go new file mode 100644 index 0000000000..b2e9054945 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_test.go @@ -0,0 +1,141 @@ +package main + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "sort" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +type chunkRoute struct { + path string + body map[string]any +} + +// chunkServer answers every request with status and reply, recording it. +func chunkServer(t *testing.T, status int, reply string) (*httptest.Server, *[]chunkRoute) { + t.Helper() + var got []chunkRoute + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var m map[string]any + _ = json.Unmarshal(b, &m) + if r.Method != http.MethodPost { + t.Errorf("%s %s: want POST", r.Method, r.URL.Path) + } + got = append(got, chunkRoute{path: r.URL.Path, body: m}) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = io.WriteString(w, reply) + })) + t.Cleanup(srv.Close) + return srv, &got +} + +func runChunk(args ...string) (int, string, string) { + var out, errb bytes.Buffer + code := run(append([]string{"ops", "chunk"}, args...), &out, &errb) + return code, out.String(), errb.String() +} + +func TestOpsChunk_HTTPCommandsSendSpecRequests(t *testing.T) { + srv, got := chunkServer(t, 200, `{"volumeID":"v1","cutLSN":9}`) + addr := strings.TrimPrefix(srv.URL, "http://") + if code, out, errs := runChunk("cut", "--volume", "v1", "--status-addr", addr, "--min-lsn", "7", "--timeout", "2s"); code != 0 || out != `{"volumeID":"v1","cutLSN":9}` { + t.Fatalf("cut: %d %q %q", code, out, errs) + } + code, _, errs := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--label", "agent.step=npm-ci", "--consistency", "app") + if code != 0 || !strings.Contains(errs, "request id ") { + t.Fatalf("snapshot: %d %q (a generated request id must be printed)", code, errs) + } + if code, _, errs := runChunk("detach", "--volume", "v1", "--status-addr", addr); code != 0 { + t.Fatalf("detach: %d %q", code, errs) + } + if len(*got) != 3 { + t.Fatalf("requests: %+v", *got) + } + cut, snap, det := (*got)[0], (*got)[1], (*got)[2] + if cut.path != "/chunk/cut" || cut.body["volumeID"] != "v1" || cut.body["minLSN"] != float64(7) || cut.body["timeoutMs"] != float64(2000) { + t.Fatalf("cut request: %+v", cut) + } + labels, _ := snap.body["labels"].(map[string]any) + if snap.path != "/chunk/snapshot" || snap.body["name"] != "s1" || snap.body["consistency"] != "app" || labels["agent.step"] != "npm-ci" || + len(snap.body["requestID"].(string)) != 32 { + t.Fatalf("snapshot request: %+v", snap) + } + if det.path != "/chunk/detach" || det.body["volumeID"] != "v1" || det.body["timeoutMs"] != float64(120000) { + t.Fatalf("detach request: %+v", det) + } + var keys []string + for k := range snap.body { + keys = append(keys, k) + } + sort.Strings(keys) + if strings.Join(keys, ",") != "consistency,expiresAtNs,labels,name,requestID,timeoutMs,volumeID" { + t.Fatalf("snapshot request fields %v", keys) + } +} + +func TestOpsChunk_HTTPFailureIsTyped(t *testing.T) { + srv, _ := chunkServer(t, 409, `{"code":"not_primary","message":"volume v1 is not a healthy primary here","retryable":false}`) + code, out, errs := runChunk("cut", "--volume", "v1", "--status-addr", srv.URL) + if e := chunkErrorOut(t, out); code != chunkExitFailed || e.Code != "not_primary" || e.Message != "volume v1 is not a healthy primary here" || e.Retryable || + !strings.Contains(errs, "not_primary: volume v1 is not a healthy primary here") { + t.Fatalf("refused cut: %d %q %q; want the route's error body on stdout", code, out, errs) + } + if code, out, _ := runChunk("cut", "--volume", "v1"); code != 2 || chunkErrorOut(t, out).Code != "bad_request" { + t.Fatalf("cut without --status-addr: exit %d %q, want 2 and bad_request", code, out) + } + if code, out, _ := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--label", "nokey"); code != 2 || chunkErrorOut(t, out).Code != "bad_request" { + t.Fatalf("a label without '=': exit %d %q, want 2 and bad_request", code, out) + } +} + +// chunkErrorOut decodes the CLI's error body from stdout. +func chunkErrorOut(t *testing.T, out string) chunkErrBody { + t.Helper() + var e chunkErrBody + if err := json.Unmarshal([]byte(out), &e); err != nil || e.Code == "" { + t.Fatalf("stdout is not an error body: %q (%v)", out, err) + } + if strings.Contains(e.Message, e.Code) { + t.Fatalf("the error message repeats its code: %+v", e) + } + return e +} + +// Every failure is the error body on stdout and a non-zero exit (B9 W2 +// appendix): usage, an unreachable blockvolume, a catalog refusal. +func TestOpsChunk_ErrorsAreJSONOnStdout(t *testing.T) { + if code, out, _ := runChunk("nope"); code != 2 || chunkErrorOut(t, out).Code != "bad_request" { + t.Fatalf("unknown subcommand: exit %d %q", code, out) + } + if code, out, _ := runChunk("cut", "--bogus"); code != 2 || chunkErrorOut(t, out).Code != "bad_request" { + t.Fatalf("unknown flag: exit %d %q", code, out) + } + dead := httptest.NewServer(http.NotFoundHandler()) + addr := dead.URL + dead.Close() + if code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", addr); code != chunkExitFailed { + t.Fatalf("unreachable blockvolume: exit %d %q", code, out) + } else if e := chunkErrorOut(t, out); e.Code != "remote_unavailable" || !e.Retryable { + t.Fatalf("unreachable blockvolume: %+v, want remote_unavailable and retryable", e) + } + + store := newMemChunkStore() + useMemChunkStore(t, store) + src := cliVolume(t, store, "v1", "s1") + tid, _ := layout.NewVolumeID() + if code, out, _ := runChunk(cliArgs("restore", volArgs("source", src), volArgs("target", chunkstore.VolumeRef{Name: "v2", ID: tid}), []string{"--snapshot", "s9"})...); code != chunkExitFailed { + t.Fatalf("restore of a missing snapshot: exit %d %q", code, out) + } else if e := chunkErrorOut(t, out); e.Code != "snapshot_not_found" || e.Retryable { + t.Fatalf("restore of a missing snapshot: %+v", e) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_typed_codes_test.go b/seaweed-block/cmd/sw-block/chunk_typed_codes_test.go new file mode 100644 index 0000000000..b1fb8c2a9d --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_typed_codes_test.go @@ -0,0 +1,66 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func jsonCode(t *testing.T, out []byte) string { + t.Helper() + var b struct{ Code string } + if err := json.Unmarshal(bytes.TrimSpace(out), &b); err != nil { + t.Fatalf("output %q is not one JSON object: %v", out, err) + } + return b.Code +} + +// The JSON codes a runner decides by, never the message text: a restore the +// master refused for a foreign source is restore_source_not_own (from its +// typed reason; an untyped FailedPrecondition stays not_admitted), and a +// volume the master does not know is volume_not_found (any other resolve +// failure stays bad_request). +func TestOpsChunkTypedRefusalCodes(t *testing.T) { + prevRestore, prevResolve := restoreCreateRPC, resolveVolumeID + t.Cleanup(func() { restoreCreateRPC, resolveVolumeID = prevRestore, prevResolve }) + restore := []string{"ops", "chunk", "restore", "--master", "m:1", "--source", "t", "--target", "t2", "--snapshot", "copy"} + for _, c := range []struct { + name string + err error + code string + }{ + {"typed foreign source", lifecycleclient.WithReason(status.New(codes.FailedPrecondition, "restore target: the snapshot names another volume's chunks"), lifecycleclient.ReasonRestoreSourceNotOwn).Err(), "restore_source_not_own"}, + {"untyped refusal", status.Error(codes.FailedPrecondition, "restore target: the snapshot names another volume's chunks"), "not_admitted"}, + } { + restoreCreateRPC = func(context.Context, string, *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) { + return nil, c.err + } + var out, errs bytes.Buffer + if exit := run(restore, &out, &errs); exit != chunkExitFailed || jsonCode(t, out.Bytes()) != c.code { + t.Fatalf("%s: exit %d code %q; want %d %q (%s)", c.name, exit, jsonCode(t, out.Bytes()), chunkExitFailed, c.code, errs.String()) + } + } + snapshots := []string{"ops", "chunk", "snapshots", "--master", "m:1", "--volume", "ghost", "--chunk-filer", "filer:18888"} + for _, c := range []struct { + name string + err error + exit int + code string + }{ + {"unknown volume", status.Error(codes.NotFound, "volume not found"), chunkExitFailed, "volume_not_found"}, + {"master unreachable", status.Error(codes.Unavailable, "connection refused"), 2, codeBadRequestCLI}, + } { + resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{}, c.err } + var out, errs bytes.Buffer + if exit := run(snapshots, &out, &errs); exit != c.exit || jsonCode(t, out.Bytes()) != c.code { + t.Fatalf("%s: exit %d code %q; want %d %q (%s)", c.name, exit, jsonCode(t, out.Bytes()), c.exit, c.code, errs.String()) + } + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_verify.go b/seaweed-block/cmd/sw-block/chunk_verify.go new file mode 100644 index 0000000000..279daae6c1 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_verify.go @@ -0,0 +1,286 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "sync" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// chunkVerify: sw-block ops chunk verify --master master:9180 --volume v --chunk-filer host:port +// checks the volume's store read-only: VOLUME, HEAD, every root HEAD names +// (the current image and every snapshot), their segments and chunks +// (chunkstore.VerifyLayout). --orphans also reports the volume's own names +// that no reachable root names (it never deletes them). Exit 0: clean; 3: +// the pass completed with findings; 1: it could not complete (the partial +// result is printed with the reason); 2: usage. +func chunkVerify(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("verify", stderr) + var ( + volumeID, master, filer, base, snapshot, depth string + allSnapshots, orphans bool + concurrency int + bytesPerSec int64 + timeout, deadline time.Duration + ) + fs.StringVar(&volumeID, "volume", "", "volume name with --master, or an explicit - store directory") + fs.StringVar(&master, "master", "", "blockmaster gRPC address (resolves --volume name to its full layout identity)") + fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") + fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") + fs.StringVar(&snapshot, "snapshot", "", "unsupported: every snapshot HEAD names is always checked") + fs.BoolVar(&allSnapshots, "all-snapshots", false, "unsupported: every snapshot HEAD names is always checked") + fs.StringVar(&depth, "depth", "bindings", "meta or bindings: named filer entries, sizes and needle HEAD; data: and every chunk's bytes hash to its name") + fs.BoolVar(&orphans, "orphans", false, "also report the volume's own names no reachable root names (report only)") + fs.IntVar(&concurrency, "concurrency", 1, "unsupported: chunks are read one at a time") + fs.Int64Var(&bytesPerSec, "bytes-per-sec", 0, "unsupported: chunk reads are not paced") + fs.DurationVar(&timeout, "timeout", 10*time.Minute, "no-progress window: the pass fails only after this long without completing an object read; required with --depth data") + fs.DurationVar(&deadline, "deadline", 0, "optional bound for the whole pass (0: none)") + if err := fs.Parse(args); err != nil { + return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + timeoutSet := false + unsupported := "" + fs.Visit(func(f *flag.Flag) { + switch f.Name { + case "snapshot", "all-snapshots", "concurrency", "bytes-per-sec": + if unsupported == "" { + unsupported = f.Name + } + } + if f.Name == "timeout" { + timeoutSet = true + } + }) + usage := func(msg string) int { + return chunkFail("verify", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, msg, false) + } + d := map[string]string{"meta": layout.DepthNames, "bindings": layout.DepthNames, "data": layout.DepthFull}[depth] + switch { + case unsupported != "": + return usage("--" + unsupported + " is unsupported; verify checks every named snapshot sequentially without pacing") + case fs.NArg() != 0: + return usage("unexpected arguments") + case volumeID == "": + return usage("--volume is required") + case filer == "": + return usage("--chunk-filer is required") + case d == "": + return usage(fmt.Sprintf("--depth %q: meta, bindings or data", depth)) + case d == layout.DepthFull && !timeoutSet: + return usage("--depth data reads every chunk: give an explicit --timeout for the pass") + case timeout <= 0: + return usage("--timeout must be positive") + case deadline < 0: + return usage("--deadline must not be negative") + } + // The pass is bounded by progress, not by its length: it ends only when + // no object read has completed for --timeout (each one renews the + // window), or at the optional --deadline. Verify writes nothing, but + // against a split filer view it would report false findings, so it runs + // the single-filer start check, bounded by --timeout. + ctx, cancel := context.WithCancelCause(context.Background()) + defer cancel(nil) + if deadline > 0 { + var stopDeadline context.CancelFunc + ctx, stopDeadline = context.WithTimeoutCause(ctx, deadline, fmt.Errorf("verify: --deadline %s reached: %w", deadline, context.DeadlineExceeded)) + defer stopDeadline() + } + progress := watchVerifyProgress(ctx, timeout, cancel) + dir := volumeID + opts := layout.VerifyOptions{Depth: d, Orphans: orphans, Progress: progress} + withCause := func(err error) error { + if ctx.Err() != nil { + if c := context.Cause(ctx); c != nil && !errors.Is(err, c) { + return fmt.Errorf("%w (%w)", err, c) + } + } + return err + } + if master != "" { + id, err := resolveVolumeID(ctx, master, volumeID) + if err != nil { + return verifyIncomplete(layout.VerifyResult{}, withCause(err), stdout, stderr) + } + dir, opts.ExpectedID = layout.VolumeDir(volumeID, id), id + } + f, closeFn, err := dialChunkFiler(filer) + if err != nil { + return usage(err.Error()) + } + defer closeFn() + if exit := refuseUnlessSingleFilerWithin(ctx, "verify", f, timeout, stdout, stderr); exit >= 0 { + return exit + } + res, err := chunkstore.VerifyLayout(ctx, f, base, dir, opts) + if err != nil { + return verifyIncomplete(res, withCause(err), stdout, stderr) + } + if !res.Complete && ctx.Err() != nil { + // A pass ended inside a step that reports incomplete rather than an + // error (the final HEAD confirmations): keep why it was ended. + if c := context.Cause(ctx); c != nil { + res.Incomplete += " (" + c.Error() + ")" + } + } + if master == "" && res.Incomplete == "no VOLUME" { + return usage("no VOLUME in the supplied directory: give --master to resolve a name, or the - store directory") + } + out, err := verifyJSON(res) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk verify: %v\n", err) + return chunkExitFailed + } + if err := writeAll(stdout, out); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk verify: write the result: %v\n", err) + return chunkExitFailed + } + if !res.Complete { + fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: incomplete: %s\n", volumeID, res.Incomplete) + return chunkExitFailed + } + if len(res.Findings) != 0 { + fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %d findings\n", volumeID, len(res.Findings)) + return chunkExitFindings + } + return ops.VolumeStatusExitOK +} + +// errVerifyStalled is the cause of a verify pass ended by its no-progress +// window: a transient failure, answered like a deadline. +var errVerifyStalled = errors.New("verify: no object read completed within the --timeout no-progress window") + +// verifyWatch is a pass's no-progress window. Renewal and expiry are decided +// under one lock on the clock's (monotonic) time: whichever of a read's +// renewal or the ticker's check comes first after the window elapsed expires +// it, so an elapsed window is never renewed. +type verifyWatch struct { + mu sync.Mutex + window time.Duration + now func() time.Time + last time.Time + expired bool + cancel context.CancelCauseFunc +} + +func newVerifyWatch(window time.Duration, now func() time.Time, cancel context.CancelCauseFunc) *verifyWatch { + return &verifyWatch{window: window, now: now, last: now(), cancel: cancel} +} + +// expireLocked expires the window once it has elapsed; it reports whether +// the window is expired. +func (w *verifyWatch) expireLocked() bool { + if !w.expired && w.now().Sub(w.last) >= w.window { + w.expired = true + } + return w.expired +} + +// renew records a completed read, unless the window has already elapsed. +func (w *verifyWatch) renew() { + w.mu.Lock() + expired := w.expireLocked() + if !expired { + w.last = w.now() + } + w.mu.Unlock() + if expired { + w.fire() + } +} + +// check expires an elapsed window; it reports whether the window expired. +func (w *verifyWatch) check() bool { + w.mu.Lock() + expired := w.expireLocked() + w.mu.Unlock() + if expired { + w.fire() + } + return expired +} + +func (w *verifyWatch) fire() { + w.cancel(fmt.Errorf("%w (%s)", errVerifyStalled, w.window)) +} + +// watchVerifyProgress returns the progress callback of a verify pass and +// cancels ctx (cause errVerifyStalled) once its window elapses without a +// call; the pass start counts as progress. It stops when ctx ends. +func watchVerifyProgress(ctx context.Context, window time.Duration, cancel context.CancelCauseFunc) func() { + w := newVerifyWatch(window, time.Now, cancel) + every := min(max(window/4, time.Millisecond), time.Second) + go func() { + tick := time.NewTicker(every) + defer tick.Stop() + for { + select { + case <-ctx.Done(): + return + case <-tick.C: + } + if w.check() { + return + } + } + }() + return w.renew +} + +// verifyJSON is the result as one JSON object whose findings array holds +// one finding per line. +func verifyJSON(res layout.VerifyResult) ([]byte, error) { + findings := res.Findings + res.Findings = nil + head, err := json.Marshal(res) + if err != nil { + return nil, err + } + const tail = `"Findings":null}` + if !bytes.HasSuffix(head, []byte(tail)) { + return nil, errors.New("verify result: unexpected field order") + } + var buf bytes.Buffer + buf.Write(head[:len(head)-len(tail)]) + buf.WriteString(`"Findings":[`) + for i, f := range findings { + line, err := json.Marshal(f) + if err != nil { + return nil, err + } + if i > 0 { + buf.WriteByte(',') + } + buf.WriteByte('\n') + buf.Write(line) + } + if len(findings) > 0 { + buf.WriteByte('\n') + } + buf.WriteString("]}\n") + return buf.Bytes(), nil +} + +// verifyIncomplete prints the error body with the partial result under +// "verify", and fails. +func verifyIncomplete(res layout.VerifyResult, err error, stdout, stderr io.Writer) int { + body := struct { + chunkErrBody + Verify layout.VerifyResult `json:"verify"` + }{Verify: res} + body.Code, body.Message = codeInternalCLI, err.Error() + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled) { + body.Code, body.Retryable = chunkstore.CodeDeadlineExceeded, true + } + fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %s (incomplete)\n", body.Code, body.Message) + chunkResult("verify", body, nil, stdout, stderr) + return chunkExitFailed +} diff --git a/seaweed-block/cmd/sw-block/chunk_verify_production_test.go b/seaweed-block/cmd/sw-block/chunk_verify_production_test.go new file mode 100644 index 0000000000..205230d639 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_verify_production_test.go @@ -0,0 +1,53 @@ +package main + +import ( + "context" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +func TestOpsChunk_VerifyProductionLayoutNameAndDirectory(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "verify-prod", "s") + for i, args := range [][]string{ + cliArgs("verify", volArgs("volume", v), []string{"--depth", "data", "--timeout", "5s", "--orphans"}), + {"verify", "--volume", v.Dir(), "--chunk-filer", "filer:18888", "--depth", "data", "--timeout", "5s", "--orphans"}, + } { + code, out, errs := runChunk(args...) + res := decodeVerify(t, out) + if res.MasterIdentityChecked != (i == 0) { + t.Fatalf("master identity disclosure: %s", out) + } + if code != 0 || !res.Complete || !res.OrphansChecked || len(res.Findings) != 0 || res.Chunks != 1 { + t.Fatalf("%v: exit%d out=%s err=%s", args, code, out, errs) + } + } +} + +func TestOpsChunk_VerifyBindsMasterFullIDDespiteDirectoryPrefixCollision(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "verify-collision", "s") + want := v.ID + want[15] ^= 1 + if layout.VolumeDir(v.Name, want) != v.Dir() { + t.Fatal("test ids do not collide on id8") + } + resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return want, nil } + code, out, errs := runChunk(cliArgs("verify", volArgs("volume", v))...) + res := decodeVerify(t, out) + if code != 1 || res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindIdentity { + t.Fatalf("wrong full identity: %d %s %s", code, out, errs) + } +} + +func TestOpsChunk_VerifyLegacyNameNeedsResolution(t *testing.T) { + verifyCLIFixture(t) + code, out, errs := runChunk("verify", "--volume", "v1", "--chunk-filer", "filer:18888") + if code != 2 || strings.Contains(out, "MISSING") || !strings.Contains(out+errs, "--master") || !strings.Contains(out+errs, "-") { + t.Fatalf("legacy name: %d %s %s", code, out, errs) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_verify_test.go b/seaweed-block/cmd/sw-block/chunk_verify_test.go new file mode 100644 index 0000000000..4ac1cd30f0 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_verify_test.go @@ -0,0 +1,256 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "path" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// verifyCLIFixture is volume v1 on the content-named layout (VOLUME, HEAD, +// one root naming chunks 0 and 1) on an in-memory filer and blob store; it +// returns the store and chunk 1's pool path. +func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, string) { + assumeSingleFilerFixture(t) + t.Helper() + ctx := context.Background() + mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) + prev := dialChunkFiler + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return mem, func() error { return nil }, nil + } + t.Cleanup(func() { dialChunkFiler = prev }) + var root string + put := func(rel string, b []byte) { + p := path.Join(root, rel) + if err := mem.CreateEntry(ctx, path.Dir(p), &filerpb.Entry{Name: path.Base(p), Content: b}, true); err != nil { + t.Fatal(err) + } + } + id, err := layout.NewVolumeID() + if err != nil { + t.Fatal(err) + } + root = path.Join(defaultChunkPathCLI, layout.VolumeDir("v1", id)) + oldResolve := resolveVolumeID + resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return id, nil } + t.Cleanup(func() { resolveVolumeID = oldResolve }) + vb, err := layout.Volume{ID: id, Name: "v1", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4096}, Format: layout.VolumeFormat}.Encode() + if err != nil { + t.Fatal(err) + } + put(layout.VolumeName, vb) + manifest := map[uint64]layout.Ref{} + var last string + for idx := uint64(0); idx < 2; idx++ { + data := bytes.Repeat([]byte{byte(0x30 + idx)}, 4096) + c := layout.NameChunk(idx, data) + put(c.Path(), data) + manifest[idx] = layout.Ref{Owner: "v1", OwnerID: id, Chunk: c} + last = c.Path() + } + r, segs, err := layout.Build(manifest) + if err != nil { + t.Fatal(err) + } + for n, b := range segs { + put(n.Path(), b) + } + rn, rb, err := layout.NameRoot(r) + if err != nil { + t.Fatal(err) + } + put(rn.Path(), rb) + hb, err := layout.Head{VolumeID: id, Epoch: 1, Holder: "s/r", ClaimID: "c", Activity: layout.Activity{Kind: layout.ActIdle}, Current: &rn}.Encode() + if err != nil { + t.Fatal(err) + } + put(layout.HeadName, hb) + e, err := mem.LookupEntry(ctx, root, layout.HeadName) + if err != nil { + t.Fatal(err) + } + e.Extended = map[string][]byte{"swb.layout.kind": []byte("head"), "swb.layout.volume": []byte(id.String()), "swb.layout.gen": []byte("1")} + if err := mem.UpdateEntry(ctx, root, e, nil); err != nil { + t.Fatal(err) + } + return mem, path.Join(root, last) +} + +func decodeVerify(t *testing.T, out string) layout.VerifyResult { + t.Helper() + var res layout.VerifyResult + if err := json.Unmarshal([]byte(out), &res); err != nil { + t.Fatalf("stdout is not a verify result: %q (%v)", out, err) + } + return res +} + +// verify's exit codes: 0 clean, 3 completed with findings, 1 could not +// complete, 2 usage; the result is one JSON object with one finding per line. +func TestOpsChunk_VerifyExitCodes(t *testing.T) { + mem, chunk1 := verifyCLIFixture(t) + filer := []string{"--volume", "v1", "--master", "m:1", "--chunk-filer", "filer:18888"} + + code, out, errs := runChunk(append([]string{"verify"}, filer...)...) + res := decodeVerify(t, out) + if code != 0 || !res.Complete || len(res.Findings) != 0 || res.Chunks != 2 || res.Roots != 1 || !strings.Contains(out, `"Findings":[]`) { + t.Fatalf("clean verify: %d %q %q", code, out, errs) + } + code, out, errs = runChunk(append([]string{"verify", "--depth", "data", "--timeout", "10s", "--orphans"}, filer...)...) + if res = decodeVerify(t, out); code != 0 || !res.Complete || len(res.Findings) != 0 || !res.OrphansChecked { + t.Fatalf("clean data verify: %d %q %q", code, out, errs) + } + + // A chunk gone: completed with a finding. + if err := mem.DeleteEntry(context.Background(), path.Dir(chunk1), path.Base(chunk1), nil); err != nil { + t.Fatal(err) + } + code, out, errs = runChunk(append([]string{"verify"}, filer...)...) + res = decodeVerify(t, out) + if chunkExitFindings != 3 || code != chunkExitFindings || !res.Complete || len(res.Findings) != 1 || + res.Findings[0].Class != layout.FindMissing || !strings.Contains(errs, "1 findings") { + t.Fatalf("verify with a missing chunk: %d %q %q", code, out, errs) + } + lines := strings.Split(strings.TrimSpace(out), "\n") + if len(lines) != 3 || !strings.Contains(lines[1], `"Class":"MISSING"`) || lines[2] != "]}" { + t.Fatalf("findings are not one per line:\n%s", out) + } + + // Could not complete: a volume without VOLUME/HEAD. + code, out, errs = runChunk("verify", "--volume", "nope", "--master", "m:1", "--chunk-filer", "filer:18888") + if res = decodeVerify(t, out); code != chunkExitFailed || res.Complete || !strings.Contains(errs, "incomplete") { + t.Fatalf("verify of a missing volume: %d %q %q", code, out, errs) + } + + for _, args := range [][]string{ + {"verify", "--chunk-filer", "f:1"}, // no volume + {"verify", "--volume", "v1", "--master", "m:1"}, // no filer + {"verify", "--volume", "v1", "--master", "m:1", "--chunk-filer", "f:1", "--depth", "all"}, // bad depth + {"verify", "--volume", "v1", "--master", "m:1", "--chunk-filer", "f:1", "--depth", "data"}, // data without --timeout + {"verify", "--volume", "v1", "--master", "m:1", "--chunk-filer", "f:1", "--snapshot", "s1", "--all-snapshots"}, + {"verify", "--volume", "v1", "--master", "m:1", "--chunk-filer", "f:1", "--concurrency", "0"}, + {"verify", "--volume", "v1", "--master", "m:1", "--chunk-filer", "f:1", "--bytes-per-sec", "-1"}, + {"verify", "--volume", "v1", "--master", "m:1", "--chunk-filer", "f:1", "extra"}, + {"verify", "--volume", "v1", "--master", "m:1", "--chunk-filer", "f:1", "--bogus"}, + } { + code, out, _ := runChunk(args...) + if code != 2 || chunkErrorOut(t, out).Code != codeBadRequestCLI { + t.Fatalf("%v: exit %d %q; want 2 and bad_request", args, code, out) + } + } + if code, out, _ := runChunk("verify", "--volume", "v1", "--master", "m:1", "--chunk-filer", "f:1", "--depth", "data"); !strings.Contains(out, "--timeout") { + t.Fatalf("data without --timeout: %d %q; want the reason", code, out) + } +} + +// unreadableStore fails every read of one path with an error that is not +// "not found" (a filer answering 503). +type unreadableStore struct { + *manifestFixtureFiler + bad string +} + +func (s unreadableStore) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if path.Join(dir, name) == s.bad { + return nil, fmt.Errorf("filer: lookup %s: unavailable (503)", s.bad) + } + return s.manifestFixtureFiler.LookupEntry(ctx, dir, name) +} + +// A chunk that cannot be read is not judged: the pass could not complete +// (exit 1) and says why. +func TestOpsChunk_VerifyReadErrorIsIncomplete(t *testing.T) { + mem, chunk1 := verifyCLIFixture(t) + store := unreadableStore{mem, chunk1} + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return store, func() error { return nil }, nil + } + code, out, errs := runChunk("verify", "--volume", "v1", "--master", "m:1", "--chunk-filer", "filer:18888", "--depth", "data", "--timeout", "10s") + if code != chunkExitFailed || !strings.Contains(out, "503") || !strings.Contains(errs, "incomplete") { + t.Fatalf("verify with an unreadable chunk: %d %q %q", code, out, errs) + } +} + +// verify writes nothing, yet it is in the set that runs the single-filer +// start check (a split filer view would give false findings), and it refuses +// the way the writing commands do (TestOpsChunk_WritingCommandsRunTheSingleFilerCheck). +func TestOpsChunk_VerifyRunsTheSingleFilerCheck(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checks := 0 + checkSingleFiler = func(context.Context, chunkstore.Filer) error { + checks++ + return chunkstore.ErrNotSingleFiler + } + filer := []string{"--chunk-filer", "filer:18888"} + for name, args := range map[string][]string{ + "verify": append([]string{"ops", "chunk", "verify", "--volume", "v1"}, filer...), + "verify --depth data": append([]string{"ops", "chunk", "verify", "--volume", "v1", "--depth", "data", "--timeout", "10s"}, filer...), + } { + before := checks + var out, errb bytes.Buffer + code := run(args, &out, &errb) + if checks != before+1 { + t.Errorf("%s: start check ran %d times; want once", name, checks-before) + } + if code == 0 || !strings.Contains(out.String()+errb.String(), "exactly one filer") { + t.Errorf("%s: exit %d, out %q err %q; want the single-filer refusal", name, code, out.String(), errb.String()) + } + } +} + +// The start check runs within verify's --timeout, as for the writing +// commands (TestOpsChunk_StartCheckIsBoundedByTheTimeout): a check stalled on +// its filer or master ends verify at the timeout, as a retryable refusal. +func TestOpsChunk_VerifyStartCheckIsBoundedByTheTimeout(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checkSingleFiler = func(ctx context.Context, _ chunkstore.Filer) error { + <-ctx.Done() + return ctx.Err() + } + args := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", "filer:18888", "--timeout", "200ms"} + done := make(chan struct{}) + var out, errb bytes.Buffer + var code int + go func() { code = run(args, &out, &errb); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatalf("a stalled start check held verify past its 200ms --timeout") + } + if code == 0 || !strings.Contains(out.String(), "remote_unavailable") || !strings.Contains(out.String(), `"retryable":true`) { + t.Errorf("verify: exit %d, out %q; want a retryable remote_unavailable refusal", code, out.String()) + } +} + +func TestOpsChunkVerifyRefusesUnsupportedFlagsBeforeDial(t *testing.T) { + old := dialChunkFiler + dials := 0 + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + dials++ + return nil, nil, fmt.Errorf("unexpected dial") + } + t.Cleanup(func() { dialChunkFiler = old }) + for _, arg := range []string{"--snapshot=s1", "--all-snapshots", "--all-snapshots=false", "--concurrency=1", "--bytes-per-sec=0"} { + t.Run(arg, func(t *testing.T) { + code, out, _ := runChunk("verify", "--volume=v1", "--chunk-filer=f:1", arg) + if dials != 0 || code != 2 || chunkErrorOut(t, out).Code != codeBadRequestCLI || !strings.Contains(out, "unsupported") { + t.Fatalf("exit=%d out=%s", code, out) + } + }) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_verify_window_test.go b/seaweed-block/cmd/sw-block/chunk_verify_window_test.go new file mode 100644 index 0000000000..3dff5378c0 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_verify_window_test.go @@ -0,0 +1,395 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "path" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// runVerifyBounded runs verify and fails the test if it has not returned +// within bound: a held path is ended by the test itself, not only measured +// after it returned. +func runVerifyBounded(t *testing.T, bound time.Duration, args ...string) (int, string, string) { + t.Helper() + type result struct { + code int + out, errs string + } + done := make(chan result, 1) + joined := make(chan struct{}) + release := make(chan struct{}) + heldRelease = release // read by the held store calls of this run + go func() { + defer close(joined) + code, out, errs := runChunk(append([]string{"verify"}, args...)...) + done <- result{code, out, errs} + }() + // Registered after the fixture's cleanups, so it runs before them: every + // held store call is released, then the command is joined before the + // globals it reads are restored. A worker that survives its release stops + // the test binary, so no later test runs beside it. + t.Cleanup(func() { + close(release) + select { + case <-joined: + heldRelease = make(chan struct{}) // the next run starts unreleased + case <-time.After(10 * time.Second): + panic("a verify command survived the release of its held calls; stopping so no later test runs under restored globals") + } + }) + select { + case r := <-done: + return r.code, r.out, r.errs + case <-time.After(bound): + t.Fatalf("verify %v did not return within %s", args, bound) + return 0, "", "" + } +} + +// heldRelease is closed by runVerifyBounded's cleanup: every held store call +// (and a stubbed start check) also returns on it, so the command can always +// be joined. It is never closed outside a bounded run. +var heldRelease = make(chan struct{}) + +// errHeldReleased is what a held call returns when the test releases it. +var errHeldReleased = errors.New("held call released by the test") + +// verifyAnswer is verify's incomplete answer: the error body and the partial +// result. +type verifyAnswer struct { + Code string `json:"code"` + Message string `json:"message"` + Retryable bool `json:"retryable"` + Verify struct { + Complete bool + Incomplete string + } `json:"verify"` +} + +func decodeVerifyAnswer(t *testing.T, out string) verifyAnswer { + t.Helper() + var a verifyAnswer + if err := json.Unmarshal([]byte(out), &a); err != nil { + t.Fatalf("stdout is not a verify answer: %q (%v)", out, err) + } + return a +} + +// slowStore answers every lookup after delay (a filer slower than the pass +// is long, never silent), and holds a lookup of stall until its context +// ends (a silent filer). +type slowStore struct { + *manifestFixtureFiler + delay time.Duration + stall string +} + +func (s slowStore) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if s.stall != "" && path.Join(dir, name) == s.stall { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-heldRelease: + return nil, errHeldReleased + } + } + select { + case <-time.After(s.delay): + case <-ctx.Done(): + return nil, ctx.Err() + case <-heldRelease: + return nil, errHeldReleased + } + return s.manifestFixtureFiler.LookupEntry(ctx, dir, name) +} + +// --timeout is a no-progress window, not a bound on the pass: on a filer +// that answers each read within the window, a pass several windows long +// completes clean, at the names depth and at the data depth. (At the 1 TiB +// cap with 10 snapshots a default pass outlasts a fixed 600 s bound.) +func TestOpsChunk_VerifyTimeoutIsANoProgressWindow(t *testing.T) { + for _, depth := range []string{"bindings", "data"} { + t.Run(depth, func(t *testing.T) { + mem, _ := verifyCLIFixture(t) + store := slowStore{manifestFixtureFiler: mem, delay: 60 * time.Millisecond} + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return store, func() error { return nil }, nil + } + const window = 150 * time.Millisecond + start := time.Now() + code, out, errs := runChunk("verify", "--volume", "v1", "--master", "m:1", "--chunk-filer", "filer:18888", "--depth", depth, "--timeout", window.String()) + took := time.Since(start) + if code != 0 || !decodeVerify(t, out).Complete { + t.Fatalf("a %s pass of %s with each read inside the %s window: exit %d, out %q, err %q; want clean", depth, took, window, code, out, errs) + } + if took < 2*window { + t.Fatalf("fixture: the pass took %s, not several windows of %s; the test proves nothing", took, window) + } + }) + } +} + +// The window still ends a silent pass: a read that never answers fails the +// pass within about one window, as incomplete, naming the no-progress cause. +func TestOpsChunk_VerifyStopsAfterAWindowWithoutProgress(t *testing.T) { + mem, chunk1 := verifyCLIFixture(t) + store := slowStore{manifestFixtureFiler: mem, stall: chunk1} + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return store, func() error { return nil }, nil + } + code, out, errs := runVerifyBounded(t, 5*time.Second, "--volume", "v1", "--master", "m:1", "--chunk-filer", "filer:18888", "--depth", "data", "--timeout", "200ms") + a := decodeVerifyAnswer(t, out) + if code != chunkExitFailed || a.Verify.Complete || a.Code != chunkstore.CodeDeadlineExceeded || !a.Retryable || !strings.Contains(a.Message, "no object read completed") { + t.Fatalf("a silent pass: exit %d, answer %+v, err %q; want incomplete, retryable deadline_exceeded naming the no-progress cause", code, a, errs) + } +} + +// --deadline bounds the whole pass even while it progresses. +func TestOpsChunk_VerifyDeadlineBoundsAProgressingPass(t *testing.T) { + mem, _ := verifyCLIFixture(t) + store := slowStore{manifestFixtureFiler: mem, delay: 60 * time.Millisecond} + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return store, func() error { return nil }, nil + } + code, out, errs := runVerifyBounded(t, 5*time.Second, "--volume", "v1", "--master", "m:1", "--chunk-filer", "filer:18888", "--timeout", "10s", "--deadline", "100ms") + a := decodeVerifyAnswer(t, out) + if code != chunkExitFailed || a.Verify.Complete || a.Code != chunkstore.CodeDeadlineExceeded || !a.Retryable || !strings.Contains(a.Message, "--deadline 100ms reached") { + t.Fatalf("a progressing pass past its --deadline: exit %d, answer %+v, err %q; want incomplete, retryable deadline_exceeded naming the deadline", code, a, errs) + } + if code, _, _ := runChunk("verify", "--volume", "v1", "--chunk-filer", "filer:18888", "--deadline", "-1s"); code != 2 { + t.Fatalf("a negative --deadline: exit %d, want usage (2)", code) + } +} + +// listStore delays (or, past stallAfter calls, holds until its context +// ends) every directory page the orphan scan reads, and holds the HEAD +// lookup numbered stallHead (the final confirmation is the last one). +type listStore struct { + *manifestFixtureFiler + pageDelay time.Duration + stallList bool + stallHead int + headLookup *int + mu *sync.Mutex +} + +func (s listStore) ListEntries(ctx context.Context, dir, prefix, startAfter string, limit uint32) ([]*filerpb.Entry, error) { + if s.stallList { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-heldRelease: + return nil, errHeldReleased + } + } + select { + case <-time.After(s.pageDelay): + case <-ctx.Done(): + return nil, ctx.Err() + case <-heldRelease: + return nil, errHeldReleased + } + return s.manifestFixtureFiler.ListEntries(ctx, dir, prefix, startAfter, limit) +} + +func (s listStore) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if name == "HEAD" && s.stallHead > 0 { + s.mu.Lock() + *s.headLookup++ + n := *s.headLookup + s.mu.Unlock() + if n == s.stallHead { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-heldRelease: + return nil, errHeldReleased + } + } + } + return s.manifestFixtureFiler.LookupEntry(ctx, dir, name) +} + +func withListStore(t *testing.T, s listStore) { + t.Helper() + if s.mu == nil { + s.mu, s.headLookup = &sync.Mutex{}, new(int) + } + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return s, func() error { return nil }, nil } +} + +// Each orphan-scan page renews the window: a scan whose pages each answer +// inside it completes, though the scan is longer than the window. +func TestOpsChunk_VerifyOrphanPagesRenewTheWindow(t *testing.T) { + mem, _ := verifyCLIFixture(t) + withListStore(t, listStore{manifestFixtureFiler: mem, pageDelay: 80 * time.Millisecond}) + const window = 150 * time.Millisecond + start := time.Now() + code, out, errs := runChunk("verify", "--volume", "v1", "--master", "m:1", "--chunk-filer", "filer:18888", "--orphans", "--timeout", window.String()) + took := time.Since(start) + if code != 0 || !decodeVerify(t, out).Complete { + t.Fatalf("an orphan scan of %s with each page inside the %s window: exit %d, out %q, err %q; want clean", took, window, code, out, errs) + } + // Longer than one window: without a renewal per page the window would + // expire inside the scan. + if took <= window+50*time.Millisecond { + t.Fatalf("fixture: the scan took %s, not longer than the %s window; the test proves nothing", took, window) + } +} + +// A silent orphan scan, and a silent final HEAD confirmation, each end the +// pass within about one window, incomplete, naming the no-progress cause. +func TestOpsChunk_VerifySilentScanOrConfirmationNamesTheCause(t *testing.T) { + for name, s := range map[string]listStore{ + "orphan scan": {stallList: true}, + "final confirmation": {stallHead: 2}, + } { + t.Run(name, func(t *testing.T) { + mem, _ := verifyCLIFixture(t) + s.manifestFixtureFiler = mem + withListStore(t, s) + code, out, errs := runVerifyBounded(t, 5*time.Second, "--volume", "v1", "--master", "m:1", "--chunk-filer", "filer:18888", "--orphans", "--timeout", "200ms") + if code != chunkExitFailed { + t.Fatalf("a silent %s: exit %d, out %q, err %q; want incomplete (1)", name, code, out, errs) + } + a := decodeVerifyAnswer(t, out) + why := a.Message + if a.Code == "" { // the final confirmation answers its partial result + res := decodeVerify(t, out) + if res.Complete { + t.Fatalf("a silent %s: a complete result %+v", name, res) + } + why = res.Incomplete + } else if a.Verify.Complete || a.Code != chunkstore.CodeDeadlineExceeded || !a.Retryable { + t.Fatalf("a silent %s: answer %+v; want incomplete, retryable deadline_exceeded", name, a) + } + if !strings.Contains(why, "no object read completed") { + t.Fatalf("a silent %s: incomplete reason %q does not name the no-progress cause", name, why) + } + }) + } +} + +// --deadline bounds the single-filer start check too: a stalled check ends +// verify at the deadline, though --timeout is far longer, and names it. +func TestOpsChunk_VerifyDeadlineBoundsTheStartCheck(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checkSingleFiler = func(ctx context.Context, _ chunkstore.Filer) error { + select { + case <-ctx.Done(): + return ctx.Err() + case <-heldRelease: + return errHeldReleased + } + } + code, out, errs := runVerifyBounded(t, 5*time.Second, "--volume", "v1", "--chunk-filer", "filer:18888", "--timeout", "1m", "--deadline", "200ms") + a := decodeVerifyAnswer(t, out) + if code == 0 || !a.Retryable || !strings.Contains(a.Message, "--deadline 200ms reached") { + t.Fatalf("a stalled start check past --deadline: exit %d, answer %+v, err %q; want a retryable refusal naming the deadline", code, a, errs) + } +} + +// The window's boundary, on a fake clock: a read just inside the window +// renews it; a read just past it, before any ticker check, expires it +// instead (it is never renewed) and the pass is cancelled with the +// no-progress cause. +func TestVerifyWatchRenewsOnlyInsideTheWindow(t *testing.T) { + base := time.Now() + for _, tc := range []struct { + name string + at time.Duration + expired bool + }{{"inside", 99 * time.Millisecond, false}, {"past", 101 * time.Millisecond, true}} { + t.Run(tc.name, func(t *testing.T) { + now := base + var cause error + w := newVerifyWatch(100*time.Millisecond, func() time.Time { return now }, func(c error) { cause = c }) + now = base.Add(tc.at) + w.renew() + if got := cause != nil; got != tc.expired || w.expired != tc.expired { + t.Fatalf("a read at %s: expired %v, cancelled %v (%v); want %v", tc.at, w.expired, got, cause, tc.expired) + } + if tc.expired { + if !errors.Is(cause, errVerifyStalled) { + t.Fatalf("cancel cause %v, want errVerifyStalled", cause) + } + now = base.Add(tc.at + 10*time.Millisecond) + w.renew() + if !w.check() { + t.Fatal("an expired window was renewed by a later read") + } + return + } + now = base.Add(tc.at + 99*time.Millisecond) // within the renewed window + if w.check() { + t.Fatal("a window renewed inside it expired before its new end") + } + }) + } +} + +// A pass ended inside its final HEAD confirmations publishes no absence or +// reachability conclusion: with a real orphan planted, the control (no +// stall) reports it, and a stalled confirmation ends incomplete with +// OrphansChecked false and no ORPHAN or MISSING finding, naming the +// no-progress cause. +func TestOpsChunk_VerifyStalledConfirmationSuppressesOrphanConclusions(t *testing.T) { + for _, stalled := range []bool{false, true} { + t.Run(map[bool]string{false: "control", true: "stalled confirmation"}[stalled], func(t *testing.T) { + mem, chunk1 := verifyCLIFixture(t) + // A segment no reachable root names (the orphan scan covers roots + // and segments). + root := strings.TrimSuffix(chunk1, "/"+layout.NameChunk(1, bytes.Repeat([]byte{0x31}, 4096)).Path()) + c := layout.NameChunk(7, bytes.Repeat([]byte{0x77}, 4096)) + ownerID, err := layout.NewVolumeID() // the segment is never followed: any owner id + if err != nil { + t.Fatal(err) + } + _, segs, err := layout.Build(map[uint64]layout.Ref{7: {Owner: "v1", OwnerID: ownerID, Chunk: c}}) + if err != nil { + t.Fatal(err) + } + for n, b := range segs { + orphan := path.Join(root, n.Path()) + if err := mem.CreateEntry(context.Background(), path.Dir(orphan), &filerpb.Entry{Name: path.Base(orphan), Content: b}, true); err != nil { + t.Fatal(err) + } + } + s := listStore{manifestFixtureFiler: mem} + if stalled { + s.stallHead = 2 + } + withListStore(t, s) + code, out, errs := runVerifyBounded(t, 5*time.Second, "--volume", "v1", "--master", "m:1", "--chunk-filer", "filer:18888", "--orphans", "--timeout", "200ms") + res := decodeVerify(t, out) + orphans := 0 + for _, f := range res.Findings { + if f.Class == layout.FindOrphan || f.Class == layout.FindMissing { + orphans++ + } + } + if !stalled { + if code != chunkExitFindings || !res.Complete || !res.OrphansChecked || orphans == 0 { + t.Fatalf("control: exit %d, result %+v, err %q; want the planted orphan reported (exit 3)", code, res, errs) + } + return + } + if code != chunkExitFailed || res.Complete || res.OrphansChecked || orphans != 0 || !strings.Contains(res.Incomplete, "no object read completed") { + t.Fatalf("stalled confirmation: exit %d, result %+v, err %q; want incomplete, OrphansChecked false, no ORPHAN/MISSING, the no-progress cause", code, res, errs) + } + }) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete.go b/seaweed-block/cmd/sw-block/chunk_volume_delete.go new file mode 100644 index 0000000000..fe1a7089ca --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete.go @@ -0,0 +1,211 @@ +package main + +import ( + "context" + "errors" + "fmt" + "io" + "sync" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" +) + +// chunkVolumeDelete: sw-block ops chunk volume-delete --volume v +// --chunk-filer host:port --master host:port --request-id r deletes a +// volume in the layout kernel's order. The blockmaster holds the delete's +// authority: ReserveVolumeDeletion commits the reservation (refused while +// an authority line is live; no grant for the volume after it; never given +// back), and CheckVolumeNoLiveLease runs between the HEAD read and the +// update that marks HEAD deleting. A refused delete leaves the volume +// reserved; rerun with the same --request-id once its cause is cleared. A +// rerun on a deleted volume sweeps any object that landed late. +func chunkVolumeDelete(args []string, stdout, realStderr io.Writer) int { + // The command's whole stderr is best effort (diagWriter): its answer and + // exit never wait on a slow or stuck stderr. close runs after the answer + // is on stdout. + stderr := newDiagWriter(realStderr) + defer stderr.close() + c := newBCommand("volume-delete", 120*time.Second, stdout, stderr) + c.growing = true + c.fs.Lookup("timeout").Usage = "bound for one delete sweep and the no-progress window; progress permits further sweeps" + var vol volumeFlags + var requestID string + c.bindVolume(&vol, "volume", "volume") + c.fs.StringVar(&requestID, "request-id", "", "this delete's operation id; a rerun with the same id resumes it") + var ref chunkstore.VolumeRef + return c.run(args, true, func() (err error) { + if c.master == "" || requestID == "" || c.timeout <= 0 { + return errors.New("--master and --request-id are required; --timeout must be positive") + } + ref, err = vol.ref("volume") + return err + }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) { + conn, err := link.DialMasterFromEnv(c.master) + if err != nil { + return nil, err + } + defer conn.Close() + auth := &masterAuthority{lc: control.NewLifecycleServiceClient(conn), req: &control.MarkVolumeDeletingRequest{VolumeId: ref.Name, Token: requestID}} + skipped, err := deleteVolumeWithProgress(ctx, cat, ref, auth, c.timeout, stderr) + if err != nil { + return nil, err + } + out := map[string]any{"volume": ref.Dir(), "state": "deleted"} + if len(skipped) > 0 { + // Roots HEAD names whose objects an earlier run already deleted + // (after releasing every source): reported, not read. + names := make([]string, 0, len(skipped)) + for _, rn := range skipped { + names = append(names, rn.String()) + } + out["already_deleted_roots"] = names + } + return out, nil + }) +} + +// masterAuthority is the layout delete's authority, held by the +// blockmaster: both operations are its RPCs, nothing is decided here. +type masterAuthority struct { + lc control.LifecycleServiceClient + req *control.MarkVolumeDeletingRequest +} + +func (m *masterAuthority) Reserve(ctx context.Context) error { + _, err := m.lc.ReserveVolumeDeletion(ctx, m.req) + return authorityErr(err) +} + +func (m *masterAuthority) NoLiveLease(ctx context.Context) error { + _, err := m.lc.CheckVolumeNoLiveLease(ctx, m.req) + return authorityErr(err) +} + +// authorityErr: FailedPrecondition and InvalidArgument are definite +// refusals; anything else (unavailable, deadline, a lost response) leaves +// the outcome unknown and a rerun decides. +func authorityErr(err error) error { + switch status.Code(err) { + case codes.OK: + return nil + case codes.FailedPrecondition, codes.InvalidArgument: + return fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, err) + } + return err +} + +// deleteVolumeWithProgress repeats the existing resumable kernel operation. +// There is no new durable cursor: each sweep lists what remains. A confirmed +// removal extends the no-progress window; an expired sweep alone does not end +// a growing delete. Errors and progress use stderr, leaving stdout one answer; +// stderr must not block (the command passes its diagWriter). +func deleteVolumeWithProgress(ctx context.Context, cat *chunkstore.BCatalog, ref chunkstore.VolumeRef, auth layout.DeleteAuthority, bound time.Duration, stderr io.Writer) ([]layout.RootName, error) { + done := map[string]bool{} + known := map[string]bool{} + total := 0 + object := "listing or HEAD" + lastProgress := time.Now() + skippedSet := map[layout.RootName]bool{} + var lastErr error + stalled := func(err error) error { + return &chunkstore.CatalogError{Code: "unavailable", Retryable: true, Message: fmt.Sprintf("deleted %d of %d objects; no progress at %s; retry with the same --request-id", len(done), total, object), Err: err} + } + // stderr is the command's diagWriter: its writes never block, so a slow + // stderr delays neither a sweep, the retry window nor the answer. + // A sweep stuck inside the store says so while it waits (every quarter of + // the bound, at most every 5 s): a stalled store is told apart from a slow + // delete before the bound ends the command. mu guards the sweep's counters, + // which the progress callback and the reporter share. + var mu sync.Mutex + stallEvery := min(5*time.Second, max(bound/4, 50*time.Millisecond)) + reportStalls := func(stop <-chan struct{}) { + tk := time.NewTicker(stallEvery) + defer tk.Stop() + for { + select { + case <-stop: + return + case <-tk.C: + } + mu.Lock() + idle, n, of, at := time.Since(lastProgress), len(done), total, object + mu.Unlock() + if idle >= stallEvery { + fmt.Fprintf(stderr, "volume-delete: no progress for %s, waiting on %s (deleted %d of %d objects)\n", idle.Round(time.Millisecond), at, n, of) + } + } + } + for { + if lastErr != nil && time.Since(lastProgress) >= bound { + return nil, stalled(lastErr) + } + object = "listing or HEAD" + batch, cancel := context.WithDeadline(ctx, minTime(time.Now().Add(bound), lastProgress.Add(bound))) + stop, reported := make(chan struct{}), make(chan struct{}) + go func() { defer close(reported); reportStalls(stop) }() + skipped, err := cat.DeleteVolume(batch, ref, auth, func(p layout.DeleteProgress) { + mu.Lock() + defer mu.Unlock() + if p.Object == "" { + present := make(map[string]bool, len(p.Objects)) + for _, rel := range p.Objects { + known[rel] = true + present[rel] = true + } + // A lost delete answer may have removed the object. Its absence + // in the next complete listing is progress too. + for rel := range known { + if !present[rel] && !done[rel] { + done[rel] = true + lastProgress = time.Now() + } + } + total = len(known) + } else { + object = p.Object + if p.Done && !done[p.Object] { + done[p.Object] = true + lastProgress = time.Now() + } + } + }) + cancel() + close(stop) + <-reported // prompt: the reporter never blocks on stderr + fmt.Fprintf(stderr, "volume-delete: deleted %d of %d objects\n", len(done), total) + for _, rn := range skipped { + skippedSet[rn] = true + } + if err == nil { + all := make([]layout.RootName, 0, len(skippedSet)) + for rn := range skippedSet { + all = append(all, rn) + } + return all, nil + } + transient := errors.Is(err, context.DeadlineExceeded) || status.Code(err) == codes.DeadlineExceeded || status.Code(err) == codes.Unavailable + if !transient { + return nil, err + } + remaining := bound - time.Since(lastProgress) + if remaining <= 0 || ctx.Err() != nil { + return nil, stalled(err) + } + lastErr = err + pause := min(100*time.Millisecond, remaining) + timer := time.NewTimer(pause) + select { + case <-ctx.Done(): + timer.Stop() + return nil, ctx.Err() + case <-timer.C: + } + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete_progress_test.go b/seaweed-block/cmd/sw-block/chunk_volume_delete_progress_test.go new file mode 100644 index 0000000000..28cce3db9b --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete_progress_test.go @@ -0,0 +1,291 @@ +package main + +import ( + "bytes" + "context" + "io" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type transientDeleteFiler struct { + *memChunkStore + seen map[string]bool + stuck bool + calls int + code codes.Code + absent bool + lost bool +} + +func (f *transientDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { + f.calls++ + key := dir + "/" + name + if f.absent { + if err := f.memChunkStore.DeleteEntry(ctx, dir, name, expected); err != nil { + return err + } + return chunkstore.ErrNotFound + } + if f.stuck || !f.seen[key] { + f.seen[key] = true + if f.lost { + if err := f.memChunkStore.DeleteEntry(ctx, dir, name, expected); err != nil { + return err + } + } + return status.Error(f.code, "object deadline") + } + return f.memChunkStore.DeleteEntry(ctx, dir, name, expected) +} + +func TestVolumeDeleteContinuesAcrossTransientObjectFailures(t *testing.T) { + for _, tc := range []struct { + name string + code codes.Code + stuck, absent, lost bool + }{ + {"deadline-progress", codes.DeadlineExceeded, false, false, false}, + {"unavailable-progress", codes.Unavailable, false, false, false}, + {"deadline-stuck", codes.DeadlineExceeded, true, false, false}, + {"unavailable-stuck", codes.Unavailable, true, false, false}, + {"already-absent", codes.OK, false, true, false}, + {"lost-delete-answer", codes.DeadlineExceeded, false, false, true}, + } { + name, stuck := tc.name, tc.stuck + t.Run(name, func(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, name, "daily") + f := &transientDeleteFiler{memChunkStore: store, seen: map[string]bool{}, stuck: stuck, code: tc.code, absent: tc.absent, lost: tc.lost} + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return f, func() error { return nil }, nil } + addr := startFakeLifecycle(t, &fakeLifecycle{}) + started := time.Now() + code, out, logs := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "delete-progress", "--timeout", "150ms"})...) + if stuck { + e := chunkErrorOut(t, out) + if code != 1 || e.Code != "unavailable" || !e.Retryable || !strings.Contains(e.Message, "deleted 0 of") || !strings.Contains(e.Message, "/") || !strings.Contains(e.Message, "object deadline") { + t.Fatalf("stalled delete: code=%d out=%s logs=%s", code, out, logs) + } + if time.Since(started) > 3*time.Second { + t.Fatal("no-progress window was not bounded") + } + f.stuck = false + code, out, logs = runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "delete-progress", "--timeout", "150ms"})...) + if code != 0 || !strings.Contains(out, `"state":"deleted"`) { + t.Fatalf("resume same delete: %d %s %s", code, out, logs) + } + } else if code != 0 || !strings.Contains(out, `"state":"deleted"`) || !strings.Contains(logs, "deleted 2 of 2") || (!tc.absent && !tc.lost && f.calls < 4) { + t.Fatalf("progressing delete: code=%d calls=%d out=%s logs=%s", code, f.calls, out, logs) + } + }) + } +} + +// A real expired child context must not expire the next sweep. Unlike the +// immediate error controls, this filer blocks an exchange until its deadline. +type waitingDeleteFiler struct { + *memChunkStore + bound time.Duration + calls int + waited bool + stall bool + removedAt time.Time +} + +func (f *waitingDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { + f.calls++ + if f.calls == 1 { + timer := time.NewTimer(f.bound / 2) + defer timer.Stop() + select { + case <-timer.C: + case <-ctx.Done(): + return ctx.Err() + } + err := f.memChunkStore.DeleteEntry(ctx, dir, name, expected) + if err == nil { + f.removedAt = time.Now() + } + return err + } + if f.stall { + return status.Error(codes.Unavailable, "stalled after first removal") + } + if !f.waited { + f.waited = true + <-ctx.Done() + return ctx.Err() + } + return f.memChunkStore.DeleteEntry(ctx, dir, name, expected) +} + +func TestVolumeDeleteRefreshesAnExpiredSweepAndWaitsFromLastRemoval(t *testing.T) { + for _, stall := range []bool{false, true} { + name := "expired-sweep" + if stall { + name = "progress-then-stall" + } + t.Run(name, func(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, name, "daily") + bound := 600 * time.Millisecond + f := &waitingDeleteFiler{memChunkStore: store, bound: bound, stall: stall} + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return f, func() error { return nil }, nil } + addr := startFakeLifecycle(t, &fakeLifecycle{}) + code, out, logs := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "timed-delete", "--timeout", bound.String()})...) + if f.removedAt.IsZero() { + t.Fatalf("fixture made no progress: %d %s", code, out) + } + if !stall { + if code != 0 || !f.waited || !strings.Contains(logs, "deleted 2 of 2") { + t.Fatalf("fresh sweep: %d %s %s", code, out, logs) + } + return + } + e := chunkErrorOut(t, out) + if code != 1 || e.Code != "unavailable" || !e.Retryable || !strings.Contains(e.Message, "deleted 1 of 2") || !strings.Contains(e.Message, "stalled after first removal") { + t.Fatalf("stall after progress: %d %s", code, out) + } + if elapsed := time.Since(f.removedAt); elapsed < bound || elapsed > bound+2*time.Second { + t.Fatalf("no-progress window from last removal = %s, want [%s,%s]", elapsed, bound, bound+2*time.Second) + } + }) + } +} + +// blockedDeleteFiler holds every object delete until the call's deadline: a +// store that accepts the call and never answers (its only volume server gone). +type blockedDeleteFiler struct{ *memChunkStore } + +func (f *blockedDeleteFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { + <-ctx.Done() + return ctx.Err() +} + +// A sweep stuck inside the store says so on stderr while it waits, naming +// the object and how long nothing has moved, so a stalled store is told apart +// from a slow delete before the no-progress bound ends the command. +func TestVolumeDeleteReportsAStalledStoreWhileItWaits(t *testing.T) { + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "stalled-store", "daily") + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return &blockedDeleteFiler{memChunkStore: store}, func() error { return nil }, nil + } + addr := startFakeLifecycle(t, &fakeLifecycle{}) + code, out, logs := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "stalled", "--timeout", "800ms"})...) + if e := chunkErrorOut(t, out); code != 1 || e.Code != "unavailable" { + t.Fatalf("stalled store: code=%d out=%s logs=%s; want the bounded unavailable answer", code, out, logs) + } + var stall string + for _, l := range strings.Split(logs, "\n") { + if strings.Contains(l, "no progress for") { + stall = l + break + } + } + if stall == "" || !strings.Contains(stall, "waiting on") || !strings.Contains(stall, "deleted 0 of") { + t.Fatalf("no stall report while the sweep waited: %q (logs %s)", stall, logs) + } +} + +// overlapStderr is a stderr that is NOT safe for concurrent use, as a writer +// handed to a command need not be: it flags any two overlapping Write calls. +// Each of the delete's own progress lines ("volume-delete: ...") takes delay. +type overlapStderr struct { + inFlight atomic.Int32 + overlapped atomic.Bool + b bytes.Buffer + delay time.Duration +} + +func (w *overlapStderr) Write(p []byte) (int, error) { + if w.inFlight.Add(1) > 1 { + w.overlapped.Store(true) + } + defer w.inFlight.Add(-1) + if bytes.HasPrefix(p, []byte("volume-delete:")) { + time.Sleep(w.delay) + } + return w.b.Write(p) +} + +// stuckStderr is a stderr whose writes never return (until the test ends). +type stuckStderr struct{ release chan struct{} } + +func (w *stuckStderr) Write(p []byte) (int, error) { + <-w.release + return len(p), nil +} + +// runVolumeDelete runs the delete on a store that never answers, with stderr +// as given, and returns its exit status, its stdout and how long it took; +// within limit, or the test fails. +func runVolumeDelete(t *testing.T, name string, stderr io.Writer, bound, limit time.Duration) (int, string, time.Duration) { + t.Helper() + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, name, "daily") + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return &blockedDeleteFiler{memChunkStore: store}, func() error { return nil }, nil + } + addr := startFakeLifecycle(t, &fakeLifecycle{}) + args := append([]string{"ops", "chunk"}, cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", name, "--timeout", bound.String()})...) + var out bytes.Buffer + type result struct { + code int + took time.Duration + } + got := make(chan result, 1) + started := time.Now() + go func() { c := run(args, &out, stderr); got <- result{c, time.Since(started)} }() + select { + case r := <-got: + return r.code, out.String(), r.took + case <-time.After(limit): + t.Fatalf("no answer and no exit within %s", limit) + } + return 0, "", 0 +} + +// Diagnostics never gate the answer: with a stderr whose writes never +// return, the answer reaches stdout and the command exits, as with a fast +// stderr, within the bound plus a short drain. +func TestVolumeDeleteAnswerDoesNotWaitOnAStuckStderr(t *testing.T) { + bound := 400 * time.Millisecond + var fastErr bytes.Buffer + fastCode, fastOut, _ := runVolumeDelete(t, "fast-stderr", &fastErr, bound, 10*time.Second) + stuck := &stuckStderr{release: make(chan struct{})} + t.Cleanup(func() { close(stuck.release) }) + code, out, took := runVolumeDelete(t, "stuck-stderr", stuck, bound, 10*time.Second) + fast, got := chunkErrorOut(t, fastOut), chunkErrorOut(t, out) + if code != fastCode || got.Code != fast.Code || got.Retryable != fast.Retryable || got.Code != "unavailable" { + t.Fatalf("stuck stderr changed the answer: exit %d %+v, with a fast stderr exit %d %+v", code, got, fastCode, fast) + } + if took > bound+time.Second { + t.Fatalf("the answer and exit took %s on a stuck stderr (bound %s)", took, bound) + } +} + +// The command owns its stderr: with a stderr that is not safe for concurrent +// use and takes 1 s per progress line, no two writes overlap, and the answer +// is unchanged. +func TestVolumeDeleteNeverWritesStderrConcurrently(t *testing.T) { + slow := &overlapStderr{delay: time.Second} + code, out, _ := runVolumeDelete(t, "overlap-stderr", slow, 400*time.Millisecond, 10*time.Second) + if e := chunkErrorOut(t, out); code != 1 || e.Code != "unavailable" { + t.Fatalf("answer %d %+v", code, e) + } + time.Sleep(1500 * time.Millisecond) // any write still in flight lands now + if slow.overlapped.Load() { + t.Fatal("two writes to stderr overlapped") + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete_refusal_test.go b/seaweed-block/cmd/sw-block/chunk_volume_delete_refusal_test.go new file mode 100644 index 0000000000..bbe385a468 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete_refusal_test.go @@ -0,0 +1,62 @@ +package main + +import ( + "bytes" + "context" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// A delete of an established volume (its primary attested its write-ACK +// stores, so creation is over) whose line holds a live lease is refused by +// the real master's reservation before anything is persisted, and the +// command's JSON answer says so: code not_admitted and the "refused before +// persistence" sentence. HEAD stays live and no reservation is recorded. +func TestOpsChunkVolumeDeleteRefusalSaysNothingWasPersisted(t *testing.T) { + cfg := master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }} + h, stop := startDeleteMaster(t, cfg) + defer stop() + seedForcedVolumeLease(t, h, true) + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + // The primary's attestation of its stores ends creation, as its heartbeat + // carries it in production. + if _, err := control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ReadsLevel: 1, ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "vol-f", ReplicaId: "r1", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"}}, + StoreAttestation: &control.StoreAttestation{VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1, Stores: []*control.AttestedStore{{ReplicaId: "r1", StoreId: bytes.Repeat([]byte{7}, 16)}}}}); err != nil { + t.Fatal(err) + } + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "vol-f", "daily") + code, out, stderr := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", h.Addr(), "--request-id", "live-lease"})...) + body := chunkErrorOut(t, out) + t.Logf("exit %d answer %+v", code, body) + if code != chunkExitFailed || body.Code != "not_admitted" || + !strings.Contains(body.Message, "deletion refused before persistence") { + t.Fatalf("volume-delete with a live lease: exit %d answer %+v stderr %s; want not_admitted saying it was refused before persistence", code, body, stderr) + } + if h.Lifecycle().Deletions.Reserved("vol-f") { + t.Fatal("the refused delete recorded a reservation") + } + cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + if hd, found, err := cat.ReadHead(context.Background(), v); err != nil || !found || hd.State != layout.StateLive { + t.Fatalf("HEAD after the refused delete: %+v %v %v; want live", hd, found, err) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete_reserved_test.go b/seaweed-block/cmd/sw-block/chunk_volume_delete_reserved_test.go new file mode 100644 index 0000000000..f7a524f3a5 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete_reserved_test.go @@ -0,0 +1,100 @@ +package main + +import ( + "bytes" + "context" + "reflect" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// A volume-delete refused with snapshot_has_dependents has already reserved +// the volume at the real master: workspace show then answers that the volume +// is being deleted (exit 1), and HEAD with its snapshots is unchanged. The +// control is a delete refused before any reservation (an established volume +// under a live lease): show still answers the volume normally. +func TestOpsChunkVolumeDeleteRefusedByDependentsLeavesTheVolumeReserved(t *testing.T) { + for _, c := range []struct { + name string + liveLease bool // an established volume whose line holds a live lease + wantCode string + reserved bool + }{ + {"refused by dependents after the reservation", false, "snapshot_has_dependents", true}, + {"control: refused before the reservation", true, "not_admitted", false}, + } { + t.Run(c.name, func(t *testing.T) { + cfg := master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }} + h, stop := startDeleteMaster(t, cfg) + defer stop() + seedForcedVolumeLease(t, h, c.liveLease) + if c.liveLease { + attestStores(t, h) + } + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "vol-f", "daily") + tid, _ := layout.NewVolumeID() + if code, out, errs := runChunk(cliArgs("restore", volArgs("source", v), volArgs("target", chunkstore.VolumeRef{Name: "t", ID: tid}), []string{"--snapshot", "daily"})...); code != 0 { + t.Fatalf("restore: %d %q %q", code, out, errs) + } + cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + head := func() layout.Head { + hd, found, err := cat.ReadHead(context.Background(), v) + if err != nil || !found { + t.Fatalf("HEAD: %v %v", found, err) + } + return hd + } + before := head() + code, out, stderr := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", h.Addr(), "--request-id", "del-vol-f"})...) + if body := chunkErrorOut(t, out); code != chunkExitFailed || body.Code != c.wantCode { + t.Fatalf("volume-delete: exit %d answer %+v stderr %s; want %s", code, body, stderr, c.wantCode) + } + if got := h.Lifecycle().Deletions.Reserved("vol-f"); got != c.reserved { + t.Fatalf("reserved after the refused delete: %v; want %v", got, c.reserved) + } + if after := head(); !reflect.DeepEqual(after, before) || len(after.Snapshots["daily"].Dependents) != 1 { + t.Fatalf("HEAD changed by the refused delete: before %+v, after %+v", before, after) + } + showCode, showOut, showErr := runCLI([]string{"ops", "workspace", "show", "--master", h.Addr(), "--volume", "vol-f"}) + t.Logf("show: exit %d\n%s%s", showCode, showOut, showErr) + deleting := strings.Contains(showOut+showErr, "volume is being deleted") + if c.reserved && (showCode != 1 || !deleting) { + t.Fatalf("show after a delete refused by dependents: exit %d; want 1 with \"volume is being deleted\"", showCode) + } + if !c.reserved && (showCode != 0 || deleting || !strings.Contains(showOut, "volume: vol-f")) { + t.Fatalf("show after a delete refused before the reservation: exit %d; want the volume shown normally", showCode) + } + }) + } +} + +// attestStores sends vol-f's primary attestation of its write-ACK stores, as +// its heartbeat carries it in production: the volume's creation is over. +func attestStores(t *testing.T, h *master.Host) { + t.Helper() + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ReadsLevel: 1, ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "vol-f", ReplicaId: "r1", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"}}, + StoreAttestation: &control.StoreAttestation{VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1, Stores: []*control.AttestedStore{{ReplicaId: "r1", StoreId: bytes.Repeat([]byte{7}, 16)}}}}); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete_schedule_test.go b/seaweed-block/cmd/sw-block/chunk_volume_delete_schedule_test.go new file mode 100644 index 0000000000..50d7f8d978 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete_schedule_test.go @@ -0,0 +1,95 @@ +package main + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +// The real command reserves through the real master while a first lease +// request is paused at RPC ingress. At the command's CAS-time lease check, +// resume that request: committed exclusion must refuse it before the check +// can certify absence. The authority package separately pauses every writer +// immediately before its grant lock; this test composes the transport path. +func TestOpsChunkVolumeDeleteClosesAPausedFirstGrant(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + paused, resume := make(chan struct{}), make(chan struct{}) + grantResult := make(chan error, 1) + var checked atomic.Bool + intercept := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, next grpc.UnaryHandler) (any, error) { + switch info.FullMethod { + case control.WorkspaceService_RenewWorkspaceLease_FullMethodName: + close(paused) + select { + case <-resume: + case <-ctx.Done(): + return nil, ctx.Err() + } + case control.LifecycleService_CheckVolumeNoLiveLease_FullMethodName: + close(resume) + select { + case err := <-grantResult: + if status.Code(err) != codes.FailedPrecondition { + return nil, status.Errorf(codes.Internal, "paused grant escaped reservation: %v", err) + } + case <-ctx.Done(): + return nil, ctx.Err() + } + checked.Store(true) + } + return next(ctx, req) + } + cfg := master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + ServerOptions: []grpc.ServerOption{grpc.ChainUnaryInterceptor(intercept)}, + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }} + h, stop := startDeleteMaster(t, cfg) + defer stop() + seedForcedVolumeLease(t, h, false) + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + go func() { + _, err := control.NewWorkspaceServiceClient(conn).RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}) + grantResult <- err + }() + select { + case <-paused: + case <-ctx.Done(): + t.Fatal("first grant did not reach RPC ingress") + } + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "vol-f", "daily") + code, out, stderr := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", h.Addr(), "--request-id", "paused-first-grant"})...) + if code != 0 || !checked.Load() { + t.Fatalf("delete exit=%d checked=%v out=%s err=%s", code, checked.Load(), out, stderr) + } + cat, err := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + head, found, err := cat.ReadHead(ctx, v) + if err != nil || !found || head.State != layout.StateDeleted { + t.Fatalf("final HEAD: %+v found=%v err=%v", head, found, err) + } + if !h.Lifecycle().Deletions.CommittedSnapshot("vol-f") { + t.Fatal("command did not commit the real master's reservation") + } + if s := h.Publisher().WorkspaceState("vol-f"); s != nil && s.Lease != nil { + t.Fatalf("late request created a lease: %+v", s.Lease) + } +} diff --git a/seaweed-block/cmd/sw-block/cluster_format.go b/seaweed-block/cmd/sw-block/cluster_format.go new file mode 100644 index 0000000000..028a9590e3 --- /dev/null +++ b/seaweed-block/cmd/sw-block/cluster_format.go @@ -0,0 +1,330 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "io" + "sort" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// clusterLifecycleDial opens the master's lifecycle service; a test +// replaces it. +var clusterLifecycleDial = func(addr string) (control.LifecycleServiceClient, func() error, error) { + conn, err := link.DialMasterFromEnv(addr) + if err != nil { + return nil, nil, err + } + return control.NewLifecycleServiceClient(conn), conn.Close, nil +} + +// runCluster is "sw-block cluster finalize-format|format-level|retire-host". +func runCluster(args []string, stdout, stderr io.Writer) int { + if len(args) == 0 { + fmt.Fprintln(stderr, "sw-block: expected subcommand cluster finalize-format|format-level|retire-host") + return ops.VolumeStatusExitInvalid + } + switch args[0] { + case "finalize-format": + return runClusterFinalizeFormat(args[1:], stdout, stderr) + case "format-level": + return runClusterFormatLevel(args[1:], stdout, stderr) + case "retire-host": + return runClusterRetireHost(args[1:], stdout, stderr) + } + fmt.Fprintf(stderr, "sw-block: unknown subcommand cluster %q\n", args[0]) + return ops.VolumeStatusExitInvalid +} + +// clusterFormatLevel reads the cluster's format level from the master. +func clusterFormatLevel(ctx context.Context, master string) (uint32, error) { + c, closeFn, err := clusterLifecycleDial(master) + if err != nil { + return 0, err + } + defer closeFn() + resp, err := c.FormatLevel(ctx, &control.FormatLevelRequest{}) + if err != nil { + return 0, err + } + return resp.GetFormatLevel(), nil +} + +// runClusterFormatLevel prints the cluster's format level: 0 (v1.0 +// semantics; an upgraded cluster before its finalize) or 1. +func runClusterFormatLevel(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block cluster format-level", flag.ContinueOnError) + fs.SetOutput(stderr) + master := fs.String("master", "", "blockmaster gRPC address (required)") + timeout := fs.Duration("timeout", 30*time.Second, "how long to wait for the master's answer") + if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" { + fmt.Fprintln(stderr, "usage: sw-block cluster format-level --master host:port [--timeout 30s]") + return ops.VolumeStatusExitInvalid + } + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + level, err := clusterFormatLevel(ctx, *master) + if err != nil { + fmt.Fprintln(stderr, "sw-block: cluster format-level:", err) + return ops.VolumeStatusExitUnhealthy + } + fmt.Fprintf(stdout, "format level %d\n", level) + return 0 +} + +// finalize-format's exit codes, part of its contract: a script decides by +// them and by the --json answer, never by message text. +const ( + finalizeExitOK = 0 // finalized, or already finalized + finalizeExitFailed = 1 // any other failure, a failed durable write included + finalizeExitRefused = 2 // the master refused: hosts below the level + finalizeExitTempFail = 75 // transient: the master unreachable (EX_TEMPFAIL) +) + +// finalizeAnswer is finalize-format's --json answer, one shape for every +// outcome. Result is finalized, already, refused, unavailable or failed; +// Reason the master's typed reason (or the gRPC code, "" on success); Hosts +// the refused hosts, each with what it reported (empty otherwise); Listed the +// hosts the master could not confirm and did not block on (a held volume +// with no report, a host with no report, an old process holding no volume), +// on a refusal and on a finalize alike. +type finalizeAnswer struct { + Result string `json:"result"` + Reason string `json:"reason"` + Hosts []finalizeHost `json:"hosts"` + Listed []finalizeHost `json:"listed"` + FormatLevel uint32 `json:"format_level"` + Message string `json:"message"` +} + +type finalizeHost struct { + Server string `json:"server"` + Reported string `json:"reported"` +} + +// runClusterFinalizeFormat raises the cluster's format level to 1. Going +// back to v1.0.x works only before it: afterwards a v1.0.x master or holder +// refuses the store (an expected refusal, not damage). The master refuses +// it only while a process holding a volume reports a lower level, naming +// each one; the hosts it could not confirm are listed, not blocking. +func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int) { + fs := flag.NewFlagSet("sw-block cluster finalize-format", flag.ContinueOnError) + fs.SetOutput(stderr) + master := fs.String("master", "", "blockmaster gRPC address (required)") + timeout := fs.Duration("timeout", 30*time.Second, "how long to wait for the master's answer") + // The flag is declared for parsing and help only: the mode comes from the + // arguments as a whole, read before parsing, so a bad option in any + // position cannot leave it half-parsed. + fs.Bool("json", false, "print the typed answer as JSON: result, reason, hosts, listed, format_level, message") + jsonMode := jsonRequested(args) + jsonOut := &jsonMode + answer := finalizeAnswer{Hosts: []finalizeHost{}, Listed: []finalizeHost{}} + defer func() { + if *jsonOut { + if err := json.NewEncoder(stdout).Encode(answer); err != nil { + fmt.Fprintln(stderr, "sw-block: cluster finalize-format: JSON output:", err) + if code == finalizeExitOK { + code = finalizeExitFailed // the answer a script reads was not written + } + } + } + }() + fail := func(result, reason, msg string, code int) int { + answer.Result, answer.Reason, answer.Message = result, reason, msg + fmt.Fprintln(stderr, "sw-block: cluster finalize-format:", msg) + return code + } + if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" { + fmt.Fprintln(stderr, "usage: sw-block cluster finalize-format --master host:port [--timeout 30s] [--json]") + answer.Result, answer.Reason, answer.Message = "failed", "usage", "--master is required" + return finalizeExitFailed + } + c, closeFn, err := clusterLifecycleDial(*master) + if err != nil { + return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail) + } + defer closeFn() + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + resp, err := c.FinalizeFormat(ctx, &control.FinalizeFormatRequest{Level: 1}, grpc.WaitForReady(false)) + if err != nil { + msg := status.Convert(err).Message() + reason, md := lifecycleclient.ReasonDetail(err) + if reason == "" { + reason = status.Code(err).String() + } + switch status.Code(err) { + case codes.FailedPrecondition: + answer.Hosts = metadataHosts(md, lifecycleclient.HostMetadataPrefix) + answer.Listed = metadataHosts(md, lifecycleclient.UnconfirmedMetadataPrefix) + return fail("refused", reason, msg, finalizeExitRefused) + case codes.Unavailable, codes.DeadlineExceeded: + return fail("unavailable", reason, msg, finalizeExitTempFail) + } + return fail("failed", reason, msg, finalizeExitFailed) + } + answer.FormatLevel = resp.GetFormatLevel() + for _, u := range resp.GetUnconfirmed() { + answer.Listed = append(answer.Listed, finalizeHost{Server: u.GetServerId(), Reported: u.GetDetail()}) + if !*jsonOut { + fmt.Fprintf(stdout, "not confirmed, not blocking: %s (%s)\n", u.GetServerId(), u.GetDetail()) + } + } + if resp.GetAlready() { + answer.Result, answer.Message = "already", "already finalized; nothing written" + if !*jsonOut { + fmt.Fprintf(stdout, "format level %d (already finalized; nothing written)\n", resp.GetFormatLevel()) + } + return finalizeExitOK + } + answer.Result, answer.Message = "finalized", "v1.0.x binaries now refuse this cluster's stores" + if !*jsonOut { + fmt.Fprintf(stdout, "format level %d finalized: v1.0.x binaries now refuse this cluster's stores\n", resp.GetFormatLevel()) + } + return finalizeExitOK +} + +// jsonRequested says whether args ask for JSON output (-json, --json, or +// either with =true), read before flag parsing; the last one counts, and +// nothing after a "--" terminator does. +func jsonRequested(args []string) bool { + want := false + for _, a := range args { + if a == "--" { + break + } + name := strings.TrimLeft(a, "-") + if name == a { + continue // not an option + } + val := "" + if i := strings.IndexByte(name, '='); i >= 0 { + name, val = name[:i], name[i+1:] + } + if name != "json" { + continue + } + switch val { + case "", "1", "t", "T", "true", "TRUE", "True": + want = true + default: + want = false + } + } + return want +} + +// metadataHosts reads the hosts keyed by prefix from the refusal's typed +// metadata, sorted by server id. +func metadataHosts(md map[string]string, prefix string) []finalizeHost { + hosts := []finalizeHost{} + for k, v := range md { + if server, ok := strings.CutPrefix(k, prefix); ok { + hosts = append(hosts, finalizeHost{Server: server, Reported: v}) + } + } + sort.Slice(hosts, func(i, j int) bool { return hosts[i].Server < hosts[j].Server }) + return hosts +} + +// retireAnswer is retire-host's --json answer, one shape for every outcome. +// Result is retired, refused, unavailable or failed; Reason the master's +// typed reason (or the gRPC code, "" on success); Volumes the volumes the +// host still holds when the retire is refused for them (empty otherwise). +type retireAnswer struct { + Result string `json:"result"` + Reason string `json:"reason"` + Server string `json:"server"` + Volumes []string `json:"volumes"` + Message string `json:"message"` +} + +// runClusterRetireHost removes a registered host from the node inventory. +// The master refuses it while the host holds a lease or an assignment. Exit +// codes as finalize-format's: 0 retired, 2 refused, 75 the master could not +// be reached (EX_TEMPFAIL), 1 any other failure, a usage error included. +func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) { + fs := flag.NewFlagSet("sw-block cluster retire-host", flag.ContinueOnError) + fs.SetOutput(stderr) + master := fs.String("master", "", "blockmaster gRPC address (required)") + server := fs.String("server", "", "the server id to retire (required)") + confirm := fs.String("confirm", "", "the same server id again (required)") + timeout := fs.Duration("timeout", 30*time.Second, "how long to wait for the master's answer") + // Declared for parsing and help only; the mode is read from the + // arguments as a whole, so a bad option in any position cannot half-parse it. + fs.Bool("json", false, "print the typed answer as JSON: result, reason, server, volumes, message") + jsonMode := jsonRequested(args) + answer := retireAnswer{Volumes: []string{}} + defer func() { + if jsonMode { + if err := json.NewEncoder(stdout).Encode(answer); err != nil { + fmt.Fprintln(stderr, "sw-block: cluster retire-host: JSON output:", err) + if code == finalizeExitOK { + code = finalizeExitFailed // the answer a script reads was not written + } + } + } + }() + fail := func(result, reason, msg string, code int) int { + answer.Result, answer.Reason, answer.Message = result, reason, msg + fmt.Fprintln(stderr, "sw-block: cluster retire-host:", msg) + return code + } + if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" || *server == "" || *confirm == "" { + fmt.Fprintln(stderr, "usage: sw-block cluster retire-host --master host:port --server ID --confirm ID [--timeout 30s] [--json]") + answer.Result, answer.Reason, answer.Message = "failed", "usage", "--master, --server and --confirm are required" + return finalizeExitFailed + } + answer.Server = *server + c, closeFn, err := clusterLifecycleDial(*master) + if err != nil { + return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail) + } + defer closeFn() + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + if _, err := c.RetireHost(ctx, &control.RetireHostRequest{ServerId: *server, Confirm: *confirm}); err != nil { + msg := status.Convert(err).Message() + reason, md := lifecycleclient.ReasonDetail(err) + if reason == "" { + reason = status.Code(err).String() + } + switch status.Code(err) { + case codes.FailedPrecondition: + answer.Volumes = retireVolumes(md) + return fail("refused", reason, msg, finalizeExitRefused) + case codes.Unavailable, codes.DeadlineExceeded: + return fail("unavailable", reason, msg, finalizeExitTempFail) + } + return fail("failed", reason, msg, finalizeExitFailed) + } + answer.Result, answer.Message = "retired", "host retired from the node inventory" + if !jsonMode { + fmt.Fprintf(stdout, "host %s retired\n", *server) + } + return finalizeExitOK +} + +// retireVolumes reads the held volumes from the refusal's typed metadata, +// sorted. +func retireVolumes(md map[string]string) []string { + vols := []string{} + for k := range md { + if v, ok := strings.CutPrefix(k, lifecycleclient.VolumeMetadataPrefix); ok { + vols = append(vols, v) + } + } + sort.Strings(vols) + return vols +} diff --git a/seaweed-block/cmd/sw-block/cluster_format_json_test.go b/seaweed-block/cmd/sw-block/cluster_format_json_test.go new file mode 100644 index 0000000000..e24770d975 --- /dev/null +++ b/seaweed-block/cmd/sw-block/cluster_format_json_test.go @@ -0,0 +1,263 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "reflect" + "sort" + "testing" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// finalize-format's answer is typed: exit 0 for finalized or already, 2 for +// a refusal, 75 for a transient failure (the master unreachable), 1 for any +// other failure (a failed durable write included); --json prints the same +// keys for every outcome, and a refusal lists each refused host from the +// master's typed metadata, never from its message text. The hosts the master +// could not confirm are listed, not blocking, on a refusal (metadata) and on +// a finalize (the response) alike. +func TestClusterFinalizeFormatTypedAnswer(t *testing.T) { + refused := lifecycleclient.WithReasonMetadata(status.New(codes.FailedPrecondition, "message text a script must not parse"), + lifecycleclient.ReasonFormatHostsTooOld, map[string]string{ + lifecycleclient.HostMetadataPrefix + "node-c": "volume v2 reads level 0", + lifecycleclient.HostMetadataPrefix + "node-b": "volume v1 reads level 0", + lifecycleclient.UnconfirmedMetadataPrefix + "node-d": "no report", + }).Err() + unconfirmed := []*control.FormatHostNote{{ServerId: "node-d", Detail: "no report"}, {ServerId: "node-e", Detail: "volume v3: no report"}} + for _, tc := range []struct { + name string + resp *control.FinalizeFormatResponse + err error + dialErr error + exit int + result string + reason string + hosts []finalizeHost + listed []finalizeHost + levelOut uint32 + }{ + {name: "finalized", resp: &control.FinalizeFormatResponse{FormatLevel: 1}, exit: 0, result: "finalized", levelOut: 1}, + {name: "finalized-listing", resp: &control.FinalizeFormatResponse{FormatLevel: 1, Unconfirmed: unconfirmed}, exit: 0, result: "finalized", levelOut: 1, + listed: []finalizeHost{{"node-d", "no report"}, {"node-e", "volume v3: no report"}}}, + {name: "already", resp: &control.FinalizeFormatResponse{FormatLevel: 1, Already: true}, exit: 0, result: "already", levelOut: 1}, + {name: "refused", err: refused, exit: 2, result: "refused", reason: lifecycleclient.ReasonFormatHostsTooOld, + hosts: []finalizeHost{{"node-b", "volume v1 reads level 0"}, {"node-c", "volume v2 reads level 0"}}, + listed: []finalizeHost{{"node-d", "no report"}}}, + {name: "unreachable", err: status.Error(codes.Unavailable, "connection refused"), exit: 75, result: "unavailable", reason: "Unavailable"}, + {name: "deadline", err: status.Error(codes.DeadlineExceeded, "context deadline exceeded"), exit: 75, result: "unavailable", reason: "DeadlineExceeded"}, + {name: "dial", dialErr: errors.New("bad address"), exit: 75, result: "unavailable", reason: "Unavailable"}, + {name: "write-failed", err: status.Error(codes.Internal, "format finalize: attestation write failed"), exit: 1, result: "failed", reason: "Internal"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := &fakeClusterMaster{finalize: func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) { + return tc.resp, tc.err + }} + withClusterMaster(t, f) + if tc.dialErr != nil { + clusterLifecycleDial = func(string) (control.LifecycleServiceClient, func() error, error) { return nil, nil, tc.dialErr } + } + var out, errOut bytes.Buffer + code := run([]string{"cluster", "finalize-format", "--master", "m:1", "--json"}, &out, &errOut) + if code != tc.exit { + t.Fatalf("exit %d, want %d (stderr %q)", code, tc.exit, errOut.String()) + } + var keys map[string]json.RawMessage + if err := json.Unmarshal(out.Bytes(), &keys); err != nil { + t.Fatalf("--json output %q: %v", out.String(), err) + } + var names []string + for k := range keys { + names = append(names, k) + } + sort.Strings(names) + if want := []string{"format_level", "hosts", "listed", "message", "reason", "result"}; !reflect.DeepEqual(names, want) { + t.Fatalf("--json keys %v, want %v for every outcome", names, want) + } + var a finalizeAnswer + if err := json.Unmarshal(out.Bytes(), &a); err != nil { + t.Fatal(err) + } + if a.Result != tc.result || a.Reason != tc.reason || a.FormatLevel != tc.levelOut { + t.Fatalf("answer %+v, want result %q reason %q level %d", a, tc.result, tc.reason, tc.levelOut) + } + if want := tc.hosts; want == nil && len(a.Hosts) != 0 || want != nil && !reflect.DeepEqual(a.Hosts, want) { + t.Fatalf("hosts %+v, want %+v", a.Hosts, want) + } + if want := tc.listed; a.Listed == nil || want == nil && len(a.Listed) != 0 || want != nil && !reflect.DeepEqual(a.Listed, want) { + t.Fatalf("listed %+v, want %+v (an empty list, never null)", a.Listed, want) + } + }) + } +} + +// A usage error is "any other failure": exit 1, with the same --json shape. +func TestClusterFinalizeFormatUsageIsAFailure(t *testing.T) { + var out, errOut bytes.Buffer + if code := run([]string{"cluster", "finalize-format", "--json"}, &out, &errOut); code != 1 { + t.Fatalf("finalize without --master: exit %d, want 1", code) + } + var a finalizeAnswer + if err := json.Unmarshal(out.Bytes(), &a); err != nil || a.Result != "failed" || a.Reason != "usage" || a.Hosts == nil { + t.Fatalf("usage answer %q: %+v %v", out.String(), a, err) + } +} + +// A malformed or unknown option answers in JSON whichever side of --json it +// is on, and sends nothing to the master. +func TestClusterFinalizeFormatBadOptionAnswersJSONWithoutAnRPC(t *testing.T) { + calls := 0 + f := &fakeClusterMaster{finalize: func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) { + calls++ + return &control.FinalizeFormatResponse{FormatLevel: 1}, nil + }} + withClusterMaster(t, f) + for _, args := range [][]string{ + {"cluster", "finalize-format", "--bogus", "--json", "--master", "m:1"}, + {"cluster", "finalize-format", "--json", "--master", "m:1", "--bogus"}, + {"cluster", "finalize-format", "--timeout", "soon", "-json=true", "--master", "m:1"}, + } { + var out, errOut bytes.Buffer + code := run(args, &out, &errOut) + var a finalizeAnswer + if code != 1 || json.Unmarshal(out.Bytes(), &a) != nil || a.Result != "failed" || a.Reason != "usage" || a.Hosts == nil { + t.Fatalf("%v: exit %d, stdout %q: %+v", args, code, out.String(), a) + } + } + if calls != 0 { + t.Fatalf("a malformed command sent %d finalize RPCs", calls) + } + // The mode is the arguments' last --json, whatever a partial parse saw. + for _, tc := range []struct { + args []string + json bool + }{ + {[]string{"cluster", "finalize-format", "--bogus", "--json", "--json=false"}, false}, + {[]string{"cluster", "finalize-format", "--json", "--bogus", "--json=false"}, false}, + {[]string{"cluster", "finalize-format", "--json=false", "--bogus", "--json"}, true}, + {[]string{"cluster", "finalize-format", "--json=false", "--json", "--bogus"}, true}, + } { + var out, errOut bytes.Buffer + code := run(tc.args, &out, &errOut) + var a finalizeAnswer + gotJSON := json.Unmarshal(out.Bytes(), &a) == nil && a.Result == "failed" + if code != 1 || gotJSON != tc.json || (!tc.json && out.Len() != 0) { + t.Fatalf("%v: exit %d, stdout %q; want JSON %v", tc.args, code, out.String(), tc.json) + } + } + if calls != 0 { + t.Fatalf("a malformed command sent %d finalize RPCs", calls) + } +} + +// retire-host's answer is typed like finalize-format's: exit 0 retired, 2 +// refused (the held volumes from the master's typed metadata, never its +// message text), 75 the master could not be reached, 1 any other failure or +// a usage error; --json prints the same keys for every outcome. +func TestClusterRetireHostTypedAnswer(t *testing.T) { + holds := lifecycleclient.WithReasonMetadata(status.New(codes.FailedPrecondition, "message text a script must not parse"), + lifecycleclient.ReasonHostHoldsWork, map[string]string{ + lifecycleclient.VolumeMetadataPrefix + "v2": "busy", + lifecycleclient.VolumeMetadataPrefix + "v1": "busy", + }).Err() + for _, tc := range []struct { + name string + err error + dialErr error + args []string + exit int + result string + reason string + volumes []string + }{ + {name: "retired", exit: 0, result: "retired"}, + {name: "holds-work", err: holds, exit: 2, result: "refused", reason: lifecycleclient.ReasonHostHoldsWork, volumes: []string{"v1", "v2"}}, + {name: "not-registered", err: status.Error(codes.FailedPrecondition, "retire refused: host is not registered"), exit: 2, result: "refused", reason: "FailedPrecondition"}, + {name: "unreachable", err: status.Error(codes.Unavailable, "connection refused"), exit: 75, result: "unavailable", reason: "Unavailable"}, + {name: "deadline", err: status.Error(codes.DeadlineExceeded, "context deadline exceeded"), exit: 75, result: "unavailable", reason: "DeadlineExceeded"}, + {name: "dial", dialErr: errors.New("bad address"), exit: 75, result: "unavailable", reason: "Unavailable"}, + {name: "internal", err: status.Error(codes.Internal, "node inventory write failed"), exit: 1, result: "failed", reason: "Internal"}, + {name: "usage", args: []string{"cluster", "retire-host", "--json", "--bogus", "--master", "m:1"}, exit: 1, result: "failed", reason: "usage"}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := 0 + f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) { + calls++ + if tc.err != nil { + return nil, tc.err + } + return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil + }} + withClusterMaster(t, f) + if tc.dialErr != nil { + clusterLifecycleDial = func(string) (control.LifecycleServiceClient, func() error, error) { return nil, nil, tc.dialErr } + } + args := tc.args + if args == nil { + args = []string{"cluster", "retire-host", "--master", "m:1", "--server", "busy", "--confirm", "busy", "--json"} + } + var out, errOut bytes.Buffer + code := run(args, &out, &errOut) + if code != tc.exit { + t.Fatalf("exit %d, want %d (stderr %q)", code, tc.exit, errOut.String()) + } + var keys map[string]json.RawMessage + if err := json.Unmarshal(out.Bytes(), &keys); err != nil { + t.Fatalf("--json output %q: %v", out.String(), err) + } + var names []string + for k := range keys { + names = append(names, k) + } + sort.Strings(names) + if want := []string{"message", "reason", "result", "server", "volumes"}; !reflect.DeepEqual(names, want) { + t.Fatalf("--json keys %v, want %v for every outcome", names, want) + } + var a retireAnswer + if err := json.Unmarshal(out.Bytes(), &a); err != nil { + t.Fatal(err) + } + if a.Result != tc.result || a.Reason != tc.reason { + t.Fatalf("answer %+v, want result %q reason %q", a, tc.result, tc.reason) + } + if want := tc.volumes; want == nil && len(a.Volumes) != 0 || want != nil && !reflect.DeepEqual(a.Volumes, want) { + t.Fatalf("volumes %v, want %v", a.Volumes, want) + } + if tc.name == "usage" && calls != 0 { + t.Fatalf("a usage error sent %d retire RPCs", calls) + } + }) + } +} + +// failingWriter refuses every write: a stdout the JSON answer cannot reach. +type failingWriter struct{} + +func (failingWriter) Write([]byte) (int, error) { return 0, errors.New("stdout closed") } + +// A --json answer that cannot be written fails the command: a script that +// reads it must not see a successful exit without an answer. +func TestClusterJSONOutputFailureFailsTheCommand(t *testing.T) { + f := &fakeClusterMaster{ + finalize: func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) { + return &control.FinalizeFormatResponse{FormatLevel: 1}, nil + }, + retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) { + return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil + }, + } + withClusterMaster(t, f) + for _, args := range [][]string{ + {"cluster", "finalize-format", "--master", "m:1", "--json"}, + {"cluster", "retire-host", "--master", "m:1", "--server", "node-c", "--confirm", "node-c", "--json"}, + } { + var errOut bytes.Buffer + if code := run(args, failingWriter{}, &errOut); code != 1 { + t.Fatalf("%v with an unwritable stdout: exit %d, want 1 (stderr %q)", args, code, errOut.String()) + } + } +} diff --git a/seaweed-block/cmd/sw-block/cluster_format_test.go b/seaweed-block/cmd/sw-block/cluster_format_test.go new file mode 100644 index 0000000000..00ca9ae047 --- /dev/null +++ b/seaweed-block/cmd/sw-block/cluster_format_test.go @@ -0,0 +1,128 @@ +package main + +import ( + "bytes" + "context" + "fmt" + "strings" + "testing" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type fakeClusterMaster struct { + control.LifecycleServiceClient + finalize func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) + retire func(*control.RetireHostRequest) (*control.RetireHostResponse, error) + level func() (*control.FormatLevelResponse, error) +} + +func (f *fakeClusterMaster) FormatLevel(context.Context, *control.FormatLevelRequest, ...grpc.CallOption) (*control.FormatLevelResponse, error) { + return f.level() +} + +func (f *fakeClusterMaster) FinalizeFormat(_ context.Context, r *control.FinalizeFormatRequest, _ ...grpc.CallOption) (*control.FinalizeFormatResponse, error) { + return f.finalize(r) +} + +func (f *fakeClusterMaster) RetireHost(_ context.Context, r *control.RetireHostRequest, _ ...grpc.CallOption) (*control.RetireHostResponse, error) { + return f.retire(r) +} + +func withClusterMaster(t *testing.T, f *fakeClusterMaster) { + t.Helper() + saved := clusterLifecycleDial + t.Cleanup(func() { clusterLifecycleDial = saved }) + clusterLifecycleDial = func(string) (control.LifecycleServiceClient, func() error, error) { + return f, func() error { return nil }, nil + } +} + +// finalize-format asks level 1; a refusal names the old hosts and exits 2, +// a finalize and an already-finalized cluster exit 0, a malformed command 1. +func TestClusterFinalizeFormat(t *testing.T) { + refuse := true + f := &fakeClusterMaster{finalize: func(r *control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) { + if r.GetLevel() != 1 { + t.Errorf("finalize asked level %d", r.GetLevel()) + } + if refuse { + return nil, status.Error(codes.FailedPrecondition, "format finalize refused: registered hosts do not read format level 1: node-b (no report)") + } + return &control.FinalizeFormatResponse{FormatLevel: 1}, nil + }} + withClusterMaster(t, f) + var out, errOut bytes.Buffer + if code := run([]string{"cluster", "finalize-format", "--master", "m:1"}, &out, &errOut); code != 2 || !strings.Contains(errOut.String(), "node-b (no report)") { + t.Fatalf("refused finalize: exit %d, stderr %q", code, errOut.String()) + } + refuse = false + out.Reset() + if code := run([]string{"cluster", "finalize-format", "--master", "m:1"}, &out, &errOut); code != 0 || !strings.Contains(out.String(), "format level 1 finalized") { + t.Fatalf("finalize: exit %d, stdout %q", code, out.String()) + } + f.finalize = func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) { + return &control.FinalizeFormatResponse{FormatLevel: 1, Already: true}, nil + } + out.Reset() + if code := run([]string{"cluster", "finalize-format", "--master", "m:1"}, &out, &errOut); code != 0 || !strings.Contains(out.String(), "already finalized") { + t.Fatalf("already finalized: exit %d, stdout %q", code, out.String()) + } + if code := run([]string{"cluster", "finalize-format"}, &out, &errOut); code != 1 { + t.Fatalf("finalize without --master: exit %d, want 1", code) + } +} + +// retire-host sends the server id and its confirm; a refusal exits 2. +func TestClusterRetireHost(t *testing.T) { + var got *control.RetireHostRequest + f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) { + got = r + if r.GetServerId() == "busy" { + return nil, status.Error(codes.FailedPrecondition, `retire refused: host "busy" holds a lease or an assignment for volumes v1; move them first`) + } + return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil + }} + withClusterMaster(t, f) + var out, errOut bytes.Buffer + if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c", "--confirm", "node-c"}, &out, &errOut); code != 0 || got.GetConfirm() != "node-c" || !strings.Contains(out.String(), "host node-c retired") { + t.Fatalf("retire: exit %d, request %+v, stdout %q", code, got, out.String()) + } + if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "busy", "--confirm", "busy"}, &out, &errOut); code != 2 || !strings.Contains(errOut.String(), "holds a lease or an assignment for volumes v1") { + t.Fatalf("refused retire: exit %d, stderr %q", code, errOut.String()) + } + if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c"}, &out, &errOut); code != 1 { + t.Fatalf("retire without --confirm: exit %d, want 1", code) + } +} + +// format-level prints the master's level (0 or 1) and exits 0; a master that +// cannot answer exits nonzero (a client decides from the level only when it +// has one; the snapshot CLI then runs at 0). +func TestClusterFormatLevel(t *testing.T) { + for _, want := range []uint32{0, 1} { + withClusterMaster(t, &fakeClusterMaster{level: func() (*control.FormatLevelResponse, error) { + return &control.FormatLevelResponse{FormatLevel: want}, nil + }}) + var out, errOut bytes.Buffer + if code := run([]string{"cluster", "format-level", "--master", "m:1"}, &out, &errOut); code != 0 || strings.TrimSpace(out.String()) != fmt.Sprintf("format level %d", want) { + t.Fatalf("level %d: exit %d, stdout %q, stderr %q", want, code, out.String(), errOut.String()) + } + if got, err := clusterFormatLevel(context.Background(), "m:1"); err != nil || got != want { + t.Fatalf("clusterFormatLevel: %d %v, want %d", got, err, want) + } + } + withClusterMaster(t, &fakeClusterMaster{level: func() (*control.FormatLevelResponse, error) { + return nil, status.Error(codes.Unavailable, "master down") + }}) + var out, errOut bytes.Buffer + if code := run([]string{"cluster", "format-level", "--master", "m:1"}, &out, &errOut); code == 0 { + t.Fatalf("an unreachable master: exit 0, stdout %q", out.String()) + } + if code := run([]string{"cluster", "format-level"}, &out, &errOut); code == 0 { + t.Fatal("format-level without --master: exit 0") + } +} diff --git a/seaweed-block/cmd/sw-block/failover.go b/seaweed-block/cmd/sw-block/failover.go new file mode 100644 index 0000000000..32bbd6ef76 --- /dev/null +++ b/seaweed-block/cmd/sw-block/failover.go @@ -0,0 +1,170 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "strconv" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +const opsFailoverName = "sw-block ops failover" + +// failoverRuntime is blockmaster's admin-only FailbackService, the one call +// the operator's failover makes. +type failoverRuntime interface { + ExecuteFailback(context.Context, ops.FailbackRuntimeRequest) (ops.FailbackRuntimeResult, error) +} + +// opsFailoverRuntimeFactory dials blockmaster with the mutual-TLS client +// identity from SW_BLOCK_TLS_CERT / SW_BLOCK_TLS_KEY / SW_BLOCK_TLS_CA. +var opsFailoverRuntimeFactory = func(master string) failoverRuntime { + return ops.NewGRPCFailbackRuntime(master) +} + +const failoverUsage = `usage: sw-block ops failover --master ADDR --volume V --target R + --target-data A --target-ctrl A --expect-current R@E --confirm-old-node-off V + +The operator's failover of volume V's primary to replica R, for a standalone +(systemd) deployment. blockmaster decides: when the current primary is +unreachable it runs the fencing round (every other replica fenced at E+1) and +moves the line only to a ready replica holding the highest fenced end; a +reachable primary's move is a planned move under its guard. --target-data +and --target-ctrl must be blockmaster's record of the replica (its heartbeat); +other addresses are refused before any round. A refusal publishes no line, +but a refused fencing round may already have fenced the survivors above the +line (blockmaster continues the old primary when it answers again). + +The fencing round stops the old primary's writes, not its reads: power the +old node off or cut it from its clients first, then confirm with +--confirm-old-node-off V. --expect-current is the line you saw (sw-block ops +volumes); a line that moved since is refused. + +Needs an admin client certificate: SW_BLOCK_TLS_CERT, SW_BLOCK_TLS_KEY and +SW_BLOCK_TLS_CA, all three; without them the command refuses before dialing. + +Exit: 0 moved; 1 refused by blockmaster, or the line did not move; 2 bad +arguments or identity (no call made); 3 outcome unknown (the connection or the +deadline failed: the line may have moved; read it with sw-block ops volumes +before retrying). +` + +func runOpsFailover(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet(opsFailoverName, flag.ContinueOnError) + fs.SetOutput(stderr) + fs.Usage = func() { fmt.Fprint(stderr, failoverUsage) } + var master, volume, target, data, ctrl, expect, confirm string + var timeout time.Duration + fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port") + fs.StringVar(&volume, "volume", "", "volume id") + fs.StringVar(&target, "target", "", "replica id to promote") + fs.StringVar(&data, "target-data", "", "the target replica's data address host:port") + fs.StringVar(&ctrl, "target-ctrl", "", "the target replica's control address host:port") + fs.StringVar(&expect, "expect-current", "", "the current line, exactly @") + fs.StringVar(&confirm, "confirm-old-node-off", "", "exactly the volume id: the old primary's node is off or cut from its clients") + fs.DurationVar(&timeout, "timeout", 30*time.Second, "bound for the call (the fencing round runs inside it)") + if err := fs.Parse(args); err != nil { + return 2 + } + if fs.NArg() != 0 || master == "" || volume == "" || target == "" || data == "" || ctrl == "" || timeout <= 0 { + fmt.Fprint(stderr, failoverUsage) + return 2 + } + curReplica, curEpoch, ok := parseReplicaAtEpoch(expect) + if !ok { + fmt.Fprintf(stderr, "%s: --expect-current %q is not @\n", opsFailoverName, expect) + return 2 + } + if curReplica == target { + fmt.Fprintf(stderr, "%s: the target %s is the current primary\n", opsFailoverName, target) + return 2 + } + if confirm != volume { + fmt.Fprintf(stderr, "%s: --confirm-old-node-off must be exactly %q (the old node is off or cut from its clients)\n", opsFailoverName, volume) + return 2 + } + // An admin command never falls back to a plaintext link. + if tls, err := link.MasterTLSFromEnv(); err != nil { + fmt.Fprintf(stderr, "%s: client identity: %v\n", opsFailoverName, err) + return 2 + } else if tls == nil { + fmt.Fprintf(stderr, "%s: needs an admin client certificate: set %s, %s and %s\n", opsFailoverName, link.EnvTLSCert, link.EnvTLSKey, link.EnvTLSCA) + return 2 + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + res, err := opsFailoverRuntimeFactory(master).ExecuteFailback(ctx, ops.FailbackRuntimeRequest{ + VolumeID: volume, + ReplicaID: target, + TargetDataAddr: data, + TargetCtrlAddr: ctrl, + ExpectedCurrentReplicaID: curReplica, + ExpectedCurrentEpoch: curEpoch, + // Required by the runtime but decide nothing (they are not evidence): + // blockmaster's gate (the fencing round for an unreachable primary) + // decides the move, and the target is published at blockmaster's own + // record of its addresses (a request naming others is refused). + AckEligible: true, + FrontendFencedBeforeFailback: true, // --confirm-old-node-off + DurableFrontierCovered: true, + NoCrossVolumeIdentityChange: true, + EvidenceRefs: []string{"sw-block ops failover", "operator_confirmed_old_node_off=" + volume}, + }) + if err != nil { + if failoverOutcomeUnknown(err) { + fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=unknown\n", volume, target, curReplica, curEpoch) + fmt.Fprintf(stderr, "%s: outcome unknown (%v): the line may have moved; read it with sw-block ops volumes before retrying\n", opsFailoverName, err) + return 3 + } + fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=refused\n", volume, target, curReplica, curEpoch) + fmt.Fprintf(stderr, "%s: refused: %v (no line published; a refused fencing round may have fenced the survivors)\n", opsFailoverName, err) + return 1 + } + moved := res.FailbackStarted && res.AuthorityEpochAdvanced && res.SinglePrimaryAfterFailback + fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=%s epoch_advanced=%t single_primary=%t publish_target_swapped=%t\n", + volume, target, curReplica, curEpoch, map[bool]string{true: "moved", false: "not_moved"}[moved], + res.AuthorityEpochAdvanced, res.SinglePrimaryAfterFailback, res.PublishTargetSwappedAfterFailback) + if !moved { + return 1 + } + return 0 +} + +// parseReplicaAtEpoch parses "@" with a nonzero epoch. +func parseReplicaAtEpoch(s string) (string, uint64, bool) { + i := strings.LastIndexByte(s, '@') + if i <= 0 || i == len(s)-1 { + return "", 0, false + } + e, err := strconv.ParseUint(s[i+1:], 10, 64) + if err != nil || e == 0 { + return "", 0, false + } + return s[:i], e, true +} + +// failoverOutcomeUnknown: the call did not get blockmaster's decision back +// (connection, deadline, cancellation or an internal failure), so the line +// may or may not have moved. A decided refusal is any other status. +func failoverOutcomeUnknown(err error) bool { + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { + return true + } + s, ok := status.FromError(err) + if !ok { + return true + } + switch s.Code() { + case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled, codes.Unknown, codes.Internal, codes.DataLoss, codes.ResourceExhausted: + return true + } + return false +} diff --git a/seaweed-block/cmd/sw-block/failover_test.go b/seaweed-block/cmd/sw-block/failover_test.go new file mode 100644 index 0000000000..216af4ff2a --- /dev/null +++ b/seaweed-block/cmd/sw-block/failover_test.go @@ -0,0 +1,290 @@ +package main + +import ( + "bytes" + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "errors" + "math/big" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type fakeFailoverRuntime struct { + calls []ops.FailbackRuntimeRequest + res ops.FailbackRuntimeResult + err error +} + +func (f *fakeFailoverRuntime) ExecuteFailback(_ context.Context, req ops.FailbackRuntimeRequest) (ops.FailbackRuntimeResult, error) { + f.calls = append(f.calls, req) + return f.res, f.err +} + +func withFailoverRuntime(t *testing.T, f *fakeFailoverRuntime) *string { + t.Helper() + withClientIdentity(t) + var dialed string + prev := opsFailoverRuntimeFactory + opsFailoverRuntimeFactory = func(master string) failoverRuntime { dialed = master; return f } + t.Cleanup(func() { opsFailoverRuntimeFactory = prev }) + return &dialed +} + +func failoverArgs(extra ...string) []string { + args := []string{"ops", "failover", "--master", "m:9333", "--volume", "v1", "--target", "r2", + "--target-data", "d2:1", "--target-ctrl", "c2:1", "--expect-current", "r1@4", "--confirm-old-node-off", "v1"} + return append(args, extra...) +} + +// The operator's failover sends one FailbackService call carrying the +// expected current line it was given; a move is reported and exits 0. +func TestOpsFailoverSendsTheExpectedLineAndReportsTheMove(t *testing.T) { + f := &fakeFailoverRuntime{res: ops.FailbackRuntimeResult{FailbackStarted: true, AuthorityEpochAdvanced: true, SinglePrimaryAfterFailback: true, PublishTargetSwappedAfterFailback: true}} + dialed := withFailoverRuntime(t, f) + var out, errb bytes.Buffer + if rc := run(failoverArgs(), &out, &errb); rc != 0 { + t.Fatalf("rc=%d stderr=%s", rc, errb.String()) + } + if *dialed != "m:9333" || len(f.calls) != 1 { + t.Fatalf("dialed %q calls %d; want one call to m:9333", *dialed, len(f.calls)) + } + r := f.calls[0] + if r.VolumeID != "v1" || r.ReplicaID != "r2" || r.TargetDataAddr != "d2:1" || r.TargetCtrlAddr != "c2:1" || + r.ExpectedCurrentReplicaID != "r1" || r.ExpectedCurrentEpoch != 4 || !r.FrontendFencedBeforeFailback { + t.Fatalf("request %+v", r) + } + if !strings.Contains(out.String(), "result=moved") { + t.Fatalf("stdout %q; want result=moved", out.String()) + } +} + +// A refusal by blockmaster (for example a fencing round that does not allow +// the target) is reported and exits 1; a call that returns without moving +// the line is not a move either. +func TestOpsFailoverReportsARefusal(t *testing.T) { + for _, f := range []*fakeFailoverRuntime{ + {err: status.Error(codes.FailedPrecondition, "execute failback: fenced move: the fencing round at epoch 5 does not allow r2")}, + {res: ops.FailbackRuntimeResult{FailbackStarted: true}}, + } { + withFailoverRuntime(t, f) + var out, errb bytes.Buffer + if rc := run(failoverArgs(), &out, &errb); rc != 1 { + t.Fatalf("rc=%d; want 1 (stdout %q stderr %q)", rc, out.String(), errb.String()) + } + if strings.Contains(out.String(), "result=moved") { + t.Fatalf("stdout %q reports a move", out.String()) + } + } +} + +// Every argument guard refuses locally, before any call: the old node must +// be confirmed off for exactly this volume, the expected line must be +// @ with a nonzero epoch, and the target must not be the +// current primary. +func TestOpsFailoverRefusesBadArgumentsWithoutACall(t *testing.T) { + for name, args := range map[string][]string{ + "no confirmation": {"ops", "failover", "--master", "m:9333", "--volume", "v1", "--target", "r2", "--target-data", "d2:1", "--target-ctrl", "c2:1", "--expect-current", "r1@4"}, + "confirmation for another": failoverArgs("--confirm-old-node-off", "v2"), + "expected line without epoch": failoverArgs("--expect-current", "r1"), + "expected epoch zero": failoverArgs("--expect-current", "r1@0"), + "expected epoch not a number": failoverArgs("--expect-current", "r1@x"), + "target is current": failoverArgs("--expect-current", "r2@4"), + "no master": {"ops", "failover", "--volume", "v1", "--target", "r2", "--target-data", "d2:1", "--target-ctrl", "c2:1", "--expect-current", "r1@4", "--confirm-old-node-off", "v1"}, + "stray argument": append(failoverArgs(), "extra"), + } { + t.Run(name, func(t *testing.T) { + f := &fakeFailoverRuntime{} + withFailoverRuntime(t, f) + var out, errb bytes.Buffer + if rc := run(args, &out, &errb); rc != 2 || len(f.calls) != 0 { + t.Fatalf("rc=%d calls=%d; want 2 and no call (stderr %q)", rc, len(f.calls), errb.String()) + } + }) + } +} + +// The alpha stack deploys the manual failover its notes describe: blockmaster +// serves the admin failback RPC, the executor runs with the admin client +// Secret and execution on, the CRD is applied, and uninstall removes both. +func TestAlphaStackDeploysTheManualFailover(t *testing.T) { + read := func(p string) string { + t.Helper() + b, err := os.ReadFile(filepath.Join("..", "..", p)) + if err != nil { + t.Fatal(err) + } + return string(b) + } + const crd = "charts/seaweed-block/crds/swblockreplicafailbacks.block.seaweedfs.com.yaml" + read(crd) + for file, wants := range map[string][]string{ + "deploy/k8s/alpha/block-stack.yaml": {`"--failback-runtime-rpc"`}, + "deploy/k8s/alpha/failback-executor.yaml": {"secretName: sw-block-failback-executor-tls", `"--enable-execution"`, `"--execution-policy"`, `"--failback-runtime-grpc-addr=blockmaster.kube-system.svc.cluster.local:9333"`}, + "scripts/install-k8s-alpha.sh": {crd, `render-k8s-alpha-image.sh" "$IMAGE" "$ROOT/deploy/k8s/alpha/failback-executor.yaml"`, `kubectl apply -f "$ARTIFACT_DIR/failback-executor.rendered.yaml"`}, + "scripts/run-alpha-app-demo.sh": {crd, `render-k8s-alpha-image.sh" "$IMAGE" "$ROOT/deploy/k8s/alpha/failback-executor.yaml"`, `kubectl apply -f "$ARTIFACT_DIR/failback-executor.rendered.yaml"`}, + "scripts/uninstall-k8s-alpha.sh": {crd, "deploy/k8s/alpha/failback-executor.yaml"}, + "scripts/k8s-alpha-certs.sh": {"failback-executor:admin"}, + } { + s := read(file) + for _, w := range wants { + if !strings.Contains(s, w) { + t.Errorf("%s: missing %s", file, w) + } + } + } +} + +// A call that does not get blockmaster's decision back (the connection or +// the deadline failed) is reported as unknown, exit 3, never as a refusal: +// the line may have moved. +func TestOpsFailoverReportsAnUnknownOutcome(t *testing.T) { + for name, err := range map[string]error{ + "unavailable": status.Error(codes.Unavailable, "connection reset"), + "deadline status": status.Error(codes.DeadlineExceeded, "deadline"), + "context deadline": context.DeadlineExceeded, + "not a status": errors.New("dial tcp: i/o timeout"), + } { + t.Run(name, func(t *testing.T) { + withFailoverRuntime(t, &fakeFailoverRuntime{err: err}) + var out, errb bytes.Buffer + if rc := run(failoverArgs(), &out, &errb); rc != 3 || !strings.Contains(out.String(), "result=unknown") { + t.Fatalf("rc=%d stdout=%q; want 3 and result=unknown", rc, out.String()) + } + }) + } +} + +// The admin command never dials without a complete, valid client identity: +// unset, partial or unreadable TLS settings are refused locally (exit 2, no +// call); a valid identity makes the call. +func TestOpsFailoverRequiresAClientIdentity(t *testing.T) { + dir := t.TempDir() + cert, key, ca := writeClientIdentity(t, dir) + junk := filepath.Join(dir, "junk.pem") + if err := os.WriteFile(junk, []byte("not a certificate"), 0o600); err != nil { + t.Fatal(err) + } + for name, c := range map[string]struct { + cert, key, ca string + calls int + }{ + "unset": {"", "", "", 0}, + "cert only": {cert, "", "", 0}, + "no CA": {cert, key, "", 0}, + "unreadable": {junk, junk, junk, 0}, + "valid": {cert, key, ca, 1}, + } { + t.Run(name, func(t *testing.T) { + f := &fakeFailoverRuntime{res: ops.FailbackRuntimeResult{FailbackStarted: true, AuthorityEpochAdvanced: true, SinglePrimaryAfterFailback: true}} + prev := opsFailoverRuntimeFactory + opsFailoverRuntimeFactory = func(string) failoverRuntime { return f } + t.Cleanup(func() { opsFailoverRuntimeFactory = prev }) + t.Setenv(link.EnvTLSCert, c.cert) + t.Setenv(link.EnvTLSKey, c.key) + t.Setenv(link.EnvTLSCA, c.ca) + var out, errb bytes.Buffer + rc := run(failoverArgs(), &out, &errb) + if len(f.calls) != c.calls { + t.Fatalf("calls=%d; want %d (rc=%d stderr %q)", len(f.calls), c.calls, rc, errb.String()) + } + if c.calls == 0 && rc != 2 { + t.Fatalf("rc=%d; want 2", rc) + } + if c.calls == 1 && rc != 0 { + t.Fatalf("rc=%d stderr %q; want 0", rc, errb.String()) + } + }) + } +} + +// withClientIdentity sets a valid admin client identity for the test. +func withClientIdentity(t *testing.T) { + t.Helper() + cert, key, ca := writeClientIdentity(t, t.TempDir()) + t.Setenv(link.EnvTLSCert, cert) + t.Setenv(link.EnvTLSKey, key) + t.Setenv(link.EnvTLSCA, ca) +} + +// writeClientIdentity writes a CA and a client certificate it signed. +func writeClientIdentity(t *testing.T, dir string) (certPath, keyPath, caPath string) { + t.Helper() + caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + caTmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test-ca"}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature} + caDER, err := x509.CreateCertificate(rand.Reader, caTmpl, caTmpl, &caKey.PublicKey, caKey) + if err != nil { + t.Fatal(err) + } + cliKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + cliTmpl := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "sw-block-admin"}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}} + caCert, err := x509.ParseCertificate(caDER) + if err != nil { + t.Fatal(err) + } + cliDER, err := x509.CreateCertificate(rand.Reader, cliTmpl, caCert, &cliKey.PublicKey, caKey) + if err != nil { + t.Fatal(err) + } + keyDER, err := x509.MarshalECPrivateKey(cliKey) + if err != nil { + t.Fatal(err) + } + write := func(name, typ string, der []byte) string { + p := filepath.Join(dir, name) + if err := os.WriteFile(p, pem.EncodeToMemory(&pem.Block{Type: typ, Bytes: der}), 0o600); err != nil { + t.Fatal(err) + } + return p + } + return write("client.crt", "CERTIFICATE", cliDER), write("client.key", "EC PRIVATE KEY", keyDER), write("ca.crt", "CERTIFICATE", caDER) +} + +// The executor runs the image the install selected, like the rest of the +// stack: rendering it with a registry image replaces the local image and its +// never-pull policy. +func TestAlphaFailbackExecutorRendersTheSelectedImage(t *testing.T) { + bash, err := exec.LookPath("bash") + if err != nil { + t.Skip("no bash") + } + root := filepath.Join("..", "..") + out := filepath.Join(t.TempDir(), "rendered.yaml") + const image = "registry.example.com/seaweedfs/seaweed-block:v9.9" + cmd := exec.Command(bash, filepath.Join(root, "scripts", "render-k8s-alpha-image.sh"), image, filepath.Join(root, "deploy", "k8s", "alpha", "failback-executor.yaml"), out) + if b, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("render: %v: %s", err, b) + } + b, err := os.ReadFile(out) + if err != nil { + t.Fatal(err) + } + r := string(b) + if !strings.Contains(r, "image: "+image) || !strings.Contains(r, "imagePullPolicy: IfNotPresent") || strings.Contains(r, "sw-block:local") || strings.Contains(r, "imagePullPolicy: Never") { + t.Fatalf("rendered executor does not run the selected image: %s", r) + } +} diff --git a/seaweed-block/cmd/sw-block/format_status_json_test.go b/seaweed-block/cmd/sw-block/format_status_json_test.go new file mode 100644 index 0000000000..560830e44c --- /dev/null +++ b/seaweed-block/cmd/sw-block/format_status_json_test.go @@ -0,0 +1,72 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "net" + "testing" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" +) + +// binaryTooOldStatusServer answers a cluster status whose volume carries the +// master's binary_too_old condition for a refused holder. +type binaryTooOldStatusServer struct{ inspectionControlServer } + +func (s binaryTooOldStatusServer) GetClusterStatus(ctx context.Context, q *control.GetClusterStatusRequest) (*control.ClusterStatusResponse, error) { + r, err := s.inspectionControlServer.GetClusterStatus(ctx, q) + r.Volumes = append(r.Volumes, &control.VolumeEvidence{VolumeId: "v-healthy", Status: "ok"}) + r.Volumes[0].Conditions = append(r.Volumes[0].Conditions, &control.ObservationCondition{ + Type: "HolderReadsFormat", Status: "false", Reason: "binary_too_old", Severity: "error", + Message: "node host-b's process for this volume reads format level 0; the cluster's format level is 1: no grant (binary_too_old)", + }) + return r, err +} + +// A holder refused by the format gate sees only no assignment, so the +// operator's cluster status --json carries the master's binary_too_old +// condition, with the server and its report level. +func TestClusterStatusJSONShowsABinaryTooOldHolder(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + control.RegisterEvidenceServiceServer(srv, cmdFakeEvidenceServer{}) + control.RegisterClusterEvidenceServiceServer(srv, binaryTooOldStatusServer{}) + go func() { _ = srv.Serve(ln) }() + t.Cleanup(func() { srv.Stop(); _ = ln.Close() }) + var out, errout bytes.Buffer + if code := run([]string{"shell", "-master", ln.Addr().String(), "-c", "cluster.status -o json"}, &out, &errout); code != 0 { + t.Fatalf("exit=%d stderr=%s", code, &errout) + } + var body struct { + Volumes []struct { + VolumeID string `json:"volume_id"` + Conditions []struct { + Reason string `json:"reason"` + Message string `json:"message"` + } `json:"conditions"` + } `json:"volumes"` + } + if err := json.Unmarshal(out.Bytes(), &body); err != nil { + t.Fatal(err) + } + shown := map[string]bool{} // volume id -> has the binary_too_old condition + for _, v := range body.Volumes { + shown[v.VolumeID] = shown[v.VolumeID] || false + for _, c := range v.Conditions { + if c.Reason == "binary_too_old" && bytes.Contains([]byte(c.Message), []byte("host-b's process for this volume reads format level 0")) { + shown[v.VolumeID] = true + } + } + } + if !shown["v1"] { + t.Fatalf("cluster status --json: volume v1 has no binary_too_old condition: %s", &out) + } + if healthy, listed := shown["v-healthy"]; !listed || healthy { + t.Fatalf("cluster status --json: the healthy volume listed %v, with binary_too_old %v: %s", listed, healthy, &out) + } +} diff --git a/seaweed-block/cmd/sw-block/integration_invocations_test.go b/seaweed-block/cmd/sw-block/integration_invocations_test.go new file mode 100644 index 0000000000..671dfc2e28 --- /dev/null +++ b/seaweed-block/cmd/sw-block/integration_invocations_test.go @@ -0,0 +1,278 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "go/ast" + "go/parser" + "go/token" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// The process-level integration tests (cmd/blockvolume, behind build tags) +// call this command by argument list: they compile without these tags in +// CI, so an invocation the CLI no longer accepts (a removed subcommand, a +// renamed or newly required flag) would pass compile and fail only on a +// lab run. Every literal `ops ...` invocation in them is run through this +// CLI's own argument handling here, each in a child process killed at its +// deadline. Variable values become placeholders; in the child the master +// resolves every name and the filer dial and the restore RPC answer +// errGuardPast, which a command reaches only after all its argument checks. +// Other calls meet addresses nothing listens on. A refusal of the arguments +// fails this test, and so does a call that neither answers nor fails +// within the deadline: waiting is not proof that the arguments passed. +func TestIntegrationTestInvocationsParse(t *testing.T) { + invocations := literalOpsInvocations(t, filepath.Join("..", "blockvolume")) + if len(invocations) == 0 { + t.Fatal("no ops invocations found in the integration tests") + } + for _, inv := range invocations { + inv := inv + if len(inv.args) < 2 { + t.Fatalf("%s: an ops invocation without a subcommand", inv.where) + } + t.Run(inv.where, func(t *testing.T) { + if verdict, out := guardInvocation(t, inv.args); verdict != guardPast { + t.Fatalf("sw-block %s\n%s: %s", strings.Join(inv.args, " "), verdict, out) + } + }) + } +} + +// The guard's own controls: argument lists whose missing flag is checked +// only after the volume names resolve must be refused, and a complete one +// must pass. +func TestIntegrationInvocationGuardReachesLateFlagChecks(t *testing.T) { + for _, c := range []struct { + args []string + want string + }{ + {[]string{"ops", "chunk", "snapshots", "--master", "127.0.0.1:1", "--volume", "v1"}, guardRefused}, + {[]string{"ops", "chunk", "snapshot-delete", "--master", "127.0.0.1:1", "--volume", "v1", "--name", "s1"}, guardRefused}, + {[]string{"ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--chunk-filer", "127.0.0.1:1"}, guardRefused}, + {[]string{"ops", "chunk", "snapshots", "--master", "127.0.0.1:1", "--volume", "v1", "--chunk-filer", "127.0.0.1:1"}, guardPast}, + {[]string{"ops", "chunk", "restore", "--master", "127.0.0.1:1", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--chunk-filer", "127.0.0.1:1"}, guardPast}, + } { + if verdict, out := guardInvocation(t, c.args); verdict != c.want { + t.Errorf("sw-block %s: %s, want %s: %s", strings.Join(c.args, " "), verdict, c.want, out) + } + } +} + +const ( + guardPast = "past its arguments" + guardRefused = "refused its arguments" + guardTimeout = "still running at the deadline" + guardOther = "failed for another reason" +) + +// errGuardPast is what the child's filer dial and restore RPC answer. +var errGuardPast = errors.New("invocation guard: past its arguments") + +const guardArgsEnv = "SWB_INVOCATION_GUARD_ARGS" + +// guardInvocation runs args in a child process of this test binary and +// classifies its output. +func guardInvocation(t *testing.T, args []string) (string, string) { + t.Helper() + enc, err := json.Marshal(args) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestIntegrationInvocationChild$", "-test.count=1") + cmd.Dir = t.TempDir() // whatever a call writes lands here, never in the source tree + cmd.Env = append(os.Environ(), guardArgsEnv+"="+string(enc)) + cmd.WaitDelay = time.Second + raw, _ := cmd.CombinedOutput() + out := string(raw) + switch { + case ctx.Err() != nil: + return guardTimeout, out + case strings.Contains(out, errGuardPast.Error()): + return guardPast, firstLine(out, errGuardPast.Error()) + } + for _, refusal := range []string{`"code":"bad_request"`, "unknown subcommand", "unknown command", "flag provided but not defined", "invalid value", "is required"} { + if strings.Contains(out, refusal) { + return guardRefused, firstLine(out, refusal) + } + } + if strings.Contains(out, "rpc error") || strings.Contains(out, "dial tcp") || strings.Contains(out, "connection refused") { + return guardPast, "the placeholder address refused the call" + } + return guardOther, out +} + +// TestIntegrationInvocationChild is the child process: it runs only with +// guardArgsEnv set. +func TestIntegrationInvocationChild(t *testing.T) { + enc := os.Getenv(guardArgsEnv) + if enc == "" { + t.Skip("the invocation guard's child process") + } + var args []string + if err := json.Unmarshal([]byte(enc), &args); err != nil { + t.Fatal(err) + } + resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{1}, nil } + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return nil, nil, errGuardPast } + restoreCreateRPC = func(context.Context, string, *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) { + return nil, errGuardPast + } + var stdout, stderr bytes.Buffer + code := run(args, &stdout, &stderr) + fmt.Printf("exit %d\n%s%s", code, stdout.String(), stderr.String()) +} + +type opsInvocation struct { + where string + args []string +} + +// literalOpsInvocations returns every `.command(t, "ops", ...)`, `.run(t, "ops", ...)` and +// `runCLI(ctx, h, "ops", ...)` call in +// dir's test files whose arguments are listed (not spread from a slice), +// with each non-literal argument replaced by a placeholder for its flag. +func literalOpsInvocations(t *testing.T, dir string) []opsInvocation { + t.Helper() + files, err := filepath.Glob(filepath.Join(dir, "*_test.go")) + if err != nil { + t.Fatal(err) + } + var out []opsInvocation + fset := token.NewFileSet() + for _, f := range files { + src, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + file, err := parser.ParseFile(fset, f, src, 0) + if err != nil { + t.Fatal(err) + } + ast.Inspect(file, func(n ast.Node) bool { + var elems []ast.Expr + switch x := n.(type) { + case *ast.CallExpr: + if x.Ellipsis != token.NoPos || len(x.Args) < 2 { + return true + } + from := opsArg(x) + if from < 0 { + return true + } + elems = x.Args[from:] + case *ast.CompositeLit: + // a prepared argument list, []string{"ops", ...}, that a + // harness call spreads + if len(x.Elts) < 2 || literal(x.Elts[0]) != "ops" { + return true + } + elems = x.Elts + default: + return true + } + var args []string + for _, a := range elems { + if v := literal(a); v != "" || isStringLit(a) { + args = append(args, v) + continue + } + args = append(args, placeholder(args, len(args))) + } + pos := fset.Position(n.Pos()) + out = append(out, opsInvocation{where: filepath.Base(pos.Filename) + ":" + strconv.Itoa(pos.Line), args: args}) + return true + }) + } + return out +} + +// opsArg is the index of the literal "ops" that starts the CLI argument +// list of a harness call: x.command(t, "ops", ...) or runCLI(ctx, h, "ops", +// ...); -1 for any other call. +func opsArg(call *ast.CallExpr) int { + name := "" + switch f := call.Fun.(type) { + case *ast.SelectorExpr: + name = f.Sel.Name + case *ast.Ident: + name = f.Name + } + at := map[string]int{"command": 1, "run": 1, "runCLI": 2}[name] + if at == 0 || len(call.Args) <= at || literal(call.Args[at]) != "ops" { + return -1 + } + return at +} + +func isStringLit(e ast.Expr) bool { + b, ok := e.(*ast.BasicLit) + return ok && b.Kind == token.STRING +} + +func literal(e ast.Expr) string { + b, ok := e.(*ast.BasicLit) + if !ok || b.Kind != token.STRING { + return "" + } + v, err := strconv.Unquote(b.Value) + if err != nil { + return "" + } + return v +} + +// placeholder is a value of the kind the preceding flag takes: an address +// nothing listens on, a number, a duration, or a name. +func placeholder(prev []string, at int) string { + name := "x" + strconv.Itoa(at) // distinct, so two variables never compare equal + if len(prev) == 0 { + return name + } + flag := strings.TrimLeft(prev[len(prev)-1], "-") + switch { + case strings.Contains(flag, "timeout") || strings.Contains(flag, "interval") || strings.Contains(flag, "wait"): + return "1s" + case strings.Contains(flag, "lsn") || strings.Contains(flag, "epoch") || strings.Contains(flag, "gen") || strings.Contains(flag, "count") || strings.Contains(flag, "bytes") || strings.Contains(flag, "size"): + return "1" + case strings.Contains(flag, "confirm"): + return volumeOf(prev) + "@1" // a forced move's confirmation names its volume and epoch + case strings.Contains(flag, "master") || strings.Contains(flag, "addr") || strings.Contains(flag, "filer") || strings.Contains(flag, "data") || strings.Contains(flag, "ctrl") || strings.Contains(flag, "endpoint"): + return "127.0.0.1:1" + } + return name +} + +// volumeOf is the --volume value among args, or "". +func volumeOf(args []string) string { + for i := 0; i+1 < len(args); i++ { + if args[i] == "--volume" { + return args[i+1] + } + } + return "" +} + +func firstLine(out, near string) string { + for _, l := range strings.Split(out, "\n") { + if strings.Contains(l, near) { + return l + } + } + return out +} diff --git a/seaweed-block/cmd/sw-block/log_collect.go b/seaweed-block/cmd/sw-block/log_collect.go new file mode 100644 index 0000000000..40529436bc --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect.go @@ -0,0 +1,333 @@ +package main + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + "unicode/utf8" +) + +const bundleSourceLimit = 4 << 20 +const bundleTotalLimit = 32 << 20 + +type bundleStrings []string + +func (v *bundleStrings) String() string { return strings.Join(*v, ",") } +func (v *bundleStrings) Set(s string) error { *v = append(*v, s); return nil } + +type bundleArtifact struct { + Name string `json:"name"` + State string `json:"state"` + Error string `json:"error,omitempty"` + data []byte +} +type logBundle struct { + Version int `json:"version"` + Since time.Time `json:"since"` + Until time.Time `json:"until"` + Artifacts []bundleArtifact `json:"artifacts"` + // Redaction is "not_proven" when a declared source (-log-file, -unit, + // -pid) was not read whole for credential discovery (cut by the time + // budget, unreadable, over its bound, truncated); the bundle then holds + // no artifact but this manifest, with fixed diagnostics only. Skipped + // names those sources. + Redaction string `json:"redaction,omitempty"` + Skipped []string `json:"skipped,omitempty"` + bytes int + redactor *bundleRedactor + ctx context.Context // the collection's time budget +} + +func (b *logBundle) discover(data []byte) { + if b.redactor == nil { + b.redactor = &bundleRedactor{secrets: map[string]bool{}} + } + if len(data) > bundleSourceLimit { + b.redactor.overflow = true + return + } + b.redactor.discover(data) +} + +// add adds a source the bundle collects on its own (the master's and the +// holders' status): one the time budget cut adds no bytes, and none of its +// own reach the bundle. +func (b *logBundle) add(name string, data []byte, err error) { + b.addSource(name, data, err, true) +} + +// addCommand adds a declared -unit's command output. The command's own +// failure (cut by the time budget, a nonzero exit, output truncated at its +// bound) left it not read whole, so its credentials are not all discovered; +// a command this host does not have read nothing, and is only unavailable. +// err is the artifact's error (the command's, or the time filter's after a +// whole read). +func (b *logBundle) addCommand(name string, data []byte, cmdErr, err error) { + if cmdErr != nil && !errors.Is(cmdErr, exec.ErrNotFound) { + b.unproven(name) + } + b.addSource(name, data, err, true) +} + +// unproven records a declared source whose discovery did not complete. +func (b *logBundle) unproven(name string) { b.Skipped = append(b.Skipped, name) } + +// addSource adds a source; discover says its bytes are still to be +// discovered (a log file's were, whole, as it was read). +func (b *logBundle) addSource(name string, data []byte, err error, discover bool) { + // Even a source omitted by the aggregate artifact budget can identify a + // credential repeated in a retained artifact. Keep only its bounded secrets. + if discover { + b.discover(data) + } + if err != nil { + b.discover([]byte(err.Error())) + } + a := bundleArtifact{Name: name, State: "collected", data: data} + if !utf8.Valid(data) { + err = errors.New("source is not UTF-8 text") + a.data = nil + } + if len(data) > bundleSourceLimit || b.bytes+len(data) > bundleTotalLimit { + err = errors.New("collection byte bound exceeded") + a.data = nil + } + if err != nil { + a.State = "unavailable" + a.Error = err.Error() + if len(a.Error) > 2048 { + a.Error = a.Error[:2048] + " (truncated)" + } + } + b.bytes += len(a.data) + b.Artifacts = append(b.Artifacts, a) +} +func (b *logBundle) write(dir string) error { + // All discovery completes in memory. No raw artifact is ever staged on disk. + b.discover(nil) + r := b.redactor + if r.overflow { + return errors.New("redaction discovery bound exceeded") + } + // A source cut by the time budget may hold a credential repeated in + // another artifact: no artifact is written whose redaction is not proven. + // Every free-form error goes too: only fixed diagnostics remain. + if len(b.Skipped) > 0 { + b.Redaction = "not_proven" + for i := range b.Artifacts { + a := &b.Artifacts[i] + if a.data != nil { + a.State = "withheld" + } + a.data, a.Error = nil, "withheld: redaction not proven" + } + } + outputBytes := 0 + for i := range b.Artifacts { + a := &b.Artifacts[i] + if a.data == nil { + continue + } + clean, proven := r.redactChecked(a.data) + if !proven { + a.data, a.State, a.Error = nil, "withheld", "withheld: redaction not proven" + continue + } + if len(clean) > bundleSourceLimit || outputBytes+len(clean) > bundleTotalLimit { + a.data = nil + a.State = "unavailable" + a.Error = "sanitized output exceeds collection bound" + continue + } + a.data = clean + outputBytes += len(clean) + } + meta, err := json.MarshalIndent(b, "", " ") + if err != nil { + return err + } + meta, proven := r.redactChecked(meta) + if !proven || len(meta) > bundleSourceLimit { + return errors.New("manifest exceeds collection bound") + } + if err = os.Mkdir(dir, 0700); err != nil { + return errors.New("cannot create a new bundle directory") + } + for _, a := range b.Artifacts { + if a.data == nil { + continue + } + if err = os.WriteFile(filepath.Join(dir, a.Name), a.data, 0600); err != nil { + return errors.New("cannot write sanitized bundle artifact") + } + } + return os.WriteFile(filepath.Join(dir, "manifest.json"), meta, 0600) +} +func (s inspectionShell) collectLogs(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("log.collect", flag.ContinueOnError) + // Invalid input can itself contain a secret. Do not echo the parser's text. + fs.SetOutput(io.Discard) + var dir string + var files, units, pids bundleStrings + fs.StringVar(&dir, "out", "", "new bundle directory") + since := fs.Duration("since", 15*time.Minute, "recent log window (at most 24h)") + format := fs.String("o", "text", "text or json result") + fs.Var(&files, "log-file", "local daemon log file; repeatable") + fs.Var(&units, "unit", "local journal service unit; repeatable") + fs.Var(&pids, "pid", "local process whose startup arguments to include; repeatable") + if fs.Parse(args) != nil || fs.NArg() != 0 || dir == "" || *since <= 0 || *since > 24*time.Hour || len(files)+len(units)+len(pids) > 32 || !validBundleLocalSources(units, pids) || (*format != "text" && *format != "json") { + fmt.Fprintln(stderr, "usage: log.collect -out NEW_DIR [-since 15m] [-log-file PATH ...] [-unit UNIT ...] [-pid PID ...]") + return 2 + } + if _, err := os.Lstat(dir); !errors.Is(err, os.ErrNotExist) { + fmt.Fprintln(stderr, "bundle output must not exist") + return 2 + } + now := time.Now().UTC() + b := logBundle{Version: 1, Since: now.Add(-*since), Until: now} + ctx, cancel := context.WithTimeout(context.Background(), s.timeout) + defer cancel() + b.ctx = ctx + if len(files) == 0 && len(units) == 0 { + discovered, err := defaultBundleUnits(ctx) + units = discovered + b.addJSON("unit-discovery.json", map[string]any{"units": discovered}, err) + } + // The declared sources first: the commands the time budget bounds (-unit, + // -pid), then the log files, each read whole for discovery whatever time + // is left (each is bounded at 4 MiB, at most 32 sources), so the budget + // never cuts their discovery. The status reads, not declared, come last. + b.collectLocal(ctx, units, pids) + for i, p := range files { + name, discovered := fmt.Sprintf("file-%03d.log", i+1), false + data, err := readBundleLog(p, b.Since, b.Until, func(raw []byte) { b.discover(raw); discovered = true }) + if !discovered && !errors.Is(err, errBundleLogMissing) { + b.unproven(name) // refused before discovery: not a regular file, changed, over 4 MiB, not text, unreadable + } + b.addSource(name, data, err, false) + } + b.collectStatus(ctx, s) + if err := b.write(dir); err != nil { + fmt.Fprintln(stderr, "cannot write bundle") + return 1 + } + if b.Redaction == "not_proven" { + skipped := make([]string, len(b.Skipped)) // printed as sanitized as the manifest + for i, name := range b.Skipped { + skipped[i] = b.redactor.redactText(name) + } + if *format == "json" { + _ = json.NewEncoder(stdout).Encode(map[string]any{"bundle_written": true, "complete": false, "redaction": "not_proven", "skipped": skipped, "manifest": "manifest.json"}) + } else { + named := skipped + if len(named) > 8 { + named = append(append([]string(nil), named[:8]...), fmt.Sprintf("and %d more", len(skipped)-8)) + } + fmt.Fprintf(stdout, "bundle written; incomplete: redaction not proven (not read in time: %s); only manifest.json was written\n", strings.Join(named, ", ")) + } + return 3 + } + complete := true + for _, a := range b.Artifacts { + if a.State != "collected" { + complete = false + } + } + if *format == "json" { + _ = json.NewEncoder(stdout).Encode(map[string]any{"bundle_written": true, "complete": complete, "manifest": "manifest.json"}) + } else if complete { + fmt.Fprintln(stdout, "bundle written; collection complete (not a health verdict)") + } else { + fmt.Fprintln(stdout, "bundle written; collection incomplete (see manifest.json)") + } + if !complete { + return 3 + } + return 0 +} + +// errBundleLogMissing: a declared log file that does not exist holds +// nothing to discover; it is unavailable, not unproven. +var errBundleLogMissing = errors.New("log file is unavailable") + +func readBundleLog(path string, since, until time.Time, discover ...func([]byte)) ([]byte, error) { + before, err := os.Lstat(path) + if errors.Is(err, os.ErrNotExist) { + return nil, errBundleLogMissing + } + if err != nil { + return nil, errors.New("log file is unavailable") + } + if !before.Mode().IsRegular() { + return nil, errors.New("log source must be a regular file, not a link or pipe") + } + f, err := openBundleLog(path) + if err != nil { + return nil, errors.New("cannot open log file") + } + defer f.Close() + after, err := f.Stat() + if err != nil || !after.Mode().IsRegular() || !os.SameFile(before, after) { + return nil, errors.New("log source changed during open") + } + if after.Size() > bundleSourceLimit { + return nil, errors.New("log file exceeds 4 MiB; use a bounded journal time window or rotate the log") + } + raw, err := io.ReadAll(io.LimitReader(f, bundleSourceLimit+1)) + if err != nil || len(raw) > bundleSourceLimit { + return nil, errors.New("log exceeds read bound") + } + if !utf8.Valid(raw) { + return nil, errors.New("log source is not UTF-8 text") + } + for _, observe := range discover { + observe(raw) + } + return recentBundleLog(raw, since, until) +} +func recentBundleLog(raw []byte, since, until time.Time) ([]byte, error) { + var out strings.Builder + active := false + seenStamp := false + scan := bufio.NewScanner(strings.NewReader(string(raw))) + scan.Buffer(make([]byte, 4096), 1<<20) + for scan.Scan() { + line := scan.Text() + fields := strings.Fields(line) + var at time.Time + var err error + if len(fields) >= 2 { + at, err = time.ParseInLocation("2006/01/02 15:04:05.999999", fields[0]+" "+fields[1], time.UTC) + } + if at.IsZero() && len(fields) > 0 { + at, err = time.Parse(time.RFC3339Nano, fields[0]) + if err != nil { + at, err = time.Parse("2006-01-02T15:04:05.999999-0700", fields[0]) + } + } + if !at.IsZero() && err == nil { + seenStamp = true + active = !at.Before(since) && !at.After(until) + } + if active { + out.WriteString(line) + out.WriteByte('\n') + } + } + if scan.Err() != nil { + return nil, errors.New("log record exceeds line bound") + } + if len(raw) > 0 && !seenStamp { + return nil, errors.New("no timestamped records; log window unavailable") + } + return []byte(out.String()), nil +} diff --git a/seaweed-block/cmd/sw-block/log_collect_linux_test.go b/seaweed-block/cmd/sw-block/log_collect_linux_test.go new file mode 100644 index 0000000000..04f49b3aa2 --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_linux_test.go @@ -0,0 +1,401 @@ +//go:build linux + +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "golang.org/x/sys/unix" + "google.golang.org/grpc" +) + +func TestLogCollectArgumentHelper(t *testing.T) { + if os.Getenv("SWB_LOG_COLLECT_CHILD") == "1" { + time.Sleep(time.Minute) + } +} +func TestLogCollectFindsCredentialsInProcessArgsBeforeWritingLogs(t *testing.T) { + const secret = "process-planted-7a71d6e691" + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + child := exec.Command(exe, "-test.run=^TestLogCollectArgumentHelper$", "--", "--api-token", secret) + child.Env = append(os.Environ(), "SWB_LOG_COLLECT_CHILD=1") + if err := child.Start(); err != nil { + t.Fatal(err) + } + defer func() { _ = child.Process.Kill(); _ = child.Wait() }() + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + file := filepath.Join(dir, "daemon.log") + bundle := filepath.Join(dir, "bundle") + os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" message "+secret+"\n"), 0600) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-server-id", "host-b", "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s' -pid %d", bundle, file, child.Process.Pid)}, &out, &errout) + if code != 3 { + t.Fatalf("exit%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "process-001-flags.json")) + if err != nil { + t.Fatal(err) + } + var args []string + if json.Unmarshal(raw, &args) != nil || !bytes.Contains(raw, []byte("--api-token")) { + t.Fatalf("invalid process flags: %s", raw) + } + filepath.WalkDir(bundle, func(p string, e os.DirEntry, err error) error { + if err == nil && !e.IsDir() { + b, _ := os.ReadFile(p) + if bytes.Contains(b, []byte(secret)) { + t.Errorf("process credential escaped in %s", e.Name()) + } + } + return err + }) +} +func TestLogCollectJournalsUseBoundsAndHeadSummaryIsReadOnly(t *testing.T) { + const secret = "unit-planted-2d1bbc76e1" + dir := t.TempDir() + argfile := filepath.Join(dir, "journal-args") + stamp := time.Now().UTC().Format(time.RFC3339Nano) + old := time.Now().Add(-time.Hour).UTC().Format(time.RFC3339Nano) + scripts := map[string]string{ + "systemctl": "#!/bin/sh\nprintf '%s\\n' 'ExecStart=/bin/blockvolume --api-token=" + secret + " --volume-id=v1'\n", + "journalctl": "#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$SWB_JOURNAL_ARGS\"\nprintf '%s\\n' '" + old + " old journal record' '" + stamp + " recent journal record " + secret + "'\n", + } + for name, script := range scripts { + if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0700); err != nil { + t.Fatal(err) + } + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + t.Setenv("SWB_JOURNAL_ARGS", argfile) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + s := inspectionControlServer{} + control.RegisterClusterEvidenceServiceServer(srv, s) + control.RegisterWorkspaceServiceServer(srv, s) + go srv.Serve(ln) + defer srv.Stop() + defer ln.Close() + store := newMemChunkStore() + useMemChunkStore(t, store) + v := cliVolume(t, store, "v1", "daily") + _ = volArgs("volume", v) + _, before, _ := runChunk(cliArgs("show", volArgs("volume", v))...) + holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/status": + fmt.Fprint(w, `{"VolumeID":"v1","ReplicaID":"r2","Epoch":2,"FrontendPrimaryReady":true,"Version":"test-rev"}`) + case "/status/durable": + fmt.Fprintf(w, `{"Volumes":[{"VolumeID":"v1","Impl":"walstore-chunk","Chunk":{"Attached":true,"Stats":{"LastCutNs":%d,"CutsFailed":0,"PendingUnresolved":false},"Maintenance":{"passesOk":1,"inProgress":false,"currentStartNs":0,"lastPass":{"atNs":%d,"planned":0,"removed":0,"plannedChunks":0,"plannedRoots":0,"plannedSegments":0,"removedChunks":0,"removedRoots":0,"removedSegments":0,"error":"","headGen":7,"headGenError":""}}}}]}`, time.Now().UnixNano(), time.Now().UnixNano()) + case "/status/nvme": + fmt.Fprint(w, `{"connected":true}`) + default: + http.NotFound(w, r) + } + })) + defer holder.Close() + bundle := filepath.Join(dir, "bundle") + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", ln.Addr().String(), "-filer", "test-filer", "-server-id", "host-b", "-status-addr", holder.URL, "-c", "log.collect -out '" + bundle + "' -unit sw-blockvolume.service -since 1m -o json"}, &out, &errout) + if code != 0 { + m, _ := os.ReadFile(filepath.Join(bundle, "manifest.json")) + t.Fatalf("complete collection exit%d %s %s manifest%s", code, &out, &errout, m) + } + log, err := os.ReadFile(filepath.Join(bundle, "unit-001.log")) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(log, []byte("recent journal record")) || bytes.Contains(log, []byte("old journal record")) || bytes.Contains(log, []byte(secret)) { + t.Fatalf("journal window or redaction: %s", log) + } + flags, _ := os.ReadFile(filepath.Join(bundle, "unit-001-flags.txt")) + if bytes.Contains(flags, []byte(secret)) || !bytes.Contains(flags, []byte("REDACTED")) { + t.Fatalf("unsafe flags: %s", flags) + } + args, _ := os.ReadFile(argfile) + for _, want := range []string{"--no-pager", "--utc", "--since=", "--until=", "--unit=sw-blockvolume.service"} { + if !bytes.Contains(args, []byte(want)) { + t.Fatalf("journal missing %s: %s", want, args) + } + } + for _, arg := range strings.Split(strings.TrimSpace(string(args)), "\n") { + if strings.HasPrefix(arg, "--since=") || strings.HasPrefix(arg, "--until=") { + if _, err := time.Parse("2006-01-02 15:04:05.000000 UTC", strings.SplitN(arg, "=", 2)[1]); err != nil { + t.Fatalf("journal bound is not systemd UTC form: %q", arg) + } + } + } + _, after, _ := runChunk(cliArgs("show", volArgs("volume", v))...) + if before != after { + t.Fatal("collection changed HEAD") + } + head, err := os.ReadFile(filepath.Join(bundle, "volume-001-head.json")) + if err != nil || !bytes.Contains(head, []byte("daily")) { + t.Fatalf("HEAD summary missing %v: %s", err, head) + } +} +func TestLogCollectJournalDeadlineAndLinkedFileAreUnavailable(t *testing.T) { + dir := t.TempDir() + file := filepath.Join(dir, "journalctl") + os.WriteFile(file, []byte("#!/bin/sh\nexec sleep 2\n"), 0700) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + parent, release := context.WithCancel(context.Background()) + defer release() + watchdog := time.AfterFunc(2*time.Second, release) + defer watchdog.Stop() + ctx, cancel := context.WithTimeout(parent, 30*time.Millisecond) + defer cancel() + started := time.Now() + _, err := bundleCommand(ctx, "journalctl", "--no-pager") + if err == nil || time.Since(started) > time.Second { + t.Fatalf("journal was unbounded: %v", err) + } + // The command-level linked-file control must not follow a selected key link. + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + target := filepath.Join(dir, "private-key") + link := filepath.Join(dir, "daemon.log") + os.WriteFile(target, []byte("do-not-copy"), 0600) + if err := os.Symlink(target, link); err != nil { + t.Fatal(err) + } + var out, errout bytes.Buffer + bundle := filepath.Join(dir, "bundle") + code := run([]string{"shell", "-master", addr, "-c", "log.collect -out '" + bundle + "' -log-file '" + link + "'"}, &out, &errout) + if code != 3 { + t.Fatalf("link certified: exit%d", code) + } + // The refused link was never read whole: redaction is not proven, so the + // manifest names it and carries only fixed diagnostics. + raw, _ := os.ReadFile(filepath.Join(bundle, "manifest.json")) + if !strings.Contains(string(raw), `"redaction": "not_proven"`) || !strings.Contains(string(raw), `"file-001.log"`) || strings.Contains(string(raw), "do-not-copy") { + t.Fatalf("link refusal missing: %s", raw) + } + if _, err := os.Stat(filepath.Join(bundle, "file-001.log")); !os.IsNotExist(err) { + t.Fatal("linked content copied") + } +} + +func TestLogCollectDefaultIncludesEveryTemplateInstanceWithoutAPlainHolder(t *testing.T) { + dir := t.TempDir() + stamp := time.Now().UTC().Format(time.RFC3339Nano) + scripts := map[string]string{ + "systemctl": "#!/bin/sh\nif [ \"$1\" = list-units ]; then\n printf '%s\\n' 'sw-blockvolume@first.service loaded active running first' 'sw-blockvolume@second.service loaded inactive dead second'\nelse\n printf '%s\\n' 'ExecStart=/bin/daemon --server-id=host-b'\nfi\n", + "journalctl": "#!/bin/sh\nfor arg in \"$@\"; do\n case \"$arg\" in\n --unit=sw-blockvolume.service) exit 9;;\n --unit=*) printf '%s %s\\n' '" + stamp + "' \"$arg\";;\n esac\ndone\n", + } + for name, script := range scripts { + if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0700); err != nil { + t.Fatal(err) + } + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + bundle := filepath.Join(dir, "bundle") + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-c", "log.collect -out '" + bundle + "'"}, &out, &errout) + if code != 3 { + t.Fatalf("incomplete remote observations result%d %s", code, &errout) + } + var combined bytes.Buffer + for _, name := range []string{"unit-001.log", "unit-002.log", "unit-003.log"} { + raw, err := os.ReadFile(filepath.Join(bundle, name)) + if err != nil { + t.Fatalf("missing discovered log%s: %v", name, err) + } + combined.Write(raw) + } + for _, unit := range []string{"sw-blockmaster.service", "sw-blockvolume@first.service", "sw-blockvolume@second.service"} { + if !bytes.Contains(combined.Bytes(), []byte(unit)) { + t.Fatalf("missing default source %s: %s", unit, &combined) + } + } + if bytes.Contains(combined.Bytes(), []byte("--unit=sw-blockvolume.service")) { + t.Fatal("invented a plain holder unit") + } + raw, _ := os.ReadFile(filepath.Join(bundle, "unit-discovery.json")) + if !json.Valid(raw) { + t.Fatalf("missing unit discovery inventory: %s", raw) + } +} + +// Model a pathname swapped after the collector's Lstat, before acquisition. +func TestLogCollectChangedSourceCannotBlockAcquisition(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "daemon.log") + if err := os.WriteFile(path, []byte("old regular file"), 0600); err != nil { + t.Fatal(err) + } + before, err := os.Lstat(path) + if err != nil || !before.Mode().IsRegular() { + t.Fatalf("initial source is not regular: %v", err) + } + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + if err := unix.Mkfifo(path, 0600); err != nil { + t.Fatal(err) + } + // This independent release also unblocks the old blocking-open mutant, + // so its failure is observed rather than hanging the package. + released := make(chan struct{}) + watchdog := time.AfterFunc(time.Second, func() { + fd, err := unix.Open(path, unix.O_RDWR|unix.O_NONBLOCK, 0) + if err == nil { + unix.Close(fd) + } + close(released) + }) + defer watchdog.Stop() + started := time.Now() + f, err := openBundleLog(path) + if err == nil { + info, statErr := f.Stat() + f.Close() + if statErr != nil { + t.Fatal(statErr) + } + // Unlink/create may immediately reuse the same inode on ext4. + // SameFile alone is not a type check: production also checks IsRegular. + if info.Mode().IsRegular() || info.Mode()&os.ModeNamedPipe == 0 { + t.Fatal("replacement descriptor is not the expected non-regular FIFO") + } + } + if time.Since(started) > 500*time.Millisecond { + t.Fatal("changed source needed watchdog to release acquisition") + } + select { + case <-released: + t.Fatal("acquisition reached watchdog") + default: + } +} + +// A declared unit whose journal output is truncated at its bound, with the +// collection's time budget still live: the credential named past the bound +// is never discovered, so no artifact repeating it is written. +func TestLogCollectTruncatedUnitWithholdsEveryArtifact(t *testing.T) { + const secret = "truncated-planted-60617" + dir := t.TempDir() + stamp := time.Now().UTC().Format(time.RFC3339Nano) + scripts := map[string]string{ + "systemctl": "#!/bin/sh\nprintf '%s\n' 'ExecStart=/bin/blockvolume --volume-id=v1'\n", + "journalctl": "#!/bin/sh\nhead -c 5000000 /dev/zero | tr '\\0' 'x'\nprintf '\\n%s --password=%s\\n' '" + stamp + "' '" + secret + "'\n", + } + for name, script := range scripts { + if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0700); err != nil { + t.Fatal(err) + } + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + file := filepath.Join(dir, "daemon.log") + if err := os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" opaque "+secret+"\n"), 0600); err != nil { + t.Fatal(err) + } + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + bundle := filepath.Join(dir, "bundle") + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1m", "-c", "log.collect -out '" + bundle + "' -unit 'sw-blockvolume@v1.service' -log-file '" + file + "'"}, &out, &errout) + if code != 3 || !strings.Contains(out.String(), "redaction not proven") { + t.Fatalf("exit %d %q %s", code, &out, &errout) + } + if n := bundleOccurrences(t, bundle, secret); n != 0 { + t.Fatalf("%d unredacted occurrences of the credential in the bundle", n) + } +} + +// fakeUnitCommands puts systemctl and journalctl scripts on PATH; journal +// is what journalctl prints. +func fakeUnitCommands(t *testing.T, journal string) { + t.Helper() + dir := t.TempDir() + scripts := map[string]string{ + "systemctl": "#!/bin/sh\nprintf '%s\\n' 'ExecStart=/bin/blockvolume --volume-id=v1'\n", + "journalctl": "#!/bin/sh\nprintf '%s\\n' '" + journal + "'\n", + } + for name, script := range scripts { + if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0700); err != nil { + t.Fatal(err) + } + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +// A declared source the time budget cut (a -unit's commands) may hold a +// credential another artifact repeats: the bundle then holds only its +// manifest, says the redaction is not proven, names the cut sources, and +// no byte of the bundle carries the credential. +func TestLogCollectCutDeclaredSourceWithholdsEveryArtifact(t *testing.T) { + fakeUnitCommands(t, "-- No entries --") + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + bundle := filepath.Join(dir, "bundle") + const secret = "cut-source-planted-77031" + file := filepath.Join(dir, "daemon.log") + if err := os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" opaque "+secret+"\n"), 0600); err != nil { + t.Fatal(err) + } + command := fmt.Sprintf("log.collect -out '%s' -unit 'sw-blockvolume@v1.service' -log-file '%s'", bundle, file) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1ns", "-c", command}, &out, &errout) + if code != 3 || !strings.Contains(out.String(), "incomplete: redaction not proven") || !strings.Contains(out.String(), "unit-001.log") { + t.Fatalf("exit %d %q %s", code, &out, &errout) + } + entries, err := os.ReadDir(bundle) + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if e.Name() != "manifest.json" { + t.Errorf("artifact %s written although redaction is not proven", e.Name()) + } + } + if n := bundleOccurrences(t, bundle, secret); n != 0 { + t.Fatalf("%d unredacted occurrences of the credential in the bundle", n) + } +} + +// A quiet unit (its journal read whole: no records in the window, exit 0) +// is only unavailable: it does not withhold the bundle. +func TestLogCollectQuietUnitIsOnlyUnavailable(t *testing.T) { + fakeUnitCommands(t, "-- No entries --") + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + bundle := filepath.Join(dir, "bundle") + file := filepath.Join(dir, "daemon.log") + if err := os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" local diagnostic\n"), 0600); err != nil { + t.Fatal(err) + } + command := fmt.Sprintf("log.collect -out '%s' -unit 'sw-blockvolume@v1.service' -log-file '%s'", bundle, file) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1m", "-c", command}, &out, &errout) + if code != 3 || strings.Contains(out.String(), "redaction not proven") { + t.Fatalf("exit %d %q %s", code, &out, &errout) + } + if raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")); err != nil || !bytes.Contains(raw, []byte("local diagnostic")) { + t.Fatalf("a quiet unit withheld the bundle: %v %q", err, raw) + } +} diff --git a/seaweed-block/cmd/sw-block/log_collect_local.go b/seaweed-block/cmd/sw-block/log_collect_local.go new file mode 100644 index 0000000000..3db4abfa06 --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_local.go @@ -0,0 +1,133 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "regexp" + "runtime" + "sort" + "strings" + "time" +) + +var bundleUnitName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.@:-]*$`) +var bundlePID = regexp.MustCompile(`^[1-9][0-9]{0,9}$`) + +func validBundleLocalSources(units, pids []string) bool { + for _, u := range units { + if len(u) > 256 || !bundleUnitName.MatchString(u) { + return false + } + } + for _, p := range pids { + if !bundlePID.MatchString(p) { + return false + } + } + return true +} +func bundleCommand(ctx context.Context, command string, args ...string) ([]byte, error) { + var out bundleBuffer + cmd := exec.CommandContext(ctx, command, args...) + cmd.Stdout = &out + cmd.Stderr = &out + cmd.WaitDelay = time.Second + err := cmd.Run() + return out.Bytes(), err +} + +// Discover running and inactive template instances without reading settings files. +func defaultBundleUnits(ctx context.Context) (bundleStrings, error) { + raw, err := bundleCommand(ctx, "systemctl", "list-units", "sw-blockvolume*.service", "--all", "--plain", "--no-legend", "--no-pager") + found := map[string]bool{} + for _, line := range strings.Split(string(raw), "\n") { + fields := strings.Fields(line) + if len(fields) == 0 { + continue + } + unit := fields[0] + if !strings.HasPrefix(unit, "sw-blockvolume") || !strings.HasSuffix(unit, ".service") { + continue + } + if !validBundleLocalSources([]string{unit}, nil) { + err = errors.New("a holder unit name could not be collected") + continue + } + found[unit] = true + } + holders := make([]string, 0, len(found)) + for unit := range found { + holders = append(holders, unit) + } + sort.Strings(holders) + if len(holders) > 31 { + holders = holders[:31] + err = errors.New("holder unit discovery exceeds collection bound") + } + if len(holders) == 0 { + holders = []string{"sw-blockvolume.service"} + } + return append(bundleStrings{"sw-blockmaster.service"}, holders...), err +} + +func (b *logBundle) collectLocal(ctx context.Context, units, pids []string) { + if len(units) == 0 && len(pids) == 0 { + b.addSource("startup-flags.json", nil, errors.New("no service unit or local process selected"), true) + } + for i, u := range units { + flags, err := bundleCommand(ctx, "systemctl", "show", "--property=ExecStart", "--value", "--", u) + b.addCommand(fmt.Sprintf("unit-%03d-flags.txt", i+1), flags, err, err) + raw, cmdErr := bundleCommand(ctx, "journalctl", "--no-pager", "--utc", "--output=short-iso-precise", "--since="+b.Since.UTC().Format("2006-01-02 15:04:05.000000 UTC"), "--until="+b.Until.UTC().Format("2006-01-02 15:04:05.000000 UTC"), "--unit="+u) + b.discover(raw) + err = cmdErr + if err == nil { + // The whole output was discovered: a window with no records is + // only unavailable, not unproven. + raw, err = recentBundleLog(raw, b.Since, b.Until) + } + b.addCommand(fmt.Sprintf("unit-%03d.log", i+1), raw, cmdErr, err) + } + for i, pid := range pids { + var raw []byte + var err error + gone := false // the process does not exist: nothing to discover + if runtime.GOOS != "linux" { + err = errors.New("process startup arguments require this Linux host") + } else { + f, e := os.Open("/proc/" + pid + "/cmdline") + err = e + gone = errors.Is(e, os.ErrNotExist) + if err == nil { + raw, err = io.ReadAll(io.LimitReader(f, bundleSourceLimit+1)) + f.Close() + } + if len(raw) > bundleSourceLimit { + raw = nil + err = errors.New("process arguments exceed collection bound") + } + } + var data []byte + if len(raw) == 0 && err == nil { + err = errors.New("process has no startup arguments") + } + if err == nil { + data, err = json.Marshal(strings.Split(strings.TrimRight(string(raw), "\x00"), "\x00")) + } + name := fmt.Sprintf("process-%03d-flags.json", i+1) + // A process that is gone, or an empty command line (a kernel thread), + // holds nothing to discover; any other failure left the arguments + // unread (over the bound, unreadable, not this Linux host). + if err != nil && !gone && !(len(raw) == 0 && err.Error() == "process has no startup arguments") { + b.unproven(name) + } + if err != nil { + err = errors.New("process startup arguments unavailable") + } + b.addSource(name, data, err, true) + } +} diff --git a/seaweed-block/cmd/sw-block/log_collect_open_linux.go b/seaweed-block/cmd/sw-block/log_collect_open_linux.go new file mode 100644 index 0000000000..d48c6c9222 --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_open_linux.go @@ -0,0 +1,15 @@ +package main + +import ( + "golang.org/x/sys/unix" + "os" +) + +// A renamed FIFO cannot block acquisition; a substituted link is never followed. +func openBundleLog(path string) (*os.File, error) { + fd, err := unix.Open(path, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0) + if err != nil { + return nil, err + } + return os.NewFile(uintptr(fd), path), nil +} diff --git a/seaweed-block/cmd/sw-block/log_collect_open_other.go b/seaweed-block/cmd/sw-block/log_collect_open_other.go new file mode 100644 index 0000000000..6ca23104fa --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_open_other.go @@ -0,0 +1,12 @@ +//go:build !linux && !windows + +package main + +import ( + "errors" + "os" +) + +func openBundleLog(path string) (*os.File, error) { + return nil, errors.New("safe local log acquisition is unavailable on this platform") +} diff --git a/seaweed-block/cmd/sw-block/log_collect_open_windows.go b/seaweed-block/cmd/sw-block/log_collect_open_windows.go new file mode 100644 index 0000000000..22f59dcbe5 --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_open_windows.go @@ -0,0 +1,33 @@ +package main + +import ( + "errors" + "golang.org/x/sys/windows" + "os" +) + +func openBundleLog(path string) (*os.File, error) { + name, err := windows.UTF16PtrFromString(path) + if err != nil { + return nil, err + } + handle, err := windows.CreateFile(name, windows.GENERIC_READ, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) + if err != nil { + return nil, err + } + kind, err := windows.GetFileType(handle) + if err != nil || kind != windows.FILE_TYPE_DISK { + windows.CloseHandle(handle) + return nil, errors.New("not a disk file") + } + var info windows.ByHandleFileInformation + if err := windows.GetFileInformationByHandle(handle, &info); err != nil { + windows.CloseHandle(handle) + return nil, err + } + if info.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 { + windows.CloseHandle(handle) + return nil, errors.New("not a regular file") + } + return os.NewFile(uintptr(handle), path), nil +} diff --git a/seaweed-block/cmd/sw-block/log_collect_redact.go b/seaweed-block/cmd/sw-block/log_collect_redact.go new file mode 100644 index 0000000000..2d77745b62 --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_redact.go @@ -0,0 +1,287 @@ +package main + +import ( + "encoding/json" + "io" + "net/url" + "regexp" + "sort" + "strconv" + "strings" + "time" +) + +const bundleRedacted = "[REDACTED]" + +// The same pass covers log text, structured status, startup arguments and errors. +// Claim IDs are public process identifiers, not authorization credentials. +var bundleSecretValue = regexp.MustCompile(`(?im)((?:--)?[a-z0-9_.-]*(?:password|passwd|token|secret|credential|api[_-]?key|access[_-]?key|private[_-]?key|control[_-]?key|tls[_-]?key|client[_-]?key|signing[_-]?key|jwt[a-z0-9_.-]*|hmac[a-z0-9_.-]*|key)[a-z0-9_.-]*["']?\s*(?:=|:|\s)\s*)(?:"((?:\\.|[^"\\\r\n])*)(?:"|\\?\r?$)|'([^'\r\n]*)(?:'|$)|([^\s,"';}]+))`) +var bundleAuthorization = regexp.MustCompile(`(?i)(\bauthorization["']?\s*[:=]\s*["']?(?:bearer|basic)\s+)([^\s"';,]+)`) +var bundlePrivateKey = regexp.MustCompile(`(?s)-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(?:-----END [A-Z ]*PRIVATE KEY-----|\z)`) +var bundleURLUser = regexp.MustCompile(`([a-zA-Z][a-zA-Z0-9+.-]*://)([^\s/@]+)@`) + +type bundleRedactor struct { + secrets map[string]bool + overflow bool + replacer *strings.Replacer + // collided: two keys of one JSON object sanitized to the same key in + // the value being redacted; that value's redaction is not proven. + collided bool +} + +func bundleSensitiveKey(k string) bool { + k = strings.ToLower(strings.NewReplacer("-", "", "_", "", ".", "").Replace(k)) + for _, part := range []string{"password", "passwd", "token", "secret", "credential", "authorization", "apikey", "accesskey", "privatekey", "controlkey", "tlskey", "clientkey", "signingkey", "jwt", "hmac", "keyfile"} { + if strings.Contains(k, part) { + return true + } + } + return k == "key" +} +func (r *bundleRedactor) remember(s string) { + ordinary := strings.ToLower(s) + switch ordinary { + case "", "true", "false", "yes", "no", "null": + return + } + if s == bundleRedacted { + return + } + if len(s) < 8 && strings.Trim(s, "0123456789") == "" { + return + } + if len(r.secrets) > 4096 { + r.overflow = true + return + } + r.secrets[s] = true + // An escaped appearance of an already identified secret is still a secret. + if b, err := json.Marshal(s); err == nil { + r.secrets[string(b[1:len(b)-1])] = true + } + r.secrets[url.QueryEscape(s)] = true +} +func (r *bundleRedactor) jsonValue(v any) any { + switch x := v.(type) { + case map[string]any: + // A key can carry a known credential too: keys are redacted like + // text. Two keys that then collide are not told apart (a suffix + // could itself be a credential): the value is refused. + out := make(map[string]any, len(x)) + for k, value := range x { + if bundleSensitiveKey(k) { + value = bundleRedacted + } else { + value = r.jsonValue(value) + } + key := r.redactText(k) + if _, taken := out[key]; taken { + r.collided = true + } + out[key] = value + } + return out + case []any: + for i, value := range x { + if s, ok := value.(string); ok && strings.HasPrefix(s, "-") { + flag, _, equals := strings.Cut(s, "=") + if bundleSensitiveKey(flag) { + if equals { + x[i] = flag + "=" + bundleRedacted + continue + } + if i+1 < len(x) { + if _, ok := x[i+1].(string); ok { + x[i+1] = bundleRedacted + } + } + } + } + x[i] = r.jsonValue(x[i]) + } + case string: + return r.redactText(x) + } + return v +} +func (r *bundleRedactor) discover(raw []byte) { + var v any + if bundleDecodeJSON(raw, &v) == nil { + r.discoverValue(v) + } + r.discoverText(string(raw)) +} +func (r *bundleRedactor) discoverValue(v any) { + switch x := v.(type) { + case map[string]any: + for k, v := range x { + if bundleSensitiveKey(k) { + r.rememberValue(v) + } else { + r.discoverValue(v) + } + } + case []any: + for i, v := range x { + if arg, ok := v.(string); ok && strings.HasPrefix(arg, "-") { + flag, value, equals := strings.Cut(arg, "=") + if bundleSensitiveKey(flag) { + if equals { + r.rememberValue(value) + } else if i+1 < len(x) { + r.rememberValue(x[i+1]) + } + } + } + r.discoverValue(v) + } + case string: + r.discoverText(x) + } +} +func (r *bundleRedactor) discoverText(text string) { + matches := bundleSecretValue.FindAllStringSubmatch(text, 4097) + if len(matches) == 4097 { + r.overflow = true + return + } + for _, m := range matches { + prefix := strings.TrimSpace(m[1]) + // Bare prose is masked in place, but is not a source of global secrets. + if !strings.ContainsAny(prefix, "=:") && !strings.HasPrefix(prefix, "-") { + continue + } + for _, s := range m[2:] { + r.remember(s) + if decoded, e := strconv.Unquote(`"` + s + `"`); e == nil { + r.remember(decoded) + } + } + } + matches = bundleAuthorization.FindAllStringSubmatch(text, 4097) + if len(matches) == 4097 { + r.overflow = true + return + } + for _, m := range matches { + r.remember(m[2]) + } + matches = bundleURLUser.FindAllStringSubmatch(text, 4097) + if len(matches) == 4097 { + r.overflow = true + return + } + for _, m := range matches { + if pair := strings.SplitN(m[2], ":", 2); len(pair) == 2 { + r.remember(m[2]) + r.remember(pair[1]) + if decoded, err := url.PathUnescape(pair[1]); err == nil { + r.remember(decoded) + } + } + } + for _, block := range bundlePrivateKey.FindAllString(text, -1) { + // A PEM embedded in a JSON log carries escaped line separators. + block = strings.NewReplacer(`\r\n`, "\n", `\n`, "\n", `\r`, "\n").Replace(block) + for _, line := range strings.Split(block, "\n") { + line = strings.TrimSpace(line) + if line != "" && !strings.Contains(line, "PRIVATE KEY-----") { + r.remember(line) + fields := strings.Fields(line) + if len(fields) >= 3 { + if _, err := time.Parse("2006/01/02 15:04:05.999999", fields[0]+" "+fields[1]); err == nil { + r.remember(strings.Join(fields[2:], " ")) + } + } + if len(fields) >= 2 { + if _, err := time.Parse(time.RFC3339Nano, fields[0]); err == nil { + r.remember(strings.Join(fields[1:], " ")) + } + } + } + } + } +} +func (r *bundleRedactor) rememberValue(v any) { + switch x := v.(type) { + case string: + r.remember(x) + // Sensitive JSON keys identify the whole value; Authorization also + // identifies the credential independently of its scheme. + fields := strings.Fields(x) + if len(fields) == 2 && (strings.EqualFold(fields[0], "Bearer") || strings.EqualFold(fields[0], "Basic")) { + r.remember(fields[1]) + } + r.discoverText(x) + case []any: + for _, v := range x { + r.rememberValue(v) + } + case map[string]any: + for _, v := range x { + r.rememberValue(v) + } + default: + if v != nil { + raw, _ := json.Marshal(v) + r.remember(string(raw)) + } + } +} + +// redactChecked is redact, and false when the redaction is not proven (two +// JSON keys collided once sanitized): the caller then writes nothing of it. +func (r *bundleRedactor) redactChecked(raw []byte) ([]byte, bool) { + r.collided = false + clean := r.redact(raw) + return clean, !r.collided +} + +func (r *bundleRedactor) redact(raw []byte) []byte { + var v any + if bundleDecodeJSON(raw, &v) == nil { + if b, err := json.MarshalIndent(r.jsonValue(v), "", " "); err == nil { + return append(b, '\n') + } + } + return []byte(r.redactText(string(raw))) +} +func (r *bundleRedactor) redactText(text string) string { + text = bundlePrivateKey.ReplaceAllString(text, "[REDACTED PRIVATE KEY]") + text = bundleAuthorization.ReplaceAllString(text, "${1}"+bundleRedacted) + text = bundleSecretValue.ReplaceAllString(text, "${1}"+`"`+bundleRedacted+`"`) + text = bundleURLUser.ReplaceAllString(text, "${1}"+bundleRedacted+"@") + if r.replacer == nil { + secrets := make([]string, 0, len(r.secrets)) + for s := range r.secrets { + if s != "" { + secrets = append(secrets, s) + } + } + sort.Slice(secrets, func(i, j int) bool { return len(secrets[i]) > len(secrets[j]) }) + pairs := make([]string, 0, 2*len(secrets)) + for _, secret := range secrets { + pairs = append(pairs, secret, bundleRedacted) + } + r.replacer = strings.NewReplacer(pairs...) + } + text = r.replacer.Replace(text) + return text +} + +// Preserve uint64 counters and positions exactly when sanitizing JSON. +func bundleDecodeJSON(raw []byte, v *any) error { + d := json.NewDecoder(strings.NewReader(string(raw))) + d.UseNumber() + if err := d.Decode(v); err != nil { + return err + } + var trailing any + if err := d.Decode(&trailing); err != io.EOF { + if err != nil { + return err + } + return io.ErrUnexpectedEOF + } + return nil +} diff --git a/seaweed-block/cmd/sw-block/log_collect_status.go b/seaweed-block/cmd/sw-block/log_collect_status.go new file mode 100644 index 0000000000..e97c95b24d --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_status.go @@ -0,0 +1,110 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "time" + + "github.com/seaweedfs/seaweed-block/internal/buildinfo" +) + +// A bounded writer is also used for existing command encoders and subprocesses. +type bundleBuffer struct{ buf bytes.Buffer } + +func (b *bundleBuffer) Len() int { return b.buf.Len() } +func (b *bundleBuffer) Bytes() []byte { return b.buf.Bytes() } +func (b *bundleBuffer) String() string { return b.buf.String() } +func (b *bundleBuffer) WriteString(s string) (int, error) { return b.Write([]byte(s)) } + +func (b *bundleBuffer) Write(p []byte) (int, error) { + left := bundleSourceLimit - b.Len() + if len(p) > left { + n, _ := b.buf.Write(p[:left]) + return n, errors.New("source exceeds collection bound") + } + return b.buf.Write(p) +} +func (b *logBundle) addJSON(name string, v any, err error) { + raw, e := json.Marshal(v) + if err == nil { + err = e + } + b.add(name, raw, err) +} +func (b *logBundle) collectStatus(ctx context.Context, s inspectionShell) { + started := time.Now() + cluster, err := readMasterClusterEvidence(ctx, s.master) + ended := time.Now() + b.addJSON("versions.json", map[string]string{"client": buildinfo.Version("sw-block"), "master": cluster.ProductRevision}, nil) + b.addJSON("cluster.json", cluster, err) + var check, diagnostic bundleBuffer + code := s.checkObservation(ctx, &inspectionObservation{shell: s, cluster: cluster, masterErr: err, started: started, ended: ended}, "json", &check, &diagnostic, 32) + var rows []inspectionResult + checkErr := json.Unmarshal(check.Bytes(), &rows) + if len(cluster.Volumes) > 32 { + checkErr = errors.New("cluster checks limited to the first 32 volumes") + } + if code == 2 { + checkErr = errors.New("cluster checks could not run") + } + for _, r := range rows { + if r.Status == "not checked here" { + checkErr = errors.New("some cluster checks were not checked here") + } + } + b.add("cluster-check.json", check.Bytes(), checkErr) + if err != nil { + return + } + for i, v := range cluster.Volumes { + if i >= 32 { + b.add("remaining-volumes.json", nil, errors.New("volume inventory exceeds collection bound")) + break + } + prefix := fmt.Sprintf("volume-%03d-", i+1) + for _, route := range []struct{ suffix, path string }{{"status", "/status"}, {"durable", "/status/durable"}, {"nvme", "/status/nvme"}} { + var raw json.RawMessage + var e error + if primaryInspectionHost(v) == "" || primaryInspectionHost(v) != s.serverID { + e = fmt.Errorf("not checked here: run on %s", primaryInspectionHost(v)) + } else { + e = s.readHolder(ctx, route.path, v.VolumeID, &raw) + } + b.add(prefix+route.suffix+".json", raw, e) + } + if s.filer == "" { + b.add(prefix+"head.json", nil, errors.New("filer not configured for HEAD summary")) + continue + } + if ctx.Err() != nil { + b.add(prefix+"head.json", nil, ctx.Err()) + continue + } + // Reuse the admitted name resolution and read-only HEAD summary command. + // The same caller context also bounds name resolution and store reads. + remaining := s.timeout + if end, ok := ctx.Deadline(); ok { + remaining = time.Until(end) + } + var out, errout bundleBuffer + code := chunkShowContext(ctx, []string{"--master", s.master, "--chunk-filer", s.filer, "--chunk-path", s.chunkPath, "--volume", v.VolumeID, "--timeout", remaining.String()}, &out, &errout) + var e error + if code != 0 { + e = errors.New("HEAD summary unavailable") + if errout.Len() > 0 { + b.add(prefix+"head-diagnostic.txt", errout.Bytes(), nil) + } + } + if !json.Valid(out.Bytes()) { + b.add(prefix+"head.json", nil, errors.New("HEAD summary did not return JSON")) + } else { + b.add(prefix+"head.json", out.Bytes(), e) + } + } +} + +var _ io.Writer = (*bundleBuffer)(nil) diff --git a/seaweed-block/cmd/sw-block/log_collect_test.go b/seaweed-block/cmd/sw-block/log_collect_test.go new file mode 100644 index 0000000000..0d143037ee --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_collect_test.go @@ -0,0 +1,785 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +func TestLogCollectPlantedSecretsNeverLeaveTheBundle(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + input := filepath.Join(dir, "daemon.log") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + const token = "planted-token-7c88293bd9" + const private = "planted-private-key-5e700b96" + const auth = "authorization-planted-2b1176e08" + const password = "url-password-planted-1ce197ac" + const signing = "signing-key-planted-37cfe8cb" + log := fmt.Sprintf("%s safe diagnostic claim_id=claim-for-support\n%s api_token=%s\n%s replayed opaque %s\n%s -----BEGIN PRIVATE KEY-----\n%s\n-----END PRIVATE KEY-----\n", stamp, stamp, token, stamp, token, stamp, private) + log += fmt.Sprintf("%s Authorization: Bearer %s\n%s fetch http://support:%s@localhost/metrics\n%s repeated opaque %s\n", stamp, auth, stamp, password, stamp, password) + log += fmt.Sprintf("%s -jwt.signing.key=%s\n%s opaque signing value %s\n", stamp, signing, stamp, signing) + if err := os.WriteFile(input, []byte(log), 0600); err != nil { + t.Fatal(err) + } + outDir := filepath.Join(dir, "bundle") + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-server-id", "host-b", "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s' -since 15m -o json", filepath.ToSlash(outDir), filepath.ToSlash(input))}, &out, &errout) + if code != 0 && code != 3 { + t.Fatalf("collect exit%d: %s %s", code, &out, &errout) + } + var result map[string]any + if json.Unmarshal(out.Bytes(), &result) != nil || result["bundle_written"] != true { + t.Fatalf("invalid collection result: %s", &out) + } + var combined bytes.Buffer + entries := 0 + err := filepath.WalkDir(outDir, func(path string, entry os.DirEntry, err error) error { + if err != nil { + return err + } + if entry.IsDir() { + return nil + } + entries++ + b, err := os.ReadFile(path) + if err != nil { + return err + } + combined.Write(b) + return nil + }) + if err != nil || entries < 2 { + t.Fatalf("missing real bundle: entries%d err%v", entries, err) + } + combined.Write(out.Bytes()) + combined.Write(errout.Bytes()) + for _, secret := range []string{token, private, auth, password, signing} { + if bytes.Contains(combined.Bytes(), []byte(secret)) { + t.Fatalf("planted secret left collection: %q", secret) + } + } + for _, safe := range []string{"safe diagnostic", "claim-for-support", "REDACTED"} { + if !strings.Contains(combined.String(), safe) { + t.Fatalf("lost useful evidence %q", safe) + } + } + raw, _ := os.ReadFile(input) + if string(raw) != log { + t.Fatal("collector changed source log") + } +} + +func TestLogCollectIncludesStatusAndReportsUnavailableSources(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + const secret = "status-planted-credential-8b942d" + holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/status": + fmt.Fprintf(w, `{"VolumeID":"v1","ReplicaID":"r2","Epoch":2,"FrontendPrimaryReady":true,"Version":"test-rev","api_token":%q}`, secret) + case "/status/durable": + fmt.Fprintf(w, `{"ProcessID":"test-process","Volumes":[],"claim_id":"support-claim","credentials":{"password":%q}}`, secret) + case "/status/nvme": + fmt.Fprint(w, `{"connected":true}`) + default: + http.NotFound(w, r) + } + })) + defer holder.Close() + dir := t.TempDir() + file := filepath.Join(dir, "daemon.log") + os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" diagnostic\n"), 0600) + bundle := filepath.Join(dir, "bundle") + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-server-id", "host-b", "-status-addr", holder.URL, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if code != 3 { + t.Fatalf("missing filer/start flags must be incomplete: exit%d %s", code, &errout) + } + for _, name := range []string{"versions.json", "cluster.json", "cluster-check.json", "volume-001-status.json", "volume-001-durable.json", "volume-001-nvme.json", "manifest.json"} { + raw, err := os.ReadFile(filepath.Join(bundle, name)) + if err != nil { + t.Fatalf("missing %s: %v", name, err) + } + var value any + if json.Unmarshal(raw, &value) != nil { + t.Fatalf("invalid JSON %s: %s", name, raw) + } + if bytes.Contains(raw, []byte(secret)) { + t.Fatalf("status secret escaped in %s", name) + } + } + raw, _ := os.ReadFile(filepath.Join(bundle, "volume-001-durable.json")) + if !bytes.Contains(raw, []byte("support-claim")) { + t.Fatal("lost claim identifier") + } + var m struct { + Artifacts []struct{ Name, State, Error string } + } + raw, _ = os.ReadFile(filepath.Join(bundle, "manifest.json")) + json.Unmarshal(raw, &m) + found := map[string]bool{} + for _, a := range m.Artifacts { + if a.State == "unavailable" { + found[a.Name] = a.Error != "" + } + } + for _, name := range []string{"volume-001-head.json", "startup-flags.json"} { + if !found[name] { + t.Fatalf("missing explicit incomplete source %s", name) + } + } +} + +func TestLogCollectUsesTheWindowAndRefusesExistingOutput(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + input := filepath.Join(dir, "events.log") + now := time.Now().UTC() + text := now.Add(-time.Hour).Format("2006/01/02 15:04:05.000000") + " old record\nold continuation\n" + now.Format("2006/01/02 15:04:05.000000") + " recent record\nrecent continuation\n" + now.Add(time.Hour).Format(time.RFC3339Nano) + " future record\n" + os.WriteFile(input, []byte(text), 0600) + bundle := filepath.Join(dir, "bundle") + args := []string{"shell", "-master", addr, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s' -since 1m", filepath.ToSlash(bundle), filepath.ToSlash(input))} + var out, errout bytes.Buffer + if code := run(args, &out, &errout); code != 3 { + t.Fatalf("partial bundle exit%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(raw, []byte("recent record\nrecent continuation")) || bytes.Contains(raw, []byte("old record")) || bytes.Contains(raw, []byte("future record")) { + t.Fatalf("wrong window: %s", raw) + } + before, _ := os.ReadFile(filepath.Join(bundle, "manifest.json")) + if code := run(args, &out, &errout); code != 2 { + t.Fatalf("existing output replaced: exit%d", code) + } + after, _ := os.ReadFile(filepath.Join(bundle, "manifest.json")) + if !bytes.Equal(before, after) { + t.Fatal("existing bundle changed") + } +} + +func TestLogCollectReportsUnreadableAndUnboundedInputs(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + for _, kind := range []string{"missing", "oversized", "unparseable", "binary"} { + t.Run(kind, func(t *testing.T) { + dir := t.TempDir() + input := filepath.Join(dir, "daemon.log") + bundle := filepath.Join(dir, "bundle") + var data []byte + switch kind { + case "oversized": + data = bytes.Repeat([]byte("x"), (4<<20)+1) + case "unparseable": + data = []byte("no timestamp and token=do-not-copy-this\n") + case "binary": + data = []byte{0xff, 0xfe, 0, 1} + } + if kind != "missing" { + if err := os.WriteFile(input, data, 0600); err != nil { + t.Fatal(err) + } + } + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(input))}, &out, &errout) + if code != 3 { + t.Fatalf("source failure became success: exit%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "manifest.json")) + if err != nil { + t.Fatal(err) + } + var m struct { + Artifacts []struct{ Name, State, Error string } + } + if json.Unmarshal(raw, &m) != nil { + t.Fatal("manifest is not JSON") + } + found := false + for _, a := range m.Artifacts { + if a.Name == "file-001.log" { + found = a.State == "unavailable" && a.Error != "" + } + } + if !found { + t.Fatal("unavailable source disappeared") + } + if _, err := os.Stat(filepath.Join(bundle, "file-001.log")); !os.IsNotExist(err) { + t.Fatal("unsafe source was copied") + } + }) + } +} +func TestLogCollectInvalidArgumentsNeverEchoSecretValues(t *testing.T) { + for _, args := range []string{"-unit 'bad;api_token=planted-value'", "-pid 'password=planted-value'", "-since planted-value", "-unknown planted-value"} { + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", "127.0.0.1:1", "-c", "log.collect -out unused " + args}, &out, &errout) + if code != 2 || strings.Contains(out.String()+errout.String(), "planted-value") { + t.Fatalf("invalid input leaked: exit%d %s %s", code, &out, &errout) + } + } +} + +func TestLogCollectKeepsLocalLogsWhenTheMasterDoesNotAnswer(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + done := make(chan struct{}) + var release sync.Once + releaseFixture := func() { release.Do(func() { close(done); _ = ln.Close() }) } + defer releaseFixture() + watchdog := time.AfterFunc(2*time.Second, releaseFixture) + defer watchdog.Stop() + defer ln.Close() + exited := make(chan struct{}) + defer func() { releaseFixture(); <-exited }() + go func() { + defer close(exited) + c, err := ln.Accept() + if err != nil { + return + } + defer c.Close() + <-done + }() + dir := t.TempDir() + file := filepath.Join(dir, "daemon.log") + bundle := filepath.Join(dir, "bundle") + os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" local diagnostic\n"), 0600) + var out, errout bytes.Buffer + started := time.Now() + code := run([]string{"shell", "-master", ln.Addr().String(), "-timeout", "50ms", "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if time.Since(started) > time.Second { + t.Fatal("collection needed the independent fixture watchdog") + } + if code != 3 { + t.Fatalf("stalled master result%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")) + if err != nil || !bytes.Contains(raw, []byte("local diagnostic")) { + t.Fatalf("master failure lost local logs: %v %s", err, raw) + } +} + +func TestLogCollectKeepsOrdinaryWordsAndGenerationsWhileRedactingTokens(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + file := filepath.Join(dir, "daemon.log") + bundle := filepath.Join(dir, "bundle") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + const secret = "7e0adc2391fa44d09d6f0a77b8c2f196" + text := fmt.Sprintf("%s lease token is stale for volume v1 / deletion tokens=2 gen=12->13 / this is fine\n%s token=%s\n%s opaque %s\n", stamp, stamp, secret, stamp, secret) + text += stamp + " lease token unavailable / status remains unavailable\n" + os.WriteFile(file, []byte(text), 0600) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if code != 3 { + t.Fatalf("exit%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")) + if err != nil { + t.Fatal(err) + } + for _, safe := range []string{stamp, "this is fine", "gen=12->13", "status remains unavailable"} { + if !bytes.Contains(raw, []byte(safe)) { + t.Fatalf("ordinary evidence %q destroyed: %s", safe, raw) + } + } + if bytes.Contains(raw, []byte(secret)) { + t.Fatalf("planted token escaped: %s", raw) + } +} + +// Each case teaches the collector exactly one credential, without another +// format accidentally supplying its value to discovery. +func TestLogCollectRecognizedCredentialFormsNeverLeaveTheBundle(t *testing.T) { + cases := []struct{ name, record, status, secret string }{ + {"short flag", `--password pw6abc`, "", "pw6abc"}, + {"embedded authorization", `{"Authorization":"Bearer embed-auth-376123"}`, "", "embed-auth-376123"}, + {"structured authorization", "diagnostic", `{"Authorization":"Basic structured-auth-82791"}`, "structured-auth-82791"}, + {"equals argv", "diagnostic", `["daemon","--password=multi word credential-82731"]`, "multi word credential-82731"}, + {"incomplete quoted", `password="incomplete credential-93812`, "", "incomplete credential-93812"}, + {"incomplete escape", `password="incomplete escaped-371982\`, "", "incomplete escaped-371982"}, + {"escaped pem", `{"message":"-----BEGIN PRIVATE KEY-----\nbody-planted-894123\n-----END PRIVATE KEY-----"}`, "", "body-planted-894123"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if tc.status != "" { + fmt.Fprint(w, tc.status) + } else { + fmt.Fprint(w, `{}`) + } + })) + defer holder.Close() + dir := t.TempDir() + file := filepath.Join(dir, "daemon.log") + bundle := filepath.Join(dir, "bundle") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + text := stamp + " " + tc.record + "\n" + stamp + " opaque repeat " + tc.secret + "\n" + if err := os.WriteFile(file, []byte(text), 0600); err != nil { + t.Fatal(err) + } + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-server-id", "host-b", "-status-addr", holder.URL, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if code != 3 { + t.Fatalf("exit%d %s", code, &errout) + } + count := 0 + err := filepath.WalkDir(bundle, func(p string, e os.DirEntry, err error) error { + if err != nil { + return err + } + if e.IsDir() { + return nil + } + count++ + raw, err := os.ReadFile(p) + if err != nil { + return err + } + if bytes.Contains(raw, []byte(tc.secret)) { + t.Errorf("credential survived in %s", e.Name()) + } + return nil + }) + if err != nil || count < 2 { + t.Fatalf("missing bundle: %d %v", count, err) + } + if strings.Contains(out.String()+errout.String(), tc.secret) { + t.Fatal("credential escaped command output") + } + }) + } +} + +func TestLogCollectPreservesExactLargeJSONNumbers(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"generation":18446744073709551615,"position":9007199254740993,"token":"number-test-credential"}`) + })) + defer holder.Close() + dir := t.TempDir() + file := filepath.Join(dir, "daemon.log") + bundle := filepath.Join(dir, "bundle") + os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" safe\n"), 0600) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-server-id", "host-b", "-status-addr", holder.URL, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if code != 3 { + t.Fatalf("exit%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "volume-001-status.json")) + if err != nil { + t.Fatal(err) + } + var got struct { + Generation uint64 + Position uint64 + Token string + } + if err := json.Unmarshal(raw, &got); err != nil { + t.Fatal(err) + } + if got.Generation != 18446744073709551615 || got.Position != 9007199254740993 || got.Token != "[REDACTED]" { + t.Fatalf("changed numeric evidence: %s", raw) + } +} + +func TestLogCollectRefusesExhaustedCredentialDiscovery(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + file := filepath.Join(dir, "daemon.log") + bundle := filepath.Join(dir, "bundle") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + text := strings.Repeat(stamp+" token=repeat\n", 4097) + stamp + " token=last-planted-73821\n" + stamp + " opaque last-planted-73821\n" + os.WriteFile(file, []byte(text), 0600) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if code != 1 { + t.Fatalf("incomplete credential discovery wrote a bundle: exit%d", code) + } + if _, err := os.Stat(bundle); !os.IsNotExist(err) { + t.Fatal("discovery overflow wrote output") + } +} + +func TestLogCollectDiscoversCredentialsBeforeTheTimeWindow(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + file := filepath.Join(dir, "daemon.log") + bundle := filepath.Join(dir, "bundle") + now := time.Now().UTC() + stamp := now.Format("2006/01/02 15:04:05.000000") + old := now.Add(-time.Hour).Format("2006/01/02 15:04:05.000000") + const secret = "window-body-923817" + text := old + " -----BEGIN PRIVATE KEY-----\n" + stamp + " " + secret + "\n" + stamp + " -----END PRIVATE KEY-----\n" + stamp + " opaque " + secret + "\n" + old + " old diagnostic\n" + os.WriteFile(file, []byte(text), 0600) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s' -since 1m", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if code != 3 { + t.Fatalf("exit%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")) + if err != nil { + t.Fatal(err) + } + if bytes.Contains(raw, []byte(secret)) || bytes.Contains(raw, []byte("old diagnostic")) { + t.Fatal("window leaked key body or retained an old record") + } +} + +func TestLogCollectDiscoversCredentialsInSourcesBeyondTheArtifactBudget(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + bundle := filepath.Join(dir, "bundle") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + const secret = "budget-planted-381927" + line := stamp + " " + strings.Repeat(" ", 65500) + "\n" + text := stamp + " opaque " + secret + "\n" + strings.Repeat(line, 63) + text += strings.Repeat(" ", (4<<20)-len(text)-1) + "\n" + command := fmt.Sprintf("log.collect -out '%s'", filepath.ToSlash(bundle)) + for i := 0; i < 8; i++ { + file := filepath.Join(dir, fmt.Sprintf("log%d", i)) + if err := os.WriteFile(file, []byte(text), 0600); err != nil { + t.Fatal(err) + } + command += fmt.Sprintf(" -log-file '%s'", filepath.ToSlash(file)) + } + file := filepath.Join(dir, "flags.log") + os.WriteFile(file, []byte(stamp+" --password="+secret+"\n"), 0600) + command += fmt.Sprintf(" -log-file '%s'", filepath.ToSlash(file)) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1m", "-c", command}, &out, &errout) + if code != 3 { + t.Fatalf("exit%d %s", code, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")) + if err != nil { + t.Fatal(err) + } + if bytes.Contains(raw, []byte(secret)) { + t.Fatal("discarding later source lost credential discovery") + } + if _, err := os.Stat(filepath.Join(bundle, "file-009.log")); !os.IsNotExist(err) { + t.Fatal("artifact byte limit was not preserved") + } +} + +type logCollectCountedInventory struct { + inspectionControlServer + reads atomic.Int32 +} + +func (s *logCollectCountedInventory) GetClusterStatus(ctx context.Context, q *control.GetClusterStatusRequest) (*control.ClusterStatusResponse, error) { + s.reads.Add(1) + return s.inspectionControlServer.GetClusterStatus(ctx, q) +} +func TestLogCollectUsesOneInventoryForChecksAndVolumeArtifacts(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + counted := &logCollectCountedInventory{} + control.RegisterClusterEvidenceServiceServer(server, counted) + control.RegisterWorkspaceServiceServer(server, counted) + go server.Serve(ln) + defer server.Stop() + defer ln.Close() + dir := t.TempDir() + file := filepath.Join(dir, "daemon.log") + bundle := filepath.Join(dir, "bundle") + os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" safe\n"), 0600) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", ln.Addr().String(), "-c", fmt.Sprintf("log.collect -out '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file))}, &out, &errout) + if code != 3 { + t.Fatalf("exit%d %s", code, &errout) + } + if counted.reads.Load() != 1 { + t.Fatalf("bundle used %d inventories", counted.reads.Load()) + } + for _, name := range []string{"cluster.json", "cluster-check.json"} { + raw, err := os.ReadFile(filepath.Join(bundle, name)) + if err != nil || !json.Valid(raw) { + t.Fatalf("missing inventory/check artifact %s: %v", name, err) + } + } +} + +// A time budget spent before the declared log files are read never cuts +// their credential discovery: a credential one file names (a flag) is +// redacted where another file repeats it. +func TestLogCollectSpentBudgetStillDiscoversEveryLogFile(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + bundle := filepath.Join(dir, "bundle") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + const secret = "spent-budget-planted-55120" + opaque := filepath.Join(dir, "opaque.log") + flags := filepath.Join(dir, "flags.log") + if err := os.WriteFile(opaque, []byte(stamp+" opaque "+secret+"\n"), 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(flags, []byte(stamp+" --password="+secret+"\n"), 0600); err != nil { + t.Fatal(err) + } + command := fmt.Sprintf("log.collect -out '%s' -log-file '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(opaque), filepath.ToSlash(flags)) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1ns", "-c", command}, &out, &errout) + if code != 3 { + t.Fatalf("exit %d %s %s", code, &out, &errout) + } + raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")) + if err != nil || !bytes.Contains(raw, []byte("opaque")) { + t.Fatalf("the first log file was not collected: %v %q", err, raw) + } + if n := bundleOccurrences(t, bundle, secret); n != 0 { + t.Fatalf("%d unredacted occurrences of the credential in the bundle", n) + } +} + +// bundleOccurrences counts secret over every byte of every file in the bundle. +func bundleOccurrences(t *testing.T, bundle, secret string) int { + t.Helper() + n := 0 + err := filepath.WalkDir(bundle, func(p string, d os.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + raw, err := os.ReadFile(p) + n += bytes.Count(raw, []byte(secret)) + return err + }) + if err != nil { + t.Fatal(err) + } + return n +} + +// collectUnproven runs log.collect over a small opaque log that repeats +// secret and the given extra arguments, and checks the bundle holds only its +// manifest, marked not proven, and no byte carrying secret. +func collectUnproven(t *testing.T, secret string, extra string) (stdout string) { + t.Helper() + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + bundle := filepath.Join(dir, "bundle") + opaque := filepath.Join(dir, "opaque.log") + if err := os.WriteFile(opaque, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" opaque "+secret+"\n"), 0600); err != nil { + t.Fatal(err) + } + extra = strings.ReplaceAll(extra, "DIR", filepath.ToSlash(dir)) + command := fmt.Sprintf("log.collect -out '%s' -log-file '%s' %s", filepath.ToSlash(bundle), filepath.ToSlash(opaque), extra) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1m", "-c", command}, &out, &errout) + if code != 3 || !strings.Contains(out.String(), "redaction not proven") { + t.Fatalf("exit %d %q %s", code, &out, &errout) + } + entries, err := os.ReadDir(bundle) + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if e.Name() != "manifest.json" { + t.Errorf("artifact %s written although redaction is not proven", e.Name()) + } + } + if n := bundleOccurrences(t, bundle, secret); n != 0 { + t.Fatalf("%d unredacted occurrences of the credential in the bundle", n) + } + return out.String() +} + +// A declared log file over its 4 MiB bound is the only source naming a +// credential another file repeats: it is never read whole, so nothing is written. +func TestLogCollectOversizedDeclaredFileWithholdsEveryArtifact(t *testing.T) { + const secret = "oversized-planted-31744" + dir := t.TempDir() + big := filepath.Join(dir, "flags.log") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + if err := os.WriteFile(big, []byte(stamp+" --password="+secret+"\n"+strings.Repeat("x", 5<<20)+"\n"), 0600); err != nil { + t.Fatal(err) + } + collectUnproven(t, secret, fmt.Sprintf("-log-file '%s'", filepath.ToSlash(big))) +} + +// A declared log file that is not text is refused before discovery: its +// discovery did not complete. +func TestLogCollectRefusedDeclaredFileWithholdsEveryArtifact(t *testing.T) { + dir := t.TempDir() + bad := filepath.Join(dir, "binary.log") + if err := os.WriteFile(bad, []byte{0xff, 0xfe, 0x00, '\n'}, 0600); err != nil { + t.Fatal(err) + } + collectUnproven(t, "refused-planted-90215", fmt.Sprintf("-log-file '%s'", filepath.ToSlash(bad))) +} + +// A declared log file that does not exist holds nothing to discover: it is +// unavailable, and the others are still written, redacted. +func TestLogCollectMissingDeclaredFileIsOnlyUnavailable(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + dir := t.TempDir() + bundle := filepath.Join(dir, "bundle") + file := filepath.Join(dir, "daemon.log") + if err := os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" local diagnostic\n"), 0600); err != nil { + t.Fatal(err) + } + command := fmt.Sprintf("log.collect -out '%s' -log-file '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file), filepath.ToSlash(filepath.Join(dir, "no-such.log"))) + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-timeout", "1m", "-c", command}, &out, &errout) + if code != 3 || strings.Contains(out.String(), "redaction not proven") { + t.Fatalf("exit %d %q %s", code, &out, &errout) + } + if raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")); err != nil || !bytes.Contains(raw, []byte("local diagnostic")) { + t.Fatalf("the readable log was not written: %v %q", err, raw) + } +} + +// A declared process whose arguments cannot be read leaves its discovery +// incomplete (off Linux they cannot be read at all); a process that is gone +// holds nothing to discover and is only unavailable. +func TestLogCollectUnreadablePIDWithholdsEveryArtifact(t *testing.T) { + if runtime.GOOS == "linux" { + t.Skip("off Linux a process's arguments cannot be read; on Linux a gone process is only unavailable") + } + collectUnproven(t, "pid-planted-41102", "-pid 1") +} + +// The names printed for skipped sources are sanitized like the manifest: a +// credential equal to a generated name is not printed. +func TestLogCollectSkippedNamesArePrintedSanitized(t *testing.T) { + dir := t.TempDir() + flags := filepath.Join(dir, "flags.log") + stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000") + if err := os.WriteFile(flags, []byte(stamp+" --password=file-003.log\n"), 0600); err != nil { + t.Fatal(err) + } + bad := filepath.Join(dir, "binary.log") // refused before discovery: file-003.log is skipped + if err := os.WriteFile(bad, []byte{0xff, 0xfe, 0x00, '\n'}, 0600); err != nil { + t.Fatal(err) + } + out := collectUnproven(t, "label-planted-27719", fmt.Sprintf("-log-file '%s' -log-file '%s'", filepath.ToSlash(flags), filepath.ToSlash(bad))) + if strings.Contains(out, "file-003.log") { + t.Fatalf("a known credential was printed as a skipped name: %q", out) + } +} + +// Unproven redaction replaces every free-form error in the manifest, also +// on entries that hold no data. +func TestLogCollectUnprovenManifestKeepsOnlyFixedErrors(t *testing.T) { + const secret = "error-planted-58810" + b := logBundle{Version: 1} + b.add("cluster.json", nil, errors.New("request failed: "+secret)) + b.unproven("file-001.log") + bundle := filepath.Join(t.TempDir(), "bundle") + if err := b.write(bundle); err != nil { + t.Fatal(err) + } + if n := bundleOccurrences(t, bundle, secret); n != 0 { + t.Fatalf("%d occurrences of a free-form error in the unproven manifest", n) + } +} + +// A known credential used as a JSON object key is redacted too, and the +// output stays valid JSON. +func TestLogCollectRedactsKnownCredentialsInJSONKeys(t *testing.T) { + const secret = "key-planted-77031" + r := &bundleRedactor{secrets: map[string]bool{}} + r.discover([]byte("--password=" + secret)) + out := r.redact([]byte(`{"` + secret + `":"opaque","other":{"` + secret + `":1}}`)) + if bytes.Contains(out, []byte(secret)) || !json.Valid(out) { + t.Fatalf("redacted JSON: %s", out) + } +} + +// Two JSON keys that collide once sanitized are not told apart by a suffix +// (the suffix could itself be a credential): that artifact is withheld, and +// no byte of the bundle carries any of the known credentials. +func TestLogCollectCollidingJSONKeysAreWithheld(t *testing.T) { + creds := []string{"alphaAAA", "betaBBBB", "#2"} + b := logBundle{Version: 1} + for _, c := range creds { + b.discover([]byte("--password=" + c)) + } + b.add("cluster.json", []byte(`{"alphaAAA":1,"betaBBBB":2,"plain":3}`), nil) + bundle := filepath.Join(t.TempDir(), "bundle") + if err := b.write(bundle); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(bundle, "cluster.json")); !os.IsNotExist(err) { + t.Fatal("an artifact whose keys collided once sanitized was written") + } + for _, c := range creds { + if n := bundleOccurrences(t, bundle, c); n != 0 { + t.Fatalf("%d occurrences of the known credential %q in the bundle", n, c) + } + } +} + +// Many keys that all sanitize to one (65,536 keys of a and b, both known) +// stop at the first collision: bounded work, and the artifact is withheld. +func TestLogCollectManyCollidingJSONKeysStopAtTheFirst(t *testing.T) { + b := logBundle{Version: 1} + b.discover([]byte("--password=a")) + b.discover([]byte("--password=b")) + var obj strings.Builder + obj.WriteByte('{') + for i := 0; i < 1<<16; i++ { + if i > 0 { + obj.WriteByte(',') + } + obj.WriteByte('"') + for bit := 15; bit >= 0; bit-- { + if i>>bit&1 == 1 { + obj.WriteByte('b') + } else { + obj.WriteByte('a') + } + } + obj.WriteString(`":1`) + } + obj.WriteByte('}') + b.add("cluster.json", []byte(obj.String()), nil) + bundle := filepath.Join(t.TempDir(), "bundle") + started := time.Now() + if err := b.write(bundle); err != nil { + t.Fatal(err) + } + if d := time.Since(started); d > 30*time.Second { + t.Fatalf("sanitizing colliding keys took %s", d) + } + if _, err := os.Stat(filepath.Join(bundle, "cluster.json")); !os.IsNotExist(err) { + t.Fatal("an artifact whose keys collided once sanitized was written") + } +} diff --git a/seaweed-block/cmd/sw-block/log_level_test.go b/seaweed-block/cmd/sw-block/log_level_test.go new file mode 100644 index 0000000000..00931a6d5e --- /dev/null +++ b/seaweed-block/cmd/sw-block/log_level_test.go @@ -0,0 +1,19 @@ +package main + +import ( + "bytes" + "strings" + "testing" +) + +func TestGlobalLogLevelFlagPreservesCommandOutput(t *testing.T) { + var out, errout bytes.Buffer + if code := run([]string{"--log-level=debug", "version"}, &out, &errout); code != 0 || !strings.Contains(out.String(), "sw-block") { + t.Fatalf("code=%d out=%q err=%q", code, out.String(), errout.String()) + } + out.Reset() + errout.Reset() + if code := run([]string{"--log-level=quiet", "version"}, &out, &errout); code == 0 || out.Len() != 0 || !strings.Contains(errout.String(), "info or debug") { + t.Fatalf("code=%d out=%q err=%q", code, out.String(), errout.String()) + } +} diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go new file mode 100644 index 0000000000..0bcdf7af0d --- /dev/null +++ b/seaweed-block/cmd/sw-block/main.go @@ -0,0 +1,2415 @@ +package main + +import ( + "context" + "crypto/rand" + "encoding/hex" + "flag" + "fmt" + "io" + "net" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "github.com/seaweedfs/seaweed-block/internal/buildinfo" + "github.com/seaweedfs/seaweed-block/internal/logging" + "gopkg.in/yaml.v3" +) + +func main() { + os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) +} + +var ( + opsStatusRunCommand = ops.DefaultRunCommand + opsInventoryRunCommand = ops.DefaultRunCommand + opsGenerateHelmValuesRunCommand = ops.DefaultRunCommand + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return ops.NewInClusterKubernetesStatusClient() + } + opsOperatorStatusWriterFactory = func() (ops.OperatorStatusWriter, error) { + return ops.NewInClusterKubernetesStatusClient() + } + opsSwBlockVolumeSourceFactory = func() (ops.OperatorSwBlockVolumeSource, error) { + return ops.NewInClusterKubernetesStatusClient() + } + opsLifecycleOwnerClientFactory = func() (ops.LifecycleOwnerClient, ops.OperatorEventSink, error) { + client, err := ops.NewInClusterKubernetesStatusClient() + if err != nil { + return nil, nil, err + } + client.EventComponent = "sw-block-lifecycle-owner" + return client, client, nil + } + opsAuthorityExecutorClientFactory = func() (ops.AuthorityExecutorClient, error) { + return ops.NewInClusterKubernetesStatusClient() + } + opsRebuildTargetOwnerClientFactory = func() (ops.RebuildTargetOwnerClient, error) { + return ops.NewInClusterKubernetesStatusClient() + } + opsFailbackTargetOwnerClientFactory = func() (ops.FailbackTargetOwnerClient, error) { + return ops.NewInClusterKubernetesStatusClient() + } + opsFrontendPublicationTargetOwnerClientFactory = func() (ops.FrontendPublicationTargetOwnerClient, error) { + return ops.NewInClusterKubernetesStatusClient() + } + opsFrontendPublicationExecutorClientFactory = func() (ops.FrontendPublicationExecutorClient, error) { + return ops.NewInClusterKubernetesStatusClient() + } + opsFailbackExecutorClientFactory = func() (ops.FailbackExecutorClient, error) { + return ops.NewInClusterKubernetesStatusClient() + } +) + +func run(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block", flag.ContinueOnError) + fs.SetOutput(stderr) + level := fs.String("log-level", "info", "log verbosity: info or debug; timestamps are UTC with microseconds (before ops)") + version := fs.Bool("version", false, "print build provenance and exit") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if err := logging.Configure(*level); err != nil { + fmt.Fprintln(stderr, "sw-block:", err) + return ops.VolumeStatusExitInvalid + } + if *version { + fmt.Fprintln(stdout, buildinfo.Version("sw-block")) + return ops.VolumeStatusExitOK + } + args = fs.Args() + if len(args) == 0 { + usage(stderr) + return ops.VolumeStatusExitInvalid + } + if args[0] == "--version" || args[0] == "version" { + fmt.Fprintln(stdout, buildinfo.Version("sw-block")) + return ops.VolumeStatusExitOK + } + if args[0] == "mini" { + return runMini(args[1:], stdout, stderr) + } + if args[0] == "volume" { + return runVolume(args[1:], stdout, stderr) + } + if args[0] == "shell" { + return runShell(args[1:], os.Stdin, stdout, stderr) + } + if args[0] == "cluster" { + return runCluster(args[1:], stdout, stderr) + } + if args[0] != "ops" { + fmt.Fprintf(stderr, "sw-block: unknown command %q\n", args[0]) + usage(stderr) + return ops.VolumeStatusExitInvalid + } + if len(args) < 2 { + fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk|volume|volume-unheld|workspace|failover") + usage(stderr) + return ops.VolumeStatusExitInvalid + } + switch args[1] { + case "status": + return runOpsStatus(args[2:], stdout, stderr) + case "inventory", "list": + return runOpsInventory(args[2:], stdout, stderr) + case "cluster": + return runOpsCluster(args[2:], stdout, stderr) + case "volumes": + return runOpsVolumes(args[2:], stdout, stderr) + case "describe": + return runOpsDescribe(args[2:], stdout, stderr) + case "timeline": + return runOpsTimeline(args[2:], stdout, stderr) + case "explain": + return runOpsExplain(args[2:], stdout, stderr) + case "report": + return runOpsReport(args[2:], stdout, stderr) + case "dashboard": + return runOpsDashboard(args[2:], stdout, stderr) + case "generate-helm-values": + return runOpsGenerateHelmValues(args[2:], stdout, stderr) + case "operator-status": + return runOpsOperatorStatus(args[2:], stdout, stderr) + case "lifecycle-owner": + return runOpsLifecycleOwner(args[2:], stdout, stderr) + case "authority-executor": + return runOpsAuthorityExecutor(args[2:], stdout, stderr) + case "rebuild-target-owner": + return runOpsRebuildTargetOwner(args[2:], stdout, stderr) + case "failback-target-owner": + return runOpsFailbackTargetOwner(args[2:], stdout, stderr) + case "failback-executor": + return runOpsFailbackExecutor(args[2:], stdout, stderr) + case "frontend-publication-target-owner": + return runOpsFrontendPublicationTargetOwner(args[2:], stdout, stderr) + case "frontend-publication-executor": + return runOpsFrontendPublicationExecutor(args[2:], stdout, stderr) + case "chunk": + return runOpsChunk(args[2:], stdout, stderr) + case "volume": + return runOpsVolume(args[2:], stdout, stderr) + case "volume-unheld": + return runOpsVolumeUnheld(args[2:], stdout, stderr) + case "workspace": + return runOpsWorkspace(args[2:], stdout, stderr) + case "failover": + return runOpsFailover(args[2:], stdout, stderr) + default: + fmt.Fprintf(stderr, "sw-block: unknown ops subcommand %q\n", args[1]) + usage(stderr) + return ops.VolumeStatusExitInvalid + } +} + +func runOpsFrontendPublicationExecutor(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops frontend-publication-executor", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + dryRun bool + namespace string + enableExecution bool + executionPolicyEnabled bool + runtimeURL string + interval time.Duration + ) + fs.BoolVar(&dryRun, "dry-run", false, "evaluate frontend publication targets without writing status") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace containing SwBlockFrontendPublication objects") + fs.BoolVar(&enableExecution, "enable-execution", false, "request frontend publication runtime execution for enabled SwBlockFrontendPublication targets") + fs.BoolVar(&executionPolicyEnabled, "execution-policy", false, "allow frontend publication runtime execution; must be set with --enable-execution") + fs.StringVar(&runtimeURL, "frontend-publication-runtime-url", "", "HTTP runtime endpoint for frontend publication execution") + fs.DurationVar(&interval, "interval", 0, "repeat frontend-publication-executor reconciliation at this interval; 0 runs once") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "sw-block ops frontend-publication-executor: unexpected args %s\n", strings.Join(fs.Args(), " ")) + return ops.VolumeStatusExitInvalid + } + if strings.TrimSpace(runtimeURL) != "" && !enableExecution { + fmt.Fprintln(stderr, "sw-block ops frontend-publication-executor: --frontend-publication-runtime-url requires --enable-execution") + return ops.VolumeStatusExitInvalid + } + runOnce := func() int { + client, err := opsFrontendPublicationExecutorClientFactory() + if err != nil { + fmt.Fprintf(stderr, "sw-block ops frontend-publication-executor: %v\n", err) + return ops.VolumeStatusExitInvalid + } + result, err := (ops.FrontendPublicationExecutorReconciler{ + Namespace: namespace, + Client: client, + DryRun: dryRun, + ExecutionRequested: enableExecution, + ExecutionPolicyEnabled: executionPolicyEnabled, + Runtime: frontendPublicationRuntimeFromURL(runtimeURL), + }).Reconcile(context.Background()) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops frontend-publication-executor: %v\n", err) + return ops.VolumeStatusExitInvalid + } + mode := "write_status" + if dryRun { + mode = "dry_run" + } + statusMutationAllowed := !dryRun && result.StatusWriteCount > 0 + fmt.Fprintf(stdout, "frontend_publication_executor=%s namespace=%s targets=%d status_writes=%d invalid_targets=%d frontend_publication_attempts=%d failback_attempts=%d status_mutation_allowed=%t frontend_publication_mutation_allowed=false mutation_allowed=%t storage_mutation_allowed=%t\n", + mode, + namespace, + result.TargetCount, + result.StatusWriteCount, + result.InvalidTargetCount, + result.FrontendPublicationAttempts, + result.FailbackAttempts, + statusMutationAllowed, + statusMutationAllowed, + result.StorageMutationAllowed) + return ops.VolumeStatusExitOK + } + if interval <= 0 { + return runOnce() + } + for { + code := runOnce() + if code != ops.VolumeStatusExitOK { + fmt.Fprintf(stderr, "sw-block ops frontend-publication-executor: iteration failed exit=%d; retrying in %s\n", code, interval) + } + time.Sleep(interval) + } +} + +func frontendPublicationRuntimeFromURL(runtimeURL string) ops.FrontendPublicationRuntime { + if strings.TrimSpace(runtimeURL) == "" { + return nil + } + return ops.NewHTTPFrontendPublicationRuntime(runtimeURL, nil) +} + +func runOpsFailbackExecutor(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops failback-executor", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + dryRun bool + namespace string + enableExecution bool + executionPolicyEnabled bool + failbackRuntimeURL string + failbackRuntimeGRPC string + interval time.Duration + ) + fs.BoolVar(&dryRun, "dry-run", false, "evaluate failback targets without writing SwBlockReplicaFailback status") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace containing SwBlockReplicaFailback objects") + fs.BoolVar(&enableExecution, "enable-execution", false, "request failback runtime execution") + fs.BoolVar(&executionPolicyEnabled, "execution-policy", false, "allow failback executor to evaluate execution; default is disabled") + fs.StringVar(&failbackRuntimeURL, "failback-runtime-url", "", "HTTP endpoint for failback runtime execution; empty uses target runtimeEndpoint when execution is enabled") + fs.StringVar(&failbackRuntimeGRPC, "failback-runtime-grpc-addr", "", "gRPC blockmaster FailbackService address for failback runtime execution") + fs.DurationVar(&interval, "interval", 0, "repeat failback-executor reconciliation at this interval; 0 runs once") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "sw-block ops failback-executor: unexpected args %s\n", strings.Join(fs.Args(), " ")) + return ops.VolumeStatusExitInvalid + } + if strings.TrimSpace(failbackRuntimeURL) != "" && !enableExecution { + fmt.Fprintf(stderr, "sw-block ops failback-executor: --failback-runtime-url requires --enable-execution reason=unsupported_runtime_without_execution failback_attempts=0\n") + return ops.VolumeStatusExitInvalid + } + if strings.TrimSpace(failbackRuntimeGRPC) != "" && !enableExecution { + fmt.Fprintf(stderr, "sw-block ops failback-executor: --failback-runtime-grpc-addr requires --enable-execution reason=unsupported_runtime_without_execution failback_attempts=0\n") + return ops.VolumeStatusExitInvalid + } + if strings.TrimSpace(failbackRuntimeURL) != "" && strings.TrimSpace(failbackRuntimeGRPC) != "" { + fmt.Fprintf(stderr, "sw-block ops failback-executor: --failback-runtime-url and --failback-runtime-grpc-addr are mutually exclusive reason=ambiguous_runtime failback_attempts=0\n") + return ops.VolumeStatusExitInvalid + } + if enableExecution && !executionPolicyEnabled { + fmt.Fprintf(stderr, "sw-block ops failback-executor: failback execution is disabled by product policy reason=%s failback_attempts=0 authority_mutation_allowed=false frontend_publication_allowed=false storage_mutation_allowed=false\n", ops.AuthorityExecutorFailbackReasonDisabled) + return ops.VolumeStatusExitInvalid + } + runOnce := func() int { + client, err := opsFailbackExecutorClientFactory() + if err != nil { + fmt.Fprintf(stderr, "sw-block ops failback-executor: %v\n", err) + return ops.VolumeStatusExitInvalid + } + var runtime ops.FailbackRuntime + if strings.TrimSpace(failbackRuntimeURL) != "" { + runtime = ops.NewHTTPFailbackRuntime(failbackRuntimeURL, nil) + } else if strings.TrimSpace(failbackRuntimeGRPC) != "" { + runtime = ops.NewGRPCFailbackRuntime(failbackRuntimeGRPC) + } + result, err := (ops.FailbackExecutorReconciler{ + Namespace: namespace, + Client: client, + Runtime: runtime, + DryRun: dryRun, + ExecutionRequested: enableExecution, + ExecutionPolicyEnabled: executionPolicyEnabled, + }).Reconcile(context.Background()) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops failback-executor: %v\n", err) + return ops.VolumeStatusExitInvalid + } + mode := "write_status" + if dryRun { + mode = "dry_run" + } + fmt.Fprintf(stdout, "failback_executor=%s namespace=%s targets=%d status_writes=%d invalid_targets=%d failback_attempts=%d execution_requested=%t execution_policy_enabled=%t status_mutation_allowed=%t authority_mutation_allowed=%t frontend_publication_allowed=%t mutation_allowed=%t storage_mutation_allowed=%t\n", + mode, + namespace, + result.TargetCount, + result.StatusWriteCount, + result.InvalidTargetCount, + result.FailbackAttempts, + enableExecution, + executionPolicyEnabled, + !dryRun && result.StatusWriteCount > 0, + result.AuthorityMutationAllowed, + result.FrontendPublicationAllowed, + !dryRun && result.StatusWriteCount > 0, + result.StorageMutationAllowed) + return ops.VolumeStatusExitOK + } + if interval <= 0 { + return runOnce() + } + for { + code := runOnce() + if code != ops.VolumeStatusExitOK { + fmt.Fprintf(stderr, "sw-block ops failback-executor: iteration failed exit=%d; retrying in %s\n", code, interval) + } + time.Sleep(interval) + } +} + +func runOpsFrontendPublicationTargetOwner(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops frontend-publication-target-owner", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + dryRun bool + namespace string + activateTargets bool + activationPolicyEnabled bool + runtimeEndpoint string + interval time.Duration + ) + fs.BoolVar(&dryRun, "dry-run", false, "evaluate frontend publication target planning without creating SwBlockFrontendPublication objects") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace containing SwBlockReplicaEligibility and SwBlockReplicaFailback objects") + fs.BoolVar(&activateTargets, "activate-targets", false, "create enabled frontend publication targets for explicit execution") + fs.BoolVar(&activationPolicyEnabled, "activation-policy", false, "allow frontend publication target activation; must be set with --activate-targets") + fs.StringVar(&runtimeEndpoint, "runtime-endpoint", "", "frontend publication runtime endpoint to stamp on activated targets") + fs.DurationVar(&interval, "interval", 0, "repeat frontend-publication-target-owner reconciliation at this interval; 0 runs once") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "sw-block ops frontend-publication-target-owner: unexpected args %s\n", strings.Join(fs.Args(), " ")) + return ops.VolumeStatusExitInvalid + } + runOnce := func() int { + client, err := opsFrontendPublicationTargetOwnerClientFactory() + if err != nil { + fmt.Fprintf(stderr, "sw-block ops frontend-publication-target-owner: %v\n", err) + return ops.VolumeStatusExitInvalid + } + result, err := (ops.FrontendPublicationTargetOwnerReconciler{ + Namespace: namespace, + Client: client, + DryRun: dryRun, + ActivateTargets: activateTargets, + ActivationPolicyEnabled: activationPolicyEnabled, + RuntimeEndpoint: runtimeEndpoint, + }).Reconcile(context.Background()) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops frontend-publication-target-owner: %v\n", err) + return ops.VolumeStatusExitInvalid + } + mode := "target_mutation" + if dryRun { + mode = "dry_run" + } + fmt.Fprintf(stdout, "frontend_publication_target_owner=%s namespace=%s eligibilities=%d ready_eligibilities=%d failbacks=%d terminal_failbacks=%d targets_planned=%d targets_existing=%d targets_created=%d invalid_eligibilities=%d invalid_failbacks=%d frontend_publication_attempts=%d failback_attempts=%d mutation_allowed=%t storage_mutation_allowed=%t\n", + mode, + namespace, + result.EligibilityCount, + result.ReadyEligibilityCount, + result.FailbackCount, + result.TerminalFailbackCount, + result.TargetPlannedCount, + result.TargetExistingCount, + result.TargetCreateCount, + result.InvalidEligibilityCount, + result.InvalidFailbackCount, + result.FrontendPublicationAttempts, + result.FailbackAttempts, + !dryRun && result.TargetCreateCount > 0, + result.StorageMutationAllowed) + return ops.VolumeStatusExitOK + } + if interval <= 0 { + return runOnce() + } + for { + code := runOnce() + if code != ops.VolumeStatusExitOK { + fmt.Fprintf(stderr, "sw-block ops frontend-publication-target-owner: iteration failed exit=%d; retrying in %s\n", code, interval) + } + time.Sleep(interval) + } +} + +func runOpsRebuildTargetOwner(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops rebuild-target-owner", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + dryRun bool + namespace string + interval time.Duration + ) + fs.BoolVar(&dryRun, "dry-run", false, "evaluate rebuild target planning without creating SwBlockReplicaRebuild objects") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace containing SwBlockVolume objects") + fs.DurationVar(&interval, "interval", 0, "repeat rebuild-target-owner reconciliation at this interval; 0 runs once") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "sw-block ops rebuild-target-owner: unexpected args %s\n", strings.Join(fs.Args(), " ")) + return ops.VolumeStatusExitInvalid + } + runOnce := func() int { + client, err := opsRebuildTargetOwnerClientFactory() + if err != nil { + fmt.Fprintf(stderr, "sw-block ops rebuild-target-owner: %v\n", err) + return ops.VolumeStatusExitInvalid + } + result, err := (ops.RebuildTargetOwnerReconciler{ + Namespace: namespace, + Client: client, + DryRun: dryRun, + }).Reconcile(context.Background()) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops rebuild-target-owner: %v\n", err) + return ops.VolumeStatusExitInvalid + } + mode := "target_mutation" + if dryRun { + mode = "dry_run" + } + fmt.Fprintf(stdout, "rebuild_target_owner=%s namespace=%s volumes=%d contracts=%d targets_planned=%d targets_existing=%d targets_created=%d invalid_contracts=%d runtime_target_ready=%d runtime_target_missing=%d mutation_allowed=%t storage_mutation_allowed=false frontend_publication_allowed=false failback_allowed=false\n", + mode, + namespace, + result.VolumeCount, + result.ContractCount, + result.TargetPlannedCount, + result.TargetExistingCount, + result.TargetCreateCount, + result.InvalidContractCount, + result.RuntimeTargetReadyCount, + result.RuntimeTargetMissingCount, + !dryRun && result.TargetCreateCount > 0) + return ops.VolumeStatusExitOK + } + if interval <= 0 { + return runOnce() + } + for { + code := runOnce() + if code != ops.VolumeStatusExitOK { + fmt.Fprintf(stderr, "sw-block ops rebuild-target-owner: iteration failed exit=%d; retrying in %s\n", code, interval) + } + time.Sleep(interval) + } +} + +func runOpsFailbackTargetOwner(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops failback-target-owner", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + dryRun bool + namespace string + interval time.Duration + activateTargets bool + activationPolicyEnabled bool + runtimeEndpoint string + ) + fs.BoolVar(&dryRun, "dry-run", false, "evaluate failback target planning without creating SwBlockReplicaFailback objects") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace containing SwBlockVolume objects") + fs.DurationVar(&interval, "interval", 0, "repeat failback-target-owner reconciliation at this interval; 0 runs once") + fs.BoolVar(&activateTargets, "activate-targets", false, "create failback targets with failbackDecision=enabled") + fs.BoolVar(&activationPolicyEnabled, "activation-policy", false, "allow failback target activation when --activate-targets is set") + fs.StringVar(&runtimeEndpoint, "runtime-endpoint", "", "failback runtime endpoint to stamp on activated targets") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "sw-block ops failback-target-owner: unexpected args %s\n", strings.Join(fs.Args(), " ")) + return ops.VolumeStatusExitInvalid + } + runOnce := func() int { + client, err := opsFailbackTargetOwnerClientFactory() + if err != nil { + fmt.Fprintf(stderr, "sw-block ops failback-target-owner: %v\n", err) + return ops.VolumeStatusExitInvalid + } + result, err := (ops.FailbackTargetOwnerReconciler{ + Namespace: namespace, + Client: client, + DryRun: dryRun, + ActivateTargets: activateTargets, + ActivationPolicyEnabled: activationPolicyEnabled, + RuntimeEndpoint: runtimeEndpoint, + }).Reconcile(context.Background()) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops failback-target-owner: %v\n", err) + return ops.VolumeStatusExitInvalid + } + mode := "target_mutation" + if dryRun { + mode = "dry_run" + } + fmt.Fprintf(stdout, "failback_target_owner=%s namespace=%s volumes=%d contracts=%d targets_planned=%d targets_existing=%d targets_created=%d invalid_contracts=%d authority_facts_missing=%d terminal_evidence_ready=%d terminal_evidence_missing=%d activate_targets=%t activation_policy=%t failback_attempts=%d mutation_allowed=%t storage_mutation_allowed=%t frontend_publication_allowed=%t\n", + mode, + namespace, + result.VolumeCount, + result.ContractCount, + result.TargetPlannedCount, + result.TargetExistingCount, + result.TargetCreateCount, + result.InvalidContractCount, + result.AuthorityFactsMissing, + result.TerminalEvidenceReady, + result.TerminalEvidenceMissing, + activateTargets, + activationPolicyEnabled, + result.FailbackAttempts, + !dryRun && result.TargetCreateCount > 0, + result.StorageMutationAllowed, + result.FrontendPublicationAllowed) + return ops.VolumeStatusExitOK + } + if interval <= 0 { + return runOnce() + } + for { + code := runOnce() + if code != ops.VolumeStatusExitOK { + fmt.Fprintf(stderr, "sw-block ops failback-target-owner: iteration failed exit=%d; retrying in %s\n", code, interval) + } + time.Sleep(interval) + } +} + +func runOpsAuthorityExecutor(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops authority-executor", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + namespace string + enableExecution bool + executionPolicyEnabled bool + allowedMutationClass string + rebuildRuntimeURL string + interval time.Duration + ) + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace containing SwBlockVolume objects") + fs.BoolVar(&enableExecution, "enable-execution", false, "request returned-replica executor mutation") + fs.BoolVar(&executionPolicyEnabled, "execution-policy", false, "allow authority executor to evaluate execution; still blocked until ACK mutation target exists") + fs.StringVar(&allowedMutationClass, "allowed-mutation-class", ops.AuthorityExecutorAllowedMutationAckEligibility, "supported values: ack_eligibility, rebuild_traffic") + fs.StringVar(&rebuildRuntimeURL, "rebuild-runtime-url", "", "HTTP endpoint for rebuild_traffic runtime execution; empty preserves planned-only status") + fs.DurationVar(&interval, "interval", 0, "repeat authority-executor reconciliation at this interval; 0 runs once") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "sw-block ops authority-executor: unexpected args %s\n", strings.Join(fs.Args(), " ")) + return ops.VolumeStatusExitInvalid + } + if allowedMutationClass != ops.AuthorityExecutorAllowedMutationAckEligibility && allowedMutationClass != ops.AuthorityExecutorAllowedMutationRebuildTraffic { + fmt.Fprintf(stderr, "sw-block ops authority-executor: unsupported mutation class %q reason=unsupported_mutation_class mutation_attempts=0 ack_eligibility_mutation_attempts=0 rebuild_progress_mutation_attempts=0\n", allowedMutationClass) + return ops.VolumeStatusExitInvalid + } + if strings.TrimSpace(rebuildRuntimeURL) != "" && allowedMutationClass != ops.AuthorityExecutorAllowedMutationRebuildTraffic { + fmt.Fprintf(stderr, "sw-block ops authority-executor: --rebuild-runtime-url requires --allowed-mutation-class rebuild_traffic reason=unsupported_runtime_mutation_class mutation_attempts=0 ack_eligibility_mutation_attempts=0 rebuild_progress_mutation_attempts=0\n") + return ops.VolumeStatusExitInvalid + } + if enableExecution && !executionPolicyEnabled { + fmt.Fprintf(stderr, "sw-block ops authority-executor: returned-replica execution is disabled by product policy reason=%s mutation_attempts=0 ack_eligibility_mutation_attempts=0 rebuild_progress_mutation_attempts=0\n", ops.AuthorityExecutorBlockedPolicyDisabled) + return ops.VolumeStatusExitInvalid + } + runOnce := func() int { + client, err := opsAuthorityExecutorClientFactory() + if err != nil { + fmt.Fprintf(stderr, "sw-block ops authority-executor: %v\n", err) + return ops.VolumeStatusExitInvalid + } + var rebuildRuntime ops.AuthorityRebuildRuntime + if strings.TrimSpace(rebuildRuntimeURL) != "" { + rebuildRuntime = ops.NewHTTPAuthorityRebuildRuntime(rebuildRuntimeURL, nil) + } + result, err := (ops.AuthorityExecutorReconciler{ + Namespace: namespace, + Client: client, + RebuildRuntime: rebuildRuntime, + ExecutionRequested: enableExecution, + ExecutionPolicyEnabled: executionPolicyEnabled, + AllowedMutationClass: allowedMutationClass, + }).Reconcile(context.Background()) + if err != nil { + if result.BlockedReason != "" { + fmt.Fprintf(stderr, "sw-block ops authority-executor: %v reason=%s mutation_attempts=%d ack_eligibility_mutation_attempts=%d rebuild_progress_mutation_attempts=%d\n", + err, result.BlockedReason, result.MutationAttemptCount, result.AckEligibilityMutationAttempts, result.RebuildProgressMutationAttempts) + } else { + fmt.Fprintf(stderr, "sw-block ops authority-executor: %v\n", err) + } + return ops.VolumeStatusExitInvalid + } + status := "disabled" + if enableExecution && result.MutationAttemptCount > 0 && result.BlockedReason != "" { + status = "partial" + } else if enableExecution && result.MutationAttemptCount > 0 { + status = "executed" + } else if enableExecution && result.BlockedReason != "" { + status = "blocked" + } + fmt.Fprintf(stdout, "authority_executor=%s namespace=%s volumes=%d contracts=%d disabled_contracts=%d blocked_contracts=%d terminal_evidence_required=%d terminal_evidence_missing=%d ack_eligibility_target_missing=%d rebuild_target_missing=%d allowed_mutation_class=%s execution_requested=%t execution_policy_enabled=%t mutation_attempts=%d ack_eligibility_mutation_attempts=%d rebuild_progress_mutation_attempts=%d mutation_allowed=%t storage_mutation_allowed=false\n", + status, + namespace, + result.VolumeCount, + result.ContractCount, + result.DisabledContractCount, + result.BlockedContractCount, + result.TerminalEvidenceRequiredCount, + result.TerminalEvidenceMissingCount, + result.AckEligibilityTargetMissingCount, + result.RebuildTargetMissingCount, + allowedMutationClass, + enableExecution, + executionPolicyEnabled, + result.MutationAttemptCount, + result.AckEligibilityMutationAttempts, + result.RebuildProgressMutationAttempts, + result.MutationAttemptCount > 0) + return ops.VolumeStatusExitOK + } + if interval <= 0 { + return runOnce() + } + for { + code := runOnce() + if code != ops.VolumeStatusExitOK { + fmt.Fprintf(stderr, "sw-block ops authority-executor: iteration failed exit=%d; retrying in %s\n", code, interval) + } + time.Sleep(interval) + } +} + +func runOpsLifecycleOwner(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops lifecycle-owner", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + dryRun bool + namespace string + interval time.Duration + ) + fs.BoolVar(&dryRun, "dry-run", false, "evaluate lifecycle-owner reconciliation without patching finalizers or emitting Events") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace containing SwBlockVolume objects") + fs.DurationVar(&interval, "interval", 0, "repeat lifecycle-owner reconciliation at this interval; 0 runs once") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "sw-block ops lifecycle-owner: unexpected args %s\n", strings.Join(fs.Args(), " ")) + return ops.VolumeStatusExitInvalid + } + runOnce := func() int { + client, events, err := opsLifecycleOwnerClientFactory() + if err != nil { + fmt.Fprintf(stderr, "sw-block ops lifecycle-owner: %v\n", err) + return ops.VolumeStatusExitInvalid + } + mode := "finalizer_mutation" + if dryRun { + mode = "dry_run" + events = nil + } + result, err := (ops.LifecycleOwnerReconciler{ + Namespace: namespace, + Client: client, + EventSink: events, + DryRun: dryRun, + }).Reconcile(context.Background()) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops lifecycle-owner: %v\n", err) + return ops.VolumeStatusExitInvalid + } + fmt.Fprintf(stdout, "lifecycle_owner=%s namespace=%s volumes=%d finalizer_patches=%d finalizer_added=%d finalizer_held=%d finalizer_released=%d events=%d mutation_allowed=%t\n", + mode, + namespace, + result.VolumeCount, + result.FinalizerPatchCount, + result.FinalizerAddedCount, + result.FinalizerHeldCount, + result.FinalizerReleasedCount, + result.EventCount, + !dryRun) + return ops.VolumeStatusExitOK + } + if interval <= 0 { + return runOnce() + } + for { + code := runOnce() + if code != ops.VolumeStatusExitOK { + fmt.Fprintf(stderr, "sw-block ops lifecycle-owner: iteration failed exit=%d; retrying in %s\n", code, interval) + } + time.Sleep(interval) + } +} + +func runOpsOperatorStatus(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops operator-status", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + dryRun bool + fromBundle string + cleanupSummary string + namespace string + masterAddr string + masterAPIAddr string + outDir string + productRevision string + claimProfile string + clusterName string + timeout time.Duration + interval time.Duration + ) + fs.BoolVar(&dryRun, "dry-run", false, "render the status projection without writing Kubernetes CRD status") + fs.StringVar(&fromBundle, "from-bundle", "", "existing inventory/support bundle directory to project") + fs.StringVar(&cleanupSummary, "cleanup-summary", "", "cleanup-summary.txt evidence to project into delete-safety status") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace for live read-only inventory") + fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address for live per-replica status evidence") + fs.StringVar(&masterAPIAddr, "master-api", "", "optional blockmaster gRPC address for ClusterEvidenceService read-only snapshot") + fs.StringVar(&outDir, "out", "", "optional directory for nested live status evidence") + fs.StringVar(&productRevision, "product-revision", "", "product revision label for live evidence") + fs.StringVar(&claimProfile, "claim-profile", "", "promotion-readiness claim profile for live evidence") + fs.StringVar(&clusterName, "cluster-name", ops.DefaultSwBlockClusterName, "SwBlockCluster object name") + fs.DurationVar(&timeout, "timeout", 5*time.Second, "live collection timeout") + fs.DurationVar(&interval, "interval", 0, "repeat dry-run projection at this interval; 0 runs once") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "sw-block ops operator-status: unexpected args %s\n", strings.Join(fs.Args(), " ")) + return ops.VolumeStatusExitInvalid + } + runOnce := func() int { + clusterArgs := []string{"--namespace", namespace, "--timeout", timeout.String()} + if fromBundle != "" { + clusterArgs = append(clusterArgs, "--from-bundle", fromBundle) + } + if masterAddr != "" { + clusterArgs = append(clusterArgs, "--master", masterAddr) + } + if masterAPIAddr != "" { + clusterArgs = append(clusterArgs, "--master-api", masterAPIAddr) + } + if outDir != "" { + clusterArgs = append(clusterArgs, "--out", outDir) + } + if productRevision != "" { + clusterArgs = append(clusterArgs, "--product-revision", productRevision) + } + if claimProfile != "" { + clusterArgs = append(clusterArgs, "--claim-profile", claimProfile) + } + cluster, _, code := loadObservationCluster("sw-block ops operator-status", clusterArgs, stderr) + if code != ops.VolumeStatusExitOK { + return code + } + if cleanupSummary != "" { + cleanup, err := ops.LoadCleanupEvidenceSummary(cleanupSummary) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops operator-status: %v\n", err) + return ops.VolumeStatusExitInvalid + } + cluster.Cleanup = cleanup + } + mode := "write_status" + var writer ops.OperatorStatusWriter + var events ops.OperatorEventSink + var volumes ops.OperatorSwBlockVolumeSource + if dryRun { + mode = "dry_run" + writer = &operatorStatusDryRunWriter{} + events = &operatorStatusDryRunEventSink{} + } else { + var err error + writer, err = opsOperatorStatusWriterFactory() + if err != nil { + fmt.Fprintf(stderr, "sw-block ops operator-status: %v\n", err) + return ops.VolumeStatusExitInvalid + } + events, _ = writer.(ops.OperatorEventSink) + volumes, _ = writer.(ops.OperatorSwBlockVolumeSource) + } + result, err := (ops.OperatorStatusReconciler{ + Namespace: namespace, + ClusterName: clusterName, + Source: operatorStatusClusterSource{cluster: cluster}, + Writer: writer, + Volumes: volumes, + EventSink: events, + }).Reconcile(context.Background()) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops operator-status: %v\n", err) + return ops.VolumeStatusExitInvalid + } + fmt.Fprintf(stdout, "operator_status=%s cluster=%s/%s volumes=%d events=%d finalizer_patches=%d mutation_allowed=false\n", + mode, + result.ClusterRef.Namespace, + result.ClusterRef.Name, + len(result.VolumeRefs), + result.EventCount, + result.FinalizerPatchCount) + if dryWriter, ok := writer.(*operatorStatusDryRunWriter); ok { + fmt.Fprintf(stdout, "cluster_status volumes=%d ready=%d blocked=%d stale=%d\n", + dryWriter.cluster.VolumeCount, + dryWriter.cluster.ReadyVolumeCount, + dryWriter.cluster.BlockedVolumeCount, + dryWriter.cluster.StaleVolumeCount) + for _, volume := range dryWriter.volumes { + fmt.Fprintf(stdout, "volume_status name=%s volume_id=%s pvc=%s status=%s reason=%s\n", + volume.ref.Name, + emptyCLI(volume.status.VolumeID), + emptyCLI(volume.status.PVCName), + emptyCLI(volume.status.Status), + emptyCLI(volume.status.ReasonCode)) + } + } + return ops.VolumeStatusExitOK + } + if interval <= 0 { + return runOnce() + } + for { + code := runOnce() + if code != ops.VolumeStatusExitOK { + fmt.Fprintf(stderr, "sw-block ops operator-status: iteration failed exit=%d; retrying in %s\n", code, interval) + } + time.Sleep(interval) + } +} + +func runOpsStatus(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops status", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + volumeID string + masterAddr string + statusAddr string + outDir string + productRevision string + runnerRevision string + timeout time.Duration + ) + fs.StringVar(&volumeID, "volume", "", "volume id to inspect") + fs.StringVar(&masterAddr, "master", "", "blockmaster gRPC address for read-only QueryVolumeStatus") + fs.StringVar(&statusAddr, "status-addr", "", "blockvolume loopback status address or URL") + fs.StringVar(&outDir, "out", "", "directory for volume-status-report.json, volume-status-summary.txt, and ops-status-bundle.json") + fs.StringVar(&productRevision, "product-revision", "", "product revision label to include in the report") + fs.StringVar(&runnerRevision, "runner-revision", "", "runner revision label to include in the report") + fs.DurationVar(&timeout, "timeout", 5*time.Second, "collection timeout") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if volumeID == "" || outDir == "" { + fmt.Fprintln(stderr, "sw-block ops status: --volume and --out are required") + return ops.VolumeStatusExitInvalid + } + if masterAddr == "" || statusAddr == "" { + fmt.Fprintln(stderr, "sw-block ops status: --master and --status-addr are both required for a clean live report") + return ops.VolumeStatusExitInvalid + } + if productRevision == "" { + productRevision = buildinfo.Version("sw-block") + } + + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + collector := ops.NewLiveVolumeStatusReportCollector(ops.LiveVolumeStatusConfig{ + VolumeID: volumeID, + MasterAddr: masterAddr, + StatusAddr: statusAddr, + ProductRevision: productRevision, + RunnerRevision: runnerRevision, + RunCommand: opsStatusRunCommand, + }) + report, code, err := ops.WriteVolumeStatusArtifacts(ctx, outDir, collector) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops status: %v\n", err) + } + fmt.Fprint(stdout, ops.RenderVolumeStatusSummary(report)) + if code != ops.VolumeStatusExitInvalid { + fmt.Fprintf(stdout, "artifacts: %s %s %s\n", ops.VolumeStatusReportArtifact, ops.VolumeStatusSummaryArtifact, ops.OpsStatusBundleArtifact) + } + return code +} + +func runOpsInventory(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops inventory", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + namespace string + masterAddr string + outDir string + productRevision string + runnerRevision string + claimProfile string + requiredFrontiers requiredFrontierFlags + timeout time.Duration + ) + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace to inspect once live discovery is enabled") + fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address; when set, collect per-replica ops status bundles for replicas with --status-addr") + fs.StringVar(&outDir, "out", "", "directory for volume-inventory.json, volume-inventory-summary.txt, and ops-inventory-bundle.json") + fs.StringVar(&productRevision, "product-revision", "", "product revision label to include in the inventory") + fs.StringVar(&runnerRevision, "runner-revision", "", "runner revision label to include in the inventory") + fs.StringVar(&claimProfile, "claim-profile", "", "promotion-readiness claim profile: beta-recovery (default), controlled-best-effort-demo, or stage2-iscsi-alua-multipath") + fs.Var(&requiredFrontiers, "required-frontier", "mounted-writer required frontier as volume_id=lsn; repeat for multiple volumes") + fs.DurationVar(&timeout, "timeout", 5*time.Second, "collection timeout") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if outDir == "" { + fmt.Fprintln(stderr, "sw-block ops inventory: --out is required") + return ops.VolumeStatusExitInvalid + } + if productRevision == "" { + productRevision = buildinfo.Version("sw-block") + } + if !ops.PromotionClaimProfileAccepted(claimProfile) { + fmt.Fprintf(stderr, "sw-block ops inventory: --claim-profile=%q invalid; want %q, %q, or %q\n", claimProfile, ops.PromotionClaimBetaRecovery, ops.PromotionClaimControlledBestEffortDemo, ops.PromotionClaimStage2ISCSIALUAMultipath) + return ops.VolumeStatusExitInvalid + } + + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + collector := ops.NewKubernetesVolumeInventoryCollector(ops.KubernetesInventoryConfig{ + Namespace: namespace, + MasterAddr: masterAddr, + StatusBundleRoot: outDir, + ProductRevision: productRevision, + RunnerRevision: runnerRevision, + ClaimProfile: claimProfile, + RequiredFrontiers: requiredFrontiers.values, + RunCommand: opsInventoryRunCommand, + }) + inventory, code, err := ops.WriteVolumeInventoryArtifacts(ctx, outDir, collector) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops inventory: %v\n", err) + } + fmt.Fprint(stdout, ops.RenderVolumeInventorySummary(inventory)) + if code != ops.VolumeStatusExitInvalid { + fmt.Fprintf(stdout, "artifacts: %s %s %s\n", ops.VolumeInventoryArtifact, ops.VolumeInventorySummaryArtifact, ops.OpsInventoryBundleArtifact) + } + return code +} + +func runOpsCluster(args []string, stdout, stderr io.Writer) int { + cluster, out, code := loadObservationCluster("sw-block ops cluster", args, stderr) + if code != ops.VolumeStatusExitOK { + return code + } + if out == "json" { + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops cluster: %v\n", err) + return ops.VolumeStatusExitInvalid + } + _, _ = stdout.Write(raw) + return ops.VolumeStatusExitOK + } + fmt.Fprint(stdout, ops.RenderClusterEvidenceText(cluster)) + return ops.VolumeStatusExitOK +} + +func runOpsVolumes(args []string, stdout, stderr io.Writer) int { + cluster, out, code := loadObservationCluster("sw-block ops volumes", args, stderr) + if code != ops.VolumeStatusExitOK { + return code + } + if out == "json" { + raw, err := ops.MarshalObservationJSON(cluster.Volumes) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops volumes: %v\n", err) + return ops.VolumeStatusExitInvalid + } + _, _ = stdout.Write(raw) + return ops.VolumeStatusExitOK + } + for _, volume := range cluster.Volumes { + fmt.Fprintf(stdout, "volume %s status=%s rf=%d primary=%s node=%s frontend=%s\n", + emptyCLI(volume.VolumeID), + emptyCLI(volume.Status), + volume.ReplicationFactor, + emptyCLI(volume.PrimaryReplica), + emptyCLI(volume.PrimaryNode), + emptyCLI(volume.PublishTarget)) + } + if len(cluster.Volumes) == 0 { + fmt.Fprintln(stdout, "volumes: none") + } + return ops.VolumeStatusExitOK +} + +func runOpsDescribe(args []string, stdout, stderr io.Writer) int { + cluster, out, code := loadObservationVolume("sw-block ops describe", args, stderr) + if code != ops.VolumeStatusExitOK { + return code + } + switch out { + case "json": + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops describe: %v\n", err) + return ops.VolumeStatusExitInvalid + } + _, _ = stdout.Write(raw) + default: + fmt.Fprint(stdout, ops.RenderClusterEvidenceText(cluster)) + } + return ops.VolumeStatusExitOK +} + +func loadObservationCluster(command string, args []string, stderr io.Writer) (ops.ClusterEvidence, string, int) { + fs := flag.NewFlagSet(command, flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + fromBundle string + cleanupSummary string + namespace string + masterAddr string + masterAPIAddr string + out string + outDir string + productRevision string + claimProfile string + requiredFrontier requiredFrontierFlags + timeout time.Duration + ) + fs.StringVar(&fromBundle, "from-bundle", "", "existing inventory/support bundle directory to explain") + fs.StringVar(&cleanupSummary, "cleanup-summary", "", "cleanup-summary.txt evidence to project into delete-safety status") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace for live read-only inventory") + fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address for live per-replica status evidence") + fs.StringVar(&masterAPIAddr, "master-api", "", "optional blockmaster gRPC address for ClusterEvidenceService read-only snapshot") + fs.StringVar(&out, "o", "text", "output format: text or json") + fs.StringVar(&outDir, "out", "", "optional directory for nested live status evidence") + fs.StringVar(&productRevision, "product-revision", "", "product revision label for live evidence") + fs.StringVar(&claimProfile, "claim-profile", "", "promotion-readiness claim profile for live evidence") + fs.Var(&requiredFrontier, "required-frontier", "required frontier as volume_id=lsn; repeat for multiple volumes") + fs.DurationVar(&timeout, "timeout", 5*time.Second, "live collection timeout") + if err := fs.Parse(args); err != nil { + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "%s: unexpected args %s\n", command, strings.Join(fs.Args(), " ")) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + var ( + cluster ops.ClusterEvidence + err error + ) + if fromBundle != "" { + cluster, err = ops.BuildObservationFromBundle(ops.ObservationBundleOptions{Dir: fromBundle}) + } else if masterAPIAddr != "" { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cluster, err = readMasterClusterEvidence(ctx, masterAPIAddr) + } else { + if productRevision == "" { + productRevision = buildinfo.Version("sw-block") + } + if !ops.PromotionClaimProfileAccepted(claimProfile) { + fmt.Fprintf(stderr, "%s: --claim-profile=%q invalid; want %q, %q, or %q\n", command, claimProfile, ops.PromotionClaimBetaRecovery, ops.PromotionClaimControlledBestEffortDemo, ops.PromotionClaimStage2ISCSIALUAMultipath) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + collector := ops.NewKubernetesVolumeInventoryCollector(ops.KubernetesInventoryConfig{ + Namespace: namespace, + MasterAddr: masterAddr, + StatusBundleRoot: outDir, + ProductRevision: productRevision, + ClaimProfile: claimProfile, + RequiredFrontiers: requiredFrontier.values, + RunCommand: opsInventoryRunCommand, + }) + inventory, collectErr := collector.Collect(ctx) + if collectErr != nil { + inventory.CollectionErrors = append(inventory.CollectionErrors, strings.Split(collectErr.Error(), "\n")...) + } + cluster, err = ops.BuildObservationFromInventory(inventory, "", outDir) + } + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", command, err) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + cluster, err = applyCleanupSummaryProjection(namespace, cleanupSummary, cluster) + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", command, err) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + cluster, err = enrichLiveObservationCluster(namespace, timeout, fromBundle == "", cluster) + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", command, err) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + return ops.NormalizeObservationCluster(cluster), out, ops.VolumeStatusExitOK +} + +func enrichLiveObservationCluster(namespace string, timeout time.Duration, live bool, cluster ops.ClusterEvidence) (ops.ClusterEvidence, error) { + if !live || os.Getenv("KUBERNETES_SERVICE_HOST") == "" { + return cluster, nil + } + enricher, err := opsNodeEvidenceEnricherFactory() + if err != nil { + return cluster, err + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cluster, err = enricher.EnrichNodeEvidence(ctx, liveNodeEvidenceNamespace(namespace), cluster) + if err != nil { + return cluster, fmt.Errorf("enrich node evidence: %w", err) + } + return cluster, nil +} + +func applyCleanupSummaryProjection(namespace, cleanupSummary string, cluster ops.ClusterEvidence) (ops.ClusterEvidence, error) { + if cleanupSummary == "" { + return cluster, nil + } + cleanup, err := ops.LoadCleanupEvidenceSummary(cleanupSummary) + if err != nil { + return ops.ClusterEvidence{}, err + } + cluster.Cleanup = cleanup + if os.Getenv("KUBERNETES_SERVICE_HOST") == "" { + return cluster, nil + } + client, err := opsSwBlockVolumeSourceFactory() + if err != nil { + return ops.ClusterEvidence{}, err + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + listNamespace := strings.TrimSpace(namespace) + if listNamespace == "" { + listNamespace = "default" + } + volumes, err := client.ListSwBlockVolumes(ctx, listNamespace) + if err != nil { + return ops.ClusterEvidence{}, err + } + return ops.ProjectSwBlockVolumeDeleteSafety(cluster, volumes), nil +} + +func liveNodeEvidenceNamespace(namespace string) string { + if namespace := strings.TrimSpace(os.Getenv("SW_BLOCK_HELM_NAMESPACE")); namespace != "" { + return namespace + } + if namespace = strings.TrimSpace(namespace); namespace != "" && namespace != "default" { + return namespace + } + return "kube-system" +} + +func readMasterClusterEvidence(ctx context.Context, masterAddr string) (ops.ClusterEvidence, error) { + conn, err := link.DialMasterFromEnv(masterAddr) + if err != nil { + return ops.ClusterEvidence{}, err + } + defer conn.Close() + resp, err := control.NewClusterEvidenceServiceClient(conn).GetClusterStatus(ctx, &control.GetClusterStatusRequest{}) + if err != nil { + return ops.ClusterEvidence{}, err + } + return clusterEvidenceFromWire(resp), nil +} + +func clusterEvidenceFromWire(resp *control.ClusterStatusResponse) ops.ClusterEvidence { + if resp == nil { + return ops.ClusterEvidence{} + } + out := ops.ClusterEvidence{ + SchemaVersion: resp.GetSchemaVersion(), + ProductRevision: resp.GetProductRevision(), + Status: resp.GetStatus(), + Conditions: conditionsFromWire(resp.GetConditions()), + NonClaims: append([]string(nil), resp.GetNonClaims()...), + } + if ts := resp.GetCapturedAt(); ts != nil && ts.IsValid() { + out.CapturedAt = ts.AsTime() + } + for _, node := range resp.GetNodes() { + out.Nodes = append(out.Nodes, nodeEvidenceFromWire(node)) + } + for _, volume := range resp.GetVolumes() { + out.Volumes = append(out.Volumes, volumeEvidenceFromWire(volume)) + } + for _, event := range resp.GetEvents() { + out.Events = append(out.Events, clusterEventFromWire(event)) + } + return out +} + +func nodeEvidenceFromWire(node *control.NodeEvidence) ops.NodeEvidence { + if node == nil { + return ops.NodeEvidence{} + } + out := ops.NodeEvidence{ + NodeName: node.GetNodeName(), + KubernetesNode: node.GetKubernetesNode(), + PhysicalHost: node.GetPhysicalHost(), + InternalIP: node.GetInternalIp(), + FrontendIP: node.GetFrontendIp(), + FrontendNetworkClass: node.GetFrontendNetworkClass(), + Schedulable: node.GetSchedulable(), + Ready: node.GetReady(), + ReplicaCount: int(node.GetReplicaCount()), + RequiredImages: append([]string(nil), node.GetRequiredImages()...), + MissingImages: append([]string(nil), node.GetMissingImages()...), + Conditions: conditionsFromWire(node.GetConditions()), + } + if ts := node.GetLastHeartbeatAt(); ts != nil && ts.IsValid() { + out.LastHeartbeatAt = ts.AsTime() + } + return out +} + +func volumeEvidenceFromWire(volume *control.VolumeEvidence) ops.VolumeEvidence { + if volume == nil { + return ops.VolumeEvidence{} + } + out := ops.VolumeEvidence{ + VolumeID: volume.GetVolumeId(), + Namespace: volume.GetNamespace(), + PVCName: volume.GetPvcName(), + PVName: volume.GetPvName(), + ReplicationFactor: int(volume.GetReplicationFactor()), + AckProfile: volume.GetAckProfile(), + ClaimProfile: volume.GetClaimProfile(), + DesiredReplicas: int(volume.GetDesiredReplicas()), + ObservedReplicas: int(volume.GetObservedReplicas()), + Status: volume.GetStatus(), + Reason: volume.GetReason(), + PrimaryReplica: volume.GetPrimaryReplica(), + PrimaryNode: volume.GetPrimaryNode(), + PublishTarget: volume.GetPublishTarget(), + Epoch: volume.GetEpoch(), + EndpointVersion: volume.GetEndpointVersion(), + Conditions: conditionsFromWire(volume.GetConditions()), + NextActions: append([]string(nil), volume.GetNextActions()...), + SupportBundleHint: volume.GetSupportBundleHint(), + } + for _, replica := range volume.GetReplicas() { + out.Replicas = append(out.Replicas, replicaEvidenceFromWire(replica)) + } + return out +} + +func replicaEvidenceFromWire(replica *control.ReplicaEvidence) ops.ReplicaEvidence { + if replica == nil { + return ops.ReplicaEvidence{} + } + return ops.ReplicaEvidence{ + ReplicaID: replica.GetReplicaId(), + ServerID: replica.GetServerId(), + KubernetesNode: replica.GetKubernetesNode(), + PhysicalHost: replica.GetPhysicalHost(), + Observed: replica.GetObserved(), + Role: replica.GetRole(), + ReplicationRole: replica.GetReplicationRole(), + DurableLatched: replica.GetDurableLatched(), + DurableFrontierKnown: replica.GetDurableFrontierKnown(), + DurableFrontierLSN: replica.GetDurableFrontierLsn(), + CandidateReady: replica.GetCandidateReady(), + CandidateReadyReason: replica.GetCandidateReadyReason(), + FrontendProtocol: replica.GetFrontendProtocol(), + FrontendTransport: replica.GetFrontendTransport(), + FrontendAddr: replica.GetFrontendAddr(), + FrontendNQN: replica.GetFrontendNqn(), + FrontendNSID: replica.GetFrontendNsid(), + StatusAddr: replica.GetStatusAddr(), + StalePrimaryFenced: replica.GetStalePrimaryFenced(), + Conditions: conditionsFromWire(replica.GetConditions()), + SupportBundlePath: replica.GetSupportBundlePath(), + } +} + +func conditionsFromWire(in []*control.ObservationCondition) []ops.ObservationCondition { + out := make([]ops.ObservationCondition, 0, len(in)) + for _, condition := range in { + if condition == nil { + continue + } + out = append(out, ops.ObservationCondition{ + Type: condition.GetType(), + Status: condition.GetStatus(), + Reason: condition.GetReason(), + Severity: condition.GetSeverity(), + Message: condition.GetMessage(), + }) + } + return out +} + +func clusterEventFromWire(event *control.ClusterEvent) ops.ClusterEvent { + if event == nil { + return ops.ClusterEvent{} + } + out := ops.ClusterEvent{ + EventID: event.GetEventId(), + VolumeID: event.GetVolumeId(), + ReplicaID: event.GetReplicaId(), + NodeName: event.GetNodeName(), + Type: event.GetEventType(), + Severity: event.GetSeverity(), + Message: event.GetMessage(), + Reason: event.GetReasonCode(), + OldValue: event.GetOldValue(), + NewValue: event.GetNewValue(), + Epoch: event.GetEpoch(), + EndpointVersion: event.GetEndpointVersion(), + CorrelationID: event.GetCorrelationId(), + EvidenceRef: event.GetEvidenceRef(), + } + if ts := event.GetEventTime(); ts != nil && ts.IsValid() { + out.EventTime = ts.AsTime() + } + return out +} + +func runOpsTimeline(args []string, stdout, stderr io.Writer) int { + cluster, out, code := loadObservationVolume("sw-block ops timeline", args, stderr) + if code != ops.VolumeStatusExitOK { + return code + } + switch out { + case "jsonl": + jsonl, err := ops.RenderClusterEventsJSONL(cluster.Events) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops timeline: %v\n", err) + return ops.VolumeStatusExitInvalid + } + fmt.Fprint(stdout, jsonl) + case "json": + raw, err := ops.MarshalObservationJSON(cluster.Events) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops timeline: %v\n", err) + return ops.VolumeStatusExitInvalid + } + _, _ = stdout.Write(raw) + default: + for _, event := range cluster.Events { + fmt.Fprintf(stdout, "%s severity=%s reason=%s volume=%s replica=%s %s\n", + event.Type, + emptyCLI(event.Severity), + emptyCLI(event.Reason), + emptyCLI(event.VolumeID), + emptyCLI(event.ReplicaID), + event.Message) + } + } + return ops.VolumeStatusExitOK +} + +func runOpsExplain(args []string, stdout, stderr io.Writer) int { + cluster, _, code := loadObservationVolume("sw-block ops explain", args, stderr) + if code != ops.VolumeStatusExitOK { + return code + } + fmt.Fprint(stdout, ops.RenderObservationExplainText(cluster)) + return ops.VolumeStatusExitOK +} + +func runOpsReport(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops report", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + fromBundle string + cleanupSummary string + namespace string + masterAddr string + masterAPIAddr string + outDir string + evidenceOutDir string + productRevision string + claimProfile string + requiredFrontier requiredFrontierFlags + timeout time.Duration + ) + fs.StringVar(&fromBundle, "from-bundle", "", "existing inventory/support bundle directory to render") + fs.StringVar(&cleanupSummary, "cleanup-summary", "", "cleanup-summary.txt evidence to project into delete-safety status") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace for live read-only inventory") + fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address for live per-replica status evidence") + fs.StringVar(&masterAPIAddr, "master-api", "", "optional blockmaster gRPC address for ClusterEvidenceService read-only snapshot") + fs.StringVar(&outDir, "out", "", "directory for index.html, cluster-evidence.json, timeline.jsonl, and summary.txt") + fs.StringVar(&evidenceOutDir, "evidence-out", "", "optional directory for nested live status evidence") + fs.StringVar(&productRevision, "product-revision", "", "product revision label for live evidence") + fs.StringVar(&claimProfile, "claim-profile", "", "promotion-readiness claim profile for live evidence") + fs.Var(&requiredFrontier, "required-frontier", "required frontier as volume_id=lsn; repeat for multiple volumes") + fs.DurationVar(&timeout, "timeout", 5*time.Second, "live collection timeout") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "sw-block ops report: unexpected args %s\n", strings.Join(fs.Args(), " ")) + return ops.VolumeStatusExitInvalid + } + if outDir == "" { + fmt.Fprintln(stderr, "sw-block ops report: --out is required") + return ops.VolumeStatusExitInvalid + } + + var ( + cluster ops.ClusterEvidence + err error + ) + switch { + case fromBundle != "": + cluster, err = ops.BuildObservationFromBundle(ops.ObservationBundleOptions{Dir: fromBundle}) + case masterAPIAddr != "": + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cluster, err = readMasterClusterEvidence(ctx, masterAPIAddr) + default: + if productRevision == "" { + productRevision = buildinfo.Version("sw-block") + } + if !ops.PromotionClaimProfileAccepted(claimProfile) { + fmt.Fprintf(stderr, "sw-block ops report: --claim-profile=%q invalid; want %q, %q, or %q\n", claimProfile, ops.PromotionClaimBetaRecovery, ops.PromotionClaimControlledBestEffortDemo, ops.PromotionClaimStage2ISCSIALUAMultipath) + return ops.VolumeStatusExitInvalid + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + collector := ops.NewKubernetesVolumeInventoryCollector(ops.KubernetesInventoryConfig{ + Namespace: namespace, + MasterAddr: masterAddr, + StatusBundleRoot: evidenceOutDir, + ProductRevision: productRevision, + ClaimProfile: claimProfile, + RequiredFrontiers: requiredFrontier.values, + RunCommand: opsInventoryRunCommand, + }) + inventory, collectErr := collector.Collect(ctx) + if collectErr != nil { + inventory.CollectionErrors = append(inventory.CollectionErrors, strings.Split(collectErr.Error(), "\n")...) + } + cluster, err = ops.BuildObservationFromInventory(inventory, "", evidenceOutDir) + } + if err != nil { + fmt.Fprintf(stderr, "sw-block ops report: %v\n", err) + return ops.VolumeStatusExitInvalid + } + cluster, err = applyCleanupSummaryProjection(namespace, cleanupSummary, cluster) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops report: %v\n", err) + return ops.VolumeStatusExitInvalid + } + cluster, err = enrichLiveObservationCluster(namespace, timeout, fromBundle == "", cluster) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops report: %v\n", err) + return ops.VolumeStatusExitInvalid + } + if err := ops.WriteObservationReportArtifacts(outDir, cluster); err != nil { + fmt.Fprintf(stderr, "sw-block ops report: %v\n", err) + return ops.VolumeStatusExitInvalid + } + fmt.Fprintf(stdout, "report_status=ok\n") + fmt.Fprintf(stdout, "report_dir=%s\n", outDir) + fmt.Fprintf(stdout, "html=%s\n", ops.ObservationReportHTMLArtifact) + fmt.Fprintf(stdout, "cluster_evidence=%s\n", ops.ObservationReportJSONArtifact) + fmt.Fprintf(stdout, "timeline=%s\n", ops.ObservationReportJSONLArtifact) + fmt.Fprintf(stdout, "operator_snapshot=%s\n", ops.ObservationOperatorSnapshotArtifact) + fmt.Fprintf(stdout, "summary=%s\n", ops.ObservationReportTextArtifact) + fmt.Fprintf(stdout, "read_only=true\n") + return ops.VolumeStatusExitOK +} + +func runOpsDashboard(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops dashboard", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + fromBundle string + cleanupSummary string + namespace string + masterAddr string + masterAPIAddr string + evidenceOutDir string + productRevision string + claimProfile string + listenAddr string + requiredFrontier requiredFrontierFlags + timeout time.Duration + serveDuration time.Duration + ) + fs.StringVar(&fromBundle, "from-bundle", "", "existing inventory/support bundle directory to serve") + fs.StringVar(&cleanupSummary, "cleanup-summary", "", "cleanup-summary.txt evidence to project into delete-safety status") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace for live read-only inventory") + fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address for live per-replica status evidence") + fs.StringVar(&masterAPIAddr, "master-api", "", "optional blockmaster gRPC address for ClusterEvidenceService read-only snapshot") + fs.StringVar(&evidenceOutDir, "evidence-out", "", "optional directory for nested live status evidence") + fs.StringVar(&productRevision, "product-revision", "", "product revision label for live evidence") + fs.StringVar(&claimProfile, "claim-profile", "", "promotion-readiness claim profile for live evidence") + fs.StringVar(&listenAddr, "listen", "127.0.0.1:9334", "dashboard listen address; keep loopback for alpha") + fs.Var(&requiredFrontier, "required-frontier", "required frontier as volume_id=lsn; repeat for multiple volumes") + fs.DurationVar(&timeout, "timeout", 5*time.Second, "live collection timeout") + fs.DurationVar(&serveDuration, "serve-duration", 0, "optional test duration; 0 serves until interrupted") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "sw-block ops dashboard: unexpected args %s\n", strings.Join(fs.Args(), " ")) + return ops.VolumeStatusExitInvalid + } + + cluster, err := loadDashboardCluster(dashboardClusterOptions{ + FromBundle: fromBundle, + CleanupSummary: cleanupSummary, + Namespace: namespace, + MasterAddr: masterAddr, + MasterAPIAddr: masterAPIAddr, + EvidenceOutDir: evidenceOutDir, + ProductRevision: productRevision, + ClaimProfile: claimProfile, + RequiredFrontiers: requiredFrontier.values, + Timeout: timeout, + }) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops dashboard: %v\n", err) + return ops.VolumeStatusExitInvalid + } + + ln, err := net.Listen("tcp", listenAddr) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops dashboard: listen %s: %v\n", listenAddr, err) + return ops.VolumeStatusExitInvalid + } + defer ln.Close() + + server := &http.Server{ + Handler: ops.NewObservationDashboardHandler(cluster), + ReadHeaderTimeout: 5 * time.Second, + } + errCh := make(chan error, 1) + go func() { + errCh <- server.Serve(ln) + }() + fmt.Fprintf(stdout, "dashboard_status=ok\n") + fmt.Fprintf(stdout, "url=http://%s/\n", ln.Addr().String()) + fmt.Fprintf(stdout, "cluster_evidence=%s\n", ops.ObservationReportJSONArtifact) + fmt.Fprintf(stdout, "timeline=%s\n", ops.ObservationReportJSONLArtifact) + fmt.Fprintf(stdout, "operator_snapshot=%s\n", ops.ObservationOperatorSnapshotArtifact) + fmt.Fprintf(stdout, "summary=%s\n", ops.ObservationReportTextArtifact) + fmt.Fprintf(stdout, "read_only=true\n") + + if serveDuration > 0 { + timer := time.NewTimer(serveDuration) + defer timer.Stop() + select { + case err := <-errCh: + if err != nil && err != http.ErrServerClosed { + fmt.Fprintf(stderr, "sw-block ops dashboard: %v\n", err) + return ops.VolumeStatusExitInvalid + } + return ops.VolumeStatusExitOK + case <-timer.C: + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + if err := server.Shutdown(ctx); err != nil { + fmt.Fprintf(stderr, "sw-block ops dashboard: shutdown: %v\n", err) + return ops.VolumeStatusExitInvalid + } + if err := <-errCh; err != nil && err != http.ErrServerClosed { + fmt.Fprintf(stderr, "sw-block ops dashboard: %v\n", err) + return ops.VolumeStatusExitInvalid + } + return ops.VolumeStatusExitOK + } + } + + if err := <-errCh; err != nil && err != http.ErrServerClosed { + fmt.Fprintf(stderr, "sw-block ops dashboard: %v\n", err) + return ops.VolumeStatusExitInvalid + } + return ops.VolumeStatusExitOK +} + +type dashboardClusterOptions struct { + FromBundle string + CleanupSummary string + Namespace string + MasterAddr string + MasterAPIAddr string + EvidenceOutDir string + ProductRevision string + ClaimProfile string + RequiredFrontiers map[string]uint64 + Timeout time.Duration +} + +func loadDashboardCluster(options dashboardClusterOptions) (ops.ClusterEvidence, error) { + var ( + cluster ops.ClusterEvidence + err error + live bool + ) + switch { + case options.FromBundle != "": + cluster, err = ops.BuildObservationFromBundle(ops.ObservationBundleOptions{Dir: options.FromBundle}) + case options.MasterAPIAddr != "": + ctx, cancel := context.WithTimeout(context.Background(), options.Timeout) + defer cancel() + cluster, err = readMasterClusterEvidence(ctx, options.MasterAPIAddr) + live = true + default: + productRevision := options.ProductRevision + if productRevision == "" { + productRevision = buildinfo.Version("sw-block") + } + if !ops.PromotionClaimProfileAccepted(options.ClaimProfile) { + return ops.ClusterEvidence{}, fmt.Errorf("--claim-profile=%q invalid; want %q, %q, or %q", options.ClaimProfile, ops.PromotionClaimBetaRecovery, ops.PromotionClaimControlledBestEffortDemo, ops.PromotionClaimStage2ISCSIALUAMultipath) + } + ctx, cancel := context.WithTimeout(context.Background(), options.Timeout) + defer cancel() + collector := ops.NewKubernetesVolumeInventoryCollector(ops.KubernetesInventoryConfig{ + Namespace: options.Namespace, + MasterAddr: options.MasterAddr, + StatusBundleRoot: options.EvidenceOutDir, + ProductRevision: productRevision, + ClaimProfile: options.ClaimProfile, + RequiredFrontiers: options.RequiredFrontiers, + RunCommand: opsInventoryRunCommand, + }) + inventory, collectErr := collector.Collect(ctx) + if collectErr != nil { + inventory.CollectionErrors = append(inventory.CollectionErrors, strings.Split(collectErr.Error(), "\n")...) + } + cluster, err = ops.BuildObservationFromInventory(inventory, "", options.EvidenceOutDir) + live = true + } + if err != nil { + return ops.ClusterEvidence{}, err + } + cluster, err = applyCleanupSummaryProjection(options.Namespace, options.CleanupSummary, cluster) + if err != nil { + return ops.ClusterEvidence{}, err + } + return enrichLiveObservationCluster(options.Namespace, options.Timeout, live, cluster) +} + +type helmValuesFile struct { + Image helmValuesImage `yaml:"image"` + CSIImage helmValuesImage `yaml:"csiImage"` + AppNamespace string `yaml:"appNamespace"` + Blockmaster *helmValuesBlockmaster `yaml:"blockmaster,omitempty"` + StorageClass helmValuesStorageClass `yaml:"storageClass"` + Replication helmValuesReplication `yaml:"replication"` + Network helmValuesNetwork `yaml:"network"` + Restart *helmValuesRestart `yaml:"restartPersistence,omitempty"` + Compat helmValuesCompat `yaml:"compat"` + CHAP helmValuesCHAP `yaml:"chap"` + Stage2Multipath helmValuesEnabled `yaml:"stage2Multipath"` + BlockNodes []helmValuesBlockNode `yaml:"blockNodes"` +} + +type helmValuesImage struct { + Repository string `yaml:"repository"` + Tag string `yaml:"tag"` + Digest string `yaml:"digest"` +} + +type helmValuesBlockmaster struct { + StateHostPath string `yaml:"stateHostPath,omitempty"` +} + +type helmValuesRestart struct { + Mode string `yaml:"mode,omitempty"` + StateHostPath string `yaml:"stateHostPath,omitempty"` +} + +type helmValuesStorageClass struct { + Create bool `yaml:"create"` + Name string `yaml:"name"` + ReplicationFactor int `yaml:"replicationFactor"` + Protocol string `yaml:"protocol"` + NVMeTransport string `yaml:"nvmeTransport"` +} + +type helmValuesReplication struct { + AckProfile string `yaml:"ackProfile"` + ExpectedSlotsPerVolume int `yaml:"expectedSlotsPerVolume"` +} + +type helmValuesNetwork struct { + ExternalISCSI bool `yaml:"externalISCSI"` + ExternalNVMe bool `yaml:"externalNVMe"` + ExternalStatus bool `yaml:"externalStatus"` + RejectLoopbackPublishTargets bool `yaml:"rejectLoopbackPublishTargets"` +} + +type helmValuesCompat struct { + LauncherDurableImplFlag bool `yaml:"launcherDurableImplFlag"` + LauncherReplicationAckFlag bool `yaml:"launcherReplicationAckFlag"` + LauncherRejectLoopbackFlag bool `yaml:"launcherRejectLoopbackFlag"` +} + +type helmValuesCHAP struct { + Enabled bool `yaml:"enabled"` + Create bool `yaml:"create"` + SecretName string `yaml:"secretName"` + Username string `yaml:"username"` + Secret string `yaml:"secret"` +} + +type helmValuesEnabled struct { + Enabled bool `yaml:"enabled"` +} + +type helmValuesBlockNode struct { + Name string `yaml:"name"` + KubernetesNode string `yaml:"kubernetesNode"` + InternalIP string `yaml:"internalIP"` + ManagementIP string `yaml:"managementIP,omitempty"` + FrontendIP string `yaml:"frontendIP,omitempty"` + FrontendNetworkClass string `yaml:"frontendNetworkClass,omitempty"` + DataPort int `yaml:"dataPort"` + ControlPort int `yaml:"controlPort"` + Pool string `yaml:"pool"` +} + +type kubernetesReadyNode struct { + Name string + InternalIP string +} + +func runOpsGenerateHelmValues(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops generate-helm-values", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + outPath string + kubeconfig string + image string + csiImage string + replicationFactor int + ackProfile string + storageClass string + protocol string + nvmeTransport string + appNamespace string + targetNode string + nodeLimit int + chapSecretName string + chapUsername string + chapSecret string + stage2Multipath bool + restartPersistence string + stateHostPath string + frontendIPMapRaw string + frontendClass string + timeout time.Duration + ) + fs.StringVar(&outPath, "out", "", "output Helm values.yaml path") + fs.StringVar(&outPath, "o", "", "output Helm values.yaml path") + fs.StringVar(&kubeconfig, "kubeconfig", "", "optional kubeconfig path passed to kubectl") + fs.StringVar(&image, "image", "ghcr.io/seaweedfs/seaweed-block:alpha", "sw-block image reference") + fs.StringVar(&csiImage, "csi-image", "ghcr.io/seaweedfs/seaweed-block-csi:alpha", "sw-block CSI image reference") + fs.IntVar(&replicationFactor, "replication-factor", 1, "storage class replication factor") + fs.StringVar(&ackProfile, "ack-profile", "best-effort", "replication ACK profile: best-effort, sync-quorum, or sync-all") + fs.StringVar(&storageClass, "storageclass", "sw-block-dynamic", "StorageClass name") + fs.StringVar(&protocol, "protocol", "iscsi", "StorageClass frontend protocol: iscsi or nvme") + fs.StringVar(&nvmeTransport, "nvme-transport", "tcp", "NVMe fabric transport: tcp or rdma") + fs.StringVar(&appNamespace, "app-namespace", "default", "default application namespace") + fs.StringVar(&targetNode, "target-node", "", "optional Kubernetes node name to select for single-node values") + fs.IntVar(&nodeLimit, "node-limit", 0, "optional maximum selected Ready node count") + fs.StringVar(&chapSecretName, "chap-secret-name", "sw-block-iscsi-chap", "iSCSI CHAP Secret name") + fs.StringVar(&chapUsername, "chap-username", "sw-block", "iSCSI CHAP username") + fs.StringVar(&chapSecret, "chap-secret", "", "iSCSI CHAP shared secret; generated when needed and omitted") + fs.BoolVar(&stage2Multipath, "stage2-multipath", false, "enable Stage 2 multipath chart values") + fs.StringVar(&restartPersistence, "restart-persistence", "ephemeral", "restart persistence mode: ephemeral or hostpath") + fs.StringVar(&stateHostPath, "state-hostpath", "/var/lib/sw-block", "hostPath base used when --restart-persistence=hostpath") + fs.StringVar(&frontendIPMapRaw, "frontend-ip-map", "", "optional comma-separated Kubernetes node to frontend/data-plane IP map, for example m01=10.0.0.181,m02=10.0.0.184") + fs.StringVar(&frontendClass, "frontend-network-class", "", "network class for --frontend-ip-map values: management_lan, 100gbe_tcp, or 100gbe_roce") + fs.DurationVar(&timeout, "timeout", 10*time.Second, "kubectl discovery timeout") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if fs.NArg() != 0 { + fmt.Fprintf(stderr, "sw-block ops generate-helm-values: unexpected args %s\n", strings.Join(fs.Args(), " ")) + return ops.VolumeStatusExitInvalid + } + if outPath == "" { + fmt.Fprintln(stderr, "sw-block ops generate-helm-values: --out is required") + return ops.VolumeStatusExitInvalid + } + if replicationFactor < 1 { + fmt.Fprintln(stderr, "sw-block ops generate-helm-values: --replication-factor must be >= 1") + return ops.VolumeStatusExitInvalid + } + if !helmValuesAckProfileAccepted(ackProfile) { + fmt.Fprintf(stderr, "sw-block ops generate-helm-values: --ack-profile=%q invalid; want best-effort, sync-quorum, or sync-all\n", ackProfile) + return ops.VolumeStatusExitInvalid + } + if !helmValuesProtocolAccepted(protocol) { + fmt.Fprintf(stderr, "sw-block ops generate-helm-values: --protocol=%q invalid; want iscsi or nvme\n", protocol) + return ops.VolumeStatusExitInvalid + } + if !helmValuesNVMeTransportAccepted(nvmeTransport) { + fmt.Fprintf(stderr, "sw-block ops generate-helm-values: --nvme-transport=%q invalid; want tcp or rdma\n", nvmeTransport) + return ops.VolumeStatusExitInvalid + } + if protocol != "nvme" && nvmeTransport != "tcp" { + fmt.Fprintln(stderr, "sw-block ops generate-helm-values: --nvme-transport=rdma requires --protocol=nvme") + return ops.VolumeStatusExitInvalid + } + if !helmValuesRestartPersistenceAccepted(restartPersistence) { + fmt.Fprintf(stderr, "sw-block ops generate-helm-values: --restart-persistence=%q invalid; want ephemeral or hostpath\n", restartPersistence) + return ops.VolumeStatusExitInvalid + } + if restartPersistence == "hostpath" && strings.TrimSpace(stateHostPath) == "" { + fmt.Fprintln(stderr, "sw-block ops generate-helm-values: --state-hostpath is required when --restart-persistence=hostpath") + return ops.VolumeStatusExitInvalid + } + frontendIPMap, err := parseHelmValuesNodeIPMap(frontendIPMapRaw) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops generate-helm-values: %v\n", err) + return ops.VolumeStatusExitInvalid + } + if len(frontendIPMap) > 0 { + if strings.TrimSpace(frontendClass) == "" { + fmt.Fprintln(stderr, "sw-block ops generate-helm-values: --frontend-network-class is required when --frontend-ip-map is set") + return ops.VolumeStatusExitInvalid + } + if !helmValuesFrontendNetworkClassAccepted(frontendClass) { + fmt.Fprintf(stderr, "sw-block ops generate-helm-values: --frontend-network-class=%q invalid; want management_lan, 100gbe_tcp, or 100gbe_roce\n", frontendClass) + return ops.VolumeStatusExitInvalid + } + } else if strings.TrimSpace(frontendClass) != "" { + fmt.Fprintln(stderr, "sw-block ops generate-helm-values: --frontend-network-class requires --frontend-ip-map") + return ops.VolumeStatusExitInvalid + } + if nvmeTransport == "rdma" && (len(frontendIPMap) == 0 || frontendClass != "100gbe_roce") { + fmt.Fprintln(stderr, "sw-block ops generate-helm-values: NVMe/RDMA requires --frontend-ip-map and --frontend-network-class=100gbe_roce") + return ops.VolumeStatusExitInvalid + } + + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + kubectlArgs := []string{} + if kubeconfig != "" { + kubectlArgs = append(kubectlArgs, "--kubeconfig", kubeconfig) + } + kubectlArgs = append(kubectlArgs, "get", "nodes", "-o", "wide", "--no-headers") + rawNodes, err := opsGenerateHelmValuesRunCommand(ctx, "kubectl", kubectlArgs...) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops generate-helm-values: kubectl node discovery failed: %v\n%s", err, rawNodes) + return ops.VolumeStatusExitInvalid + } + discovered, selected, err := selectHelmValuesNodes(string(rawNodes), targetNode, nodeLimit) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops generate-helm-values: %v\n", err) + return ops.VolumeStatusExitInvalid + } + if replicationFactor > len(selected) { + fmt.Fprintf(stderr, "sw-block ops generate-helm-values: --replication-factor=%d requires at least %d selected Ready nodes; selected=%d\n", replicationFactor, replicationFactor, len(selected)) + return ops.VolumeStatusExitInvalid + } + + multiNode := len(selected) > 1 + externalISCSI := multiNode && protocol == "iscsi" + externalNVMe := protocol == "nvme" && (multiNode || nvmeTransport == "rdma") + if externalISCSI && chapSecret == "" { + chapSecret = generateHelmValuesSecret() + } + values := helmValuesFile{ + Image: parseHelmValuesImage(image), + CSIImage: parseHelmValuesImage(csiImage), + AppNamespace: appNamespace, + StorageClass: helmValuesStorageClass{ + Create: true, + Name: storageClass, + ReplicationFactor: replicationFactor, + Protocol: protocol, + NVMeTransport: nvmeTransport, + }, + Replication: helmValuesReplication{ + AckProfile: ackProfile, + ExpectedSlotsPerVolume: replicationFactor, + }, + Network: helmValuesNetwork{ + ExternalISCSI: externalISCSI, + ExternalNVMe: externalNVMe, + ExternalStatus: false, // blockmaster runs with mutual TLS: volume status stays on loopback + RejectLoopbackPublishTargets: multiNode || nvmeTransport == "rdma", + }, + Compat: helmValuesCompat{ + LauncherRejectLoopbackFlag: false, + }, + CHAP: helmValuesCHAP{ + Enabled: externalISCSI, + Create: externalISCSI, + SecretName: chapSecretName, + Username: chapUsername, + Secret: chapSecret, + }, + Stage2Multipath: helmValuesEnabled{Enabled: stage2Multipath}, + BlockNodes: make([]helmValuesBlockNode, 0, len(selected)), + } + values.Restart = &helmValuesRestart{Mode: restartPersistence} + if restartPersistence == "hostpath" { + values.Blockmaster = &helmValuesBlockmaster{StateHostPath: stateHostPath} + values.Restart.StateHostPath = stateHostPath + } + for i, node := range selected { + ip := node.InternalIP + if !multiNode { + ip = "127.0.0.1" + } + frontendIP := "" + if len(frontendIPMap) > 0 { + var ok bool + frontendIP, ok = frontendIPMap[node.Name] + if !ok { + fmt.Fprintf(stderr, "sw-block ops generate-helm-values: --frontend-ip-map missing selected node %q\n", node.Name) + return ops.VolumeStatusExitInvalid + } + } + values.BlockNodes = append(values.BlockNodes, helmValuesBlockNode{ + Name: node.Name, + KubernetesNode: node.Name, + InternalIP: ip, + ManagementIP: node.InternalIP, + FrontendIP: frontendIP, + FrontendNetworkClass: frontendClass, + DataPort: 19101 + (i * 2), + ControlPort: 19102 + (i * 2), + Pool: "default", + }) + } + rawValues, err := yaml.Marshal(values) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops generate-helm-values: marshal values: %v\n", err) + return ops.VolumeStatusExitInvalid + } + if dir := filepath.Dir(outPath); dir != "." && dir != "" { + if err := os.MkdirAll(dir, 0o755); err != nil { + fmt.Fprintf(stderr, "sw-block ops generate-helm-values: create output dir: %v\n", err) + return ops.VolumeStatusExitInvalid + } + } + if err := os.WriteFile(outPath, rawValues, 0o600); err != nil { + fmt.Fprintf(stderr, "sw-block ops generate-helm-values: write %s: %v\n", outPath, err) + return ops.VolumeStatusExitInvalid + } + + networkMode := "loopback" + if externalISCSI { + networkMode = "external-iscsi" + } else if externalNVMe { + networkMode = "external-nvme" + } + fmt.Fprintln(stdout, "helm_values_status=ok") + fmt.Fprintf(stdout, "values_file=%s\n", outPath) + fmt.Fprintf(stdout, "network_mode=%s\n", networkMode) + fmt.Fprintf(stdout, "ready_kubernetes_nodes=%d\n", len(selected)) + fmt.Fprintf(stdout, "discovered_kubernetes_nodes=%d\n", len(discovered)) + fmt.Fprintf(stdout, "target_node=%s\n", emptyCLI(targetNode)) + fmt.Fprintf(stdout, "node_limit=%s\n", emptyCLI(strconv.Itoa(nodeLimit))) + fmt.Fprintf(stdout, "external_iscsi=%t\n", externalISCSI) + fmt.Fprintf(stdout, "external_nvme=%t\n", externalNVMe) + fmt.Fprintf(stdout, "frontend_ip_map=%s\n", emptyCLI(frontendIPMapRaw)) + fmt.Fprintf(stdout, "frontend_network_class=%s\n", emptyCLI(frontendClass)) + fmt.Fprintf(stdout, "chap_enabled=%t\n", externalISCSI) + fmt.Fprintf(stdout, "protocol=%s\n", protocol) + fmt.Fprintf(stdout, "nvme_transport=%s\n", nvmeTransport) + fmt.Fprintf(stdout, "replication_factor=%d\n", replicationFactor) + fmt.Fprintf(stdout, "ack_profile=%s\n", ackProfile) + fmt.Fprintf(stdout, "restart_persistence_mode=%s\n", restartPersistence) + if restartPersistence == "hostpath" { + fmt.Fprintf(stdout, "state_hostpath=%s\n", stateHostPath) + } + return ops.VolumeStatusExitOK +} + +func helmValuesAckProfileAccepted(value string) bool { + switch value { + case "best-effort", "sync-quorum", "sync-all": + return true + default: + return false + } +} + +func helmValuesProtocolAccepted(value string) bool { + switch value { + case "iscsi", "nvme": + return true + default: + return false + } +} + +func helmValuesNVMeTransportAccepted(value string) bool { + return value == "tcp" || value == "rdma" +} + +func helmValuesRestartPersistenceAccepted(value string) bool { + switch value { + case "ephemeral", "hostpath": + return true + default: + return false + } +} + +func helmValuesFrontendNetworkClassAccepted(value string) bool { + switch value { + case "management_lan", "100gbe_tcp", "100gbe_roce": + return true + default: + return false + } +} + +func parseHelmValuesNodeIPMap(raw string) (map[string]string, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return nil, nil + } + out := map[string]string{} + for _, part := range strings.Split(raw, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + node, ip, ok := strings.Cut(part, "=") + node = strings.TrimSpace(node) + ip = strings.TrimSpace(ip) + if !ok || node == "" || ip == "" { + return nil, fmt.Errorf("--frontend-ip-map entry %q must be node=ip", part) + } + if helmValuesIPUnsafe(ip) { + return nil, fmt.Errorf("--frontend-ip-map node %q has unsafe IP %q", node, ip) + } + if _, exists := out[node]; exists { + return nil, fmt.Errorf("--frontend-ip-map duplicates node %q", node) + } + out[node] = ip + } + if len(out) == 0 { + return nil, nil + } + return out, nil +} + +func selectHelmValuesNodes(raw, targetNode string, nodeLimit int) ([]kubernetesReadyNode, []kubernetesReadyNode, error) { + discovered := parseKubectlWideReadyNodes(raw) + if len(discovered) == 0 { + return nil, nil, fmt.Errorf("no Ready schedulable Kubernetes nodes with non-loopback InternalIP found") + } + selected := make([]kubernetesReadyNode, 0, len(discovered)) + for _, node := range discovered { + if targetNode != "" && node.Name != targetNode { + continue + } + selected = append(selected, node) + } + if targetNode != "" && len(selected) == 0 { + return discovered, nil, fmt.Errorf("--target-node=%q is not a Ready schedulable node with non-loopback InternalIP", targetNode) + } + if nodeLimit > 0 && len(selected) > nodeLimit { + selected = selected[:nodeLimit] + } + if len(selected) == 0 { + return discovered, nil, fmt.Errorf("no Kubernetes nodes selected") + } + return discovered, selected, nil +} + +func parseKubectlWideReadyNodes(raw string) []kubernetesReadyNode { + var nodes []kubernetesReadyNode + for _, line := range strings.Split(raw, "\n") { + fields := strings.Fields(line) + if len(fields) < 6 { + continue + } + status := fields[1] + internalIP := fields[5] + if !kubectlNodeStatusReadySchedulable(status) || helmValuesIPUnsafe(internalIP) { + continue + } + nodes = append(nodes, kubernetesReadyNode{ + Name: fields[0], + InternalIP: internalIP, + }) + } + return nodes +} + +func kubectlNodeStatusReadySchedulable(status string) bool { + ready := false + for _, part := range strings.Split(status, ",") { + switch strings.TrimSpace(part) { + case "Ready": + ready = true + case "SchedulingDisabled": + return false + } + } + return ready +} + +func helmValuesIPUnsafe(ip string) bool { + return ip == "" || ip == "" || ip == "0.0.0.0" || ip == "::1" || strings.HasPrefix(ip, "127.") +} + +func parseHelmValuesImage(ref string) helmValuesImage { + repository := ref + tag := "latest" + digest := "" + if before, after, ok := strings.Cut(ref, "@"); ok { + repository = before + digest = after + } + lastSlash := strings.LastIndex(repository, "/") + lastColon := strings.LastIndex(repository, ":") + if lastColon > lastSlash { + tag = repository[lastColon+1:] + repository = repository[:lastColon] + } + return helmValuesImage{Repository: repository, Tag: tag, Digest: digest} +} + +func generateHelmValuesSecret() string { + var b [18]byte + if _, err := rand.Read(b[:]); err != nil { + return fmt.Sprintf("sw-block-%d", time.Now().UnixNano()) + } + return "sw-block-" + hex.EncodeToString(b[:]) +} + +func loadObservationVolume(command string, args []string, stderr io.Writer) (ops.ClusterEvidence, string, int) { + if len(args) == 0 || args[0] != "volume" { + fmt.Fprintf(stderr, "%s: expected volume [--from-bundle |--namespace ] \n", command) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + fs := flag.NewFlagSet(command+" volume", flag.ContinueOnError) + fs.SetOutput(stderr) + var ( + fromBundle string + cleanupSummary string + namespace string + masterAddr string + out string + outDir string + productRevision string + claimProfile string + requiredFrontier requiredFrontierFlags + timeout time.Duration + ) + fs.StringVar(&fromBundle, "from-bundle", "", "existing inventory/support bundle directory to explain") + fs.StringVar(&cleanupSummary, "cleanup-summary", "", "cleanup-summary.txt evidence to project into delete-safety status") + fs.StringVar(&namespace, "namespace", "default", "Kubernetes namespace for live read-only inventory") + fs.StringVar(&masterAddr, "master", "", "optional blockmaster gRPC address for live per-replica status evidence") + fs.StringVar(&out, "o", "text", "output format: text, json, or jsonl where supported") + fs.StringVar(&outDir, "out", "", "optional directory for nested live status evidence") + fs.StringVar(&productRevision, "product-revision", "", "product revision label for live evidence") + fs.StringVar(&claimProfile, "claim-profile", "", "promotion-readiness claim profile for live evidence") + fs.Var(&requiredFrontier, "required-frontier", "required frontier as volume_id=lsn; repeat for multiple volumes") + fs.DurationVar(&timeout, "timeout", 5*time.Second, "live collection timeout") + if err := fs.Parse(normalizeObservationVolumeArgs(args[1:])); err != nil { + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + remaining := fs.Args() + if len(remaining) != 1 { + fmt.Fprintf(stderr, "%s: is required\n", command) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + volumeID := remaining[0] + var ( + cluster ops.ClusterEvidence + err error + ) + if fromBundle != "" { + cluster, err = ops.BuildObservationFromBundle(ops.ObservationBundleOptions{ + Dir: fromBundle, + VolumeID: volumeID, + }) + } else { + if productRevision == "" { + productRevision = buildinfo.Version("sw-block") + } + if !ops.PromotionClaimProfileAccepted(claimProfile) { + fmt.Fprintf(stderr, "%s: --claim-profile=%q invalid; want %q, %q, or %q\n", command, claimProfile, ops.PromotionClaimBetaRecovery, ops.PromotionClaimControlledBestEffortDemo, ops.PromotionClaimStage2ISCSIALUAMultipath) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + collector := ops.NewKubernetesVolumeInventoryCollector(ops.KubernetesInventoryConfig{ + Namespace: namespace, + MasterAddr: masterAddr, + StatusBundleRoot: outDir, + ProductRevision: productRevision, + ClaimProfile: claimProfile, + RequiredFrontiers: requiredFrontier.values, + RunCommand: opsInventoryRunCommand, + }) + inventory, collectErr := collector.Collect(ctx) + if collectErr != nil { + inventory.CollectionErrors = append(inventory.CollectionErrors, strings.Split(collectErr.Error(), "\n")...) + } + cluster, err = ops.BuildObservationFromInventory(inventory, volumeID, outDir) + if err != nil && cleanupSummary != "" && strings.Contains(err.Error(), "not found in inventory") { + cluster, err = ops.BuildObservationFromInventory(inventory, "", outDir) + } + } + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", command, err) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + cluster, err = applyCleanupSummaryProjection(namespace, cleanupSummary, cluster) + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", command, err) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + cluster, err = enrichLiveObservationCluster(namespace, timeout, fromBundle == "", cluster) + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", command, err) + return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid + } + return cluster, out, ops.VolumeStatusExitOK +} + +func normalizeObservationVolumeArgs(args []string) []string { + valueFlags := map[string]bool{ + "--from-bundle": true, + "--cleanup-summary": true, + "--namespace": true, + "--master": true, + "--out": true, + "-o": true, + "--product-revision": true, + "--claim-profile": true, + "--required-frontier": true, + "--timeout": true, + } + var volumeID string + out := make([]string, 0, len(args)) + for i := 0; i < len(args); i++ { + arg := args[i] + if valueFlags[arg] { + out = append(out, arg) + if i+1 < len(args) { + i++ + out = append(out, args[i]) + } + continue + } + if strings.HasPrefix(arg, "-") { + out = append(out, arg) + continue + } + if volumeID == "" { + volumeID = arg + continue + } + out = append(out, arg) + } + if volumeID != "" { + out = append(out, volumeID) + } + return out +} + +func usage(w io.Writer) { + fmt.Fprintln(w, "usage:") + fmt.Fprintln(w, " sw-block --version") + fmt.Fprintln(w, " sw-block shell -master [-filer ] [-chunkPath ] [-c ]") + fmt.Fprintln(w, " sw-block ops status --volume --master --status-addr --out ") + fmt.Fprintln(w, " sw-block ops inventory --namespace [--master ] --out ") + fmt.Fprintln(w, " sw-block ops cluster --namespace [--master |--master-api ] [-o json]") + fmt.Fprintln(w, " sw-block ops volumes --namespace [--master ] [-o json]") + fmt.Fprintln(w, " sw-block ops describe volume --from-bundle [-o json]") + fmt.Fprintln(w, " sw-block ops describe volume --namespace [--master ] [--out ]") + fmt.Fprintln(w, " sw-block ops timeline volume --from-bundle [-o jsonl]") + fmt.Fprintln(w, " sw-block ops explain volume --from-bundle ") + fmt.Fprintln(w, " sw-block ops explain volume --namespace [--master ] [--out ]") + fmt.Fprintln(w, " sw-block ops report --from-bundle --out ") + fmt.Fprintln(w, " sw-block ops report --master-api --out ") + fmt.Fprintln(w, " sw-block ops dashboard --from-bundle [--listen 127.0.0.1:9334]") + fmt.Fprintln(w, " sw-block ops dashboard --master-api [--listen 127.0.0.1:9334]") + fmt.Fprintln(w, " sw-block ops generate-helm-values --out values.yaml [--target-node ] [--replication-factor ] [--protocol iscsi|nvme] [--nvme-transport tcp|rdma]") + fmt.Fprintln(w, " [--restart-persistence ephemeral|hostpath] [--state-hostpath /var/lib/sw-block] [--timeout 10s]") + fmt.Fprintln(w, " sw-block ops operator-status --dry-run [--master-api |--from-bundle ] [--cleanup-summary ] [--interval 30s]") + fmt.Fprintln(w, " sw-block ops lifecycle-owner [--dry-run] [--namespace ] [--interval 30s]") + fmt.Fprintln(w, " sw-block ops authority-executor [--namespace ] [--allowed-mutation-class ack_eligibility|rebuild_traffic] [--interval 30s]") + fmt.Fprintln(w, " sw-block ops rebuild-target-owner [--dry-run] [--namespace ] [--interval 30s]") + fmt.Fprintln(w, " sw-block ops failback-target-owner [--dry-run] [--namespace ] [--interval 30s] [--activate-targets --activation-policy --runtime-endpoint ]") + fmt.Fprintln(w, " sw-block ops failback-executor [--dry-run] [--namespace ] [--enable-execution] [--execution-policy] [--failback-runtime-url ] [--interval 30s]") + fmt.Fprintln(w, " sw-block ops frontend-publication-target-owner [--dry-run] [--namespace ] [--interval 30s] [--activate-targets --activation-policy --runtime-endpoint ]") + fmt.Fprintln(w, " sw-block ops frontend-publication-executor [--dry-run] [--namespace ] [--enable-execution] [--execution-policy] [--frontend-publication-runtime-url ] [--interval 30s]") + fmt.Fprintln(w, " sw-block ops chunk cut|detach --volume --status-addr [--min-lsn ] [--timeout ]") + fmt.Fprintln(w, " sw-block ops chunk snapshot --volume --status-addr --name [--label k=v]... [--request-id ] [--consistency crash|app]") + fmt.Fprintln(w, " sw-block ops chunk snapshots|snapshot-delete --volume [--name ] --chunk-filer [--chunk-path /swblock/chunks]") + fmt.Fprintln(w, " sw-block ops chunk show --volume --chunk-filer [--chunk-path /swblock/chunks]") + fmt.Fprintln(w, " sw-block ops chunk verify --volume --chunk-filer [--chunk-path /swblock/chunks] [--depth meta|bindings|data] [--orphans] [--timeout ]") + fmt.Fprintln(w, " (read-only; every root HEAD names is checked; exit 0 clean, 3 findings, 1 incomplete; --depth data needs --timeout)") + fmt.Fprintln(w, " sw-block ops volume resolve --master [--timeout 10s] (prints the master layout id)") + fmt.Fprintln(w, " sw-block ops volume-unheld --path (exit 0: no process on this host holds it; local filesystems only)") + fmt.Fprintln(w, " sw-block ops failover --master --volume --target --target-data --target-ctrl --expect-current @ --confirm-old-node-off ") + fmt.Fprintln(w, " sw-block ops workspace force-move --master --volume --target-host --target-data --target-ctrl --request-id --confirm-forced @ [--dry-run]") + fmt.Fprintln(w, " sw-block ops workspace lost-range --master --volume [--request-id ] (authority only; no bypass: see `sw-block ops workspace help`)") +} + +func emptyCLI(value string) string { + if strings.TrimSpace(value) == "" { + return "-" + } + return value +} + +type operatorStatusClusterSource struct { + cluster ops.ClusterEvidence +} + +func (s operatorStatusClusterSource) ClusterEvidence(context.Context) (ops.ClusterEvidence, error) { + return s.cluster, nil +} + +type operatorStatusDryRunWriter struct { + cluster ops.SwBlockClusterCRDStatus + volumes []operatorStatusDryRunVolumeWrite +} + +type operatorStatusDryRunVolumeWrite struct { + ref ops.OperatorObjectRef + status ops.SwBlockVolumeCRDStatus +} + +func (w *operatorStatusDryRunWriter) WriteClusterStatus(_ context.Context, _ ops.OperatorObjectRef, status ops.SwBlockClusterCRDStatus) error { + w.cluster = status + return nil +} + +func (w *operatorStatusDryRunWriter) WriteVolumeStatus(_ context.Context, ref ops.OperatorObjectRef, status ops.SwBlockVolumeCRDStatus) error { + w.volumes = append(w.volumes, operatorStatusDryRunVolumeWrite{ref: ref, status: status}) + return nil +} + +type operatorStatusDryRunEventSink struct { + events []ops.OperatorKubernetesEvent +} + +func (s *operatorStatusDryRunEventSink) EmitEvent(_ context.Context, event ops.OperatorKubernetesEvent) error { + s.events = append(s.events, event) + return nil +} + +type requiredFrontierFlags struct { + values map[string]uint64 +} + +func (f *requiredFrontierFlags) String() string { + if f == nil || len(f.values) == 0 { + return "" + } + parts := make([]string, 0, len(f.values)) + for volumeID, lsn := range f.values { + parts = append(parts, fmt.Sprintf("%s=%d", volumeID, lsn)) + } + return strings.Join(parts, ",") +} + +func (f *requiredFrontierFlags) Set(raw string) error { + volumeID, lsnText, ok := strings.Cut(raw, "=") + volumeID = strings.TrimSpace(volumeID) + lsnText = strings.TrimSpace(lsnText) + if !ok || volumeID == "" || lsnText == "" { + return fmt.Errorf("expected volume_id=lsn") + } + lsn, err := strconv.ParseUint(lsnText, 10, 64) + if err != nil { + return fmt.Errorf("parse required frontier lsn: %w", err) + } + if f.values == nil { + f.values = map[string]uint64{} + } + f.values[volumeID] = lsn + return nil +} diff --git a/seaweed-block/cmd/sw-block/main_test.go b/seaweed-block/cmd/sw-block/main_test.go new file mode 100644 index 0000000000..6aa24b69fb --- /dev/null +++ b/seaweed-block/cmd/sw-block/main_test.go @@ -0,0 +1,4057 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + hostvolume "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/ops" + "github.com/seaweedfs/seaweed-block/core/replication" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/protobuf/types/known/timestamppb" +) + +func TestOpsStatusWritesArtifactsAndReturnsClean(t *testing.T) { + oldRunCommand := opsStatusRunCommand + opsStatusRunCommand = cleanCmdResidueCommand + defer func() { opsStatusRunCommand = oldRunCommand }() + + masterAddr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + statusServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/status": + writeCmdJSON(t, w, hostvolume.StatusProjection{ + Projection: frontend.Projection{ + VolumeID: "v1", + ReplicaID: "r1", + Epoch: 7, + EndpointVersion: 2, + Healthy: true, + }, + FrontendPrimaryReady: true, + AuthorityRole: hostvolume.AuthorityRolePrimary, + ReplicationRole: hostvolume.ReplicationRoleNone, + }) + case "/status/peers": + writeCmdJSON(t, w, struct { + Peers []replication.ReplicaPeerStatus + }{Peers: []replication.ReplicaPeerStatus{{ReplicaID: "r2", State: "healthy", Epoch: 7, EndpointVersion: 2}}}) + case "/status/durable": + writeCmdJSON(t, w, struct { + Volumes []durable.VolumeStatus + }{Volumes: []durable.VolumeStatus{{VolumeID: "v1", ReplicaID: "r1", Latched: true, Operational: true}}}) + default: + http.NotFound(w, r) + } + })) + defer statusServer.Close() + + outDir := os.Getenv("SW_BLOCK_OPS_STATUS_CLI_ARTIFACT_DIR") + if outDir == "" { + outDir = t.TempDir() + } else if err := os.MkdirAll(outDir, 0o755); err != nil { + t.Fatalf("create artifact dir: %v", err) + } + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "status", + "--volume", "v1", + "--master", masterAddr, + "--status-addr", statusServer.URL, + "--out", outDir, + "--product-revision", "product-rev", + "--runner-revision", "runner-rev", + }, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, name := range []string{ops.VolumeStatusReportArtifact, ops.VolumeStatusSummaryArtifact} { + if _, err := os.Stat(filepath.Join(outDir, name)); err != nil { + t.Fatalf("missing artifact %s: %v", name, err) + } + } + if !strings.Contains(stdout.String(), "status: ok") { + t.Fatalf("stdout missing summary:\n%s", stdout.String()) + } + if !strings.Contains(stdout.String(), ops.OpsStatusBundleArtifact) { + t.Fatalf("stdout missing bundle artifact:\n%s", stdout.String()) + } + raw, err := os.ReadFile(filepath.Join(outDir, ops.VolumeStatusReportArtifact)) + if err != nil { + t.Fatal(err) + } + var report ops.VolumeStatusReport + if err := json.Unmarshal(raw, &report); err != nil { + t.Fatal(err) + } + if report.Volume.VolumeID != "v1" || len(report.Volume.Frontends) != 1 { + t.Fatalf("report mismatch: %+v", report) + } + if len(report.CollectionErrors) != 0 { + t.Fatalf("unexpected collection errors: %+v", report.CollectionErrors) + } + rawBundle, err := os.ReadFile(filepath.Join(outDir, ops.OpsStatusBundleArtifact)) + if err != nil { + t.Fatal(err) + } + var bundle ops.OpsStatusBundle + if err := json.Unmarshal(rawBundle, &bundle); err != nil { + t.Fatal(err) + } + if bundle.Command != "sw-block ops status" || bundle.VolumeID != "v1" || bundle.ProductRevision != "product-rev" || bundle.RunnerRevision != "runner-rev" { + t.Fatalf("bundle mismatch: %+v", bundle) + } + if bundle.ExitCode != ops.VolumeStatusExitOK || bundle.Status != "ok" { + t.Fatalf("bundle classification mismatch: %+v", bundle) + } + if bundle.CollectionErrors == nil || bundle.Unchecked == nil || len(bundle.NonClaims) == 0 { + t.Fatalf("bundle should include stable arrays and non-claims: %+v", bundle) + } +} + +func TestOpsInventoryWritesEmptyClusterArtifacts(t *testing.T) { + oldRunCommand := opsInventoryRunCommand + opsInventoryRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl -n default get pvc -o json": `{"items":[]}`, + "kubectl get pv -o json": `{"items":[]}`, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": `{"items":[]}`, + }) + defer func() { opsInventoryRunCommand = oldRunCommand }() + + outDir := t.TempDir() + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "inventory", + "--namespace", "default", + "--out", outDir, + "--product-revision", "product-rev", + "--runner-revision", "runner-rev", + }, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, name := range []string{ops.VolumeInventoryArtifact, ops.VolumeInventorySummaryArtifact, ops.OpsInventoryBundleArtifact} { + if _, err := os.Stat(filepath.Join(outDir, name)); err != nil { + t.Fatalf("missing artifact %s: %v", name, err) + } + } + if !strings.Contains(stdout.String(), "inventory_status: ok") || + !strings.Contains(stdout.String(), "volumes: total=0") || + !strings.Contains(stdout.String(), ops.OpsInventoryBundleArtifact) { + t.Fatalf("stdout missing inventory evidence:\n%s", stdout.String()) + } + + raw, err := os.ReadFile(filepath.Join(outDir, ops.VolumeInventoryArtifact)) + if err != nil { + t.Fatal(err) + } + var inventory ops.VolumeInventory + if err := json.Unmarshal(raw, &inventory); err != nil { + t.Fatal(err) + } + if inventory.ProductRevision != "product-rev" || inventory.RunnerRevision != "runner-rev" || len(inventory.Volumes) != 0 { + t.Fatalf("inventory mismatch: %+v", inventory) + } + rawBundle, err := os.ReadFile(filepath.Join(outDir, ops.OpsInventoryBundleArtifact)) + if err != nil { + t.Fatal(err) + } + var bundle ops.OpsInventoryBundle + if err := json.Unmarshal(rawBundle, &bundle); err != nil { + t.Fatal(err) + } + if bundle.Command != "sw-block ops inventory" || bundle.Status != "ok" || bundle.VolumeCount != 0 { + t.Fatalf("bundle mismatch: %+v", bundle) + } +} + +func TestOpsListAliasesInventory(t *testing.T) { + oldRunCommand := opsInventoryRunCommand + opsInventoryRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl -n default get pvc -o json": `{"items":[]}`, + "kubectl get pv -o json": `{"items":[]}`, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": `{"items":[]}`, + }) + defer func() { opsInventoryRunCommand = oldRunCommand }() + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "list", "--out", t.TempDir(), "--product-revision", "product-rev"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if !strings.Contains(stdout.String(), "inventory_status: ok") { + t.Fatalf("stdout=%s", stdout.String()) + } +} + +func TestOpsInventoryClusterUnreachableReturnsInvalidWithBundle(t *testing.T) { + oldRunCommand := opsInventoryRunCommand + opsInventoryRunCommand = func(context.Context, string, ...string) ([]byte, error) { + return []byte("The connection to the server 127.0.0.1:6443 was refused\n"), errors.New("exit status 1") + } + defer func() { opsInventoryRunCommand = oldRunCommand }() + + outDir := t.TempDir() + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "inventory", "--out", outDir, "--product-revision", "product-rev"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if !strings.Contains(stderr.String(), "kubernetes_unreachable") || + !strings.Contains(stdout.String(), "inventory_status: invalid") { + t.Fatalf("stdout=%s stderr=%s", stdout.String(), stderr.String()) + } + raw, err := os.ReadFile(filepath.Join(outDir, ops.OpsInventoryBundleArtifact)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(raw), "kubernetes_unreachable") { + t.Fatalf("bundle missing unreachable evidence:\n%s", raw) + } +} + +func TestOpsInventoryMissingOutReturnsInvalid(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "inventory"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d want %d", code, ops.VolumeStatusExitInvalid) + } + if !strings.Contains(stderr.String(), "--out is required") { + t.Fatalf("stderr=%s", stderr.String()) + } +} + +func TestOpsOperatorStatusDryRunFromBundle(t *testing.T) { + dir := t.TempDir() + cluster := ops.NewClusterEvidence(time.Date(2026, 6, 2, 23, 30, 0, 0, time.UTC)) + cluster.ManagedVolumes = []ops.ManagedVolumeProjection{ops.ProjectManagedVolume(ops.ManagedVolumeFacts{ + VolumeID: "pvc-operator", + PVCName: "demo-pvc", + PVC: &ops.PVCFact{Phase: "Bound"}, + Authority: &ops.AuthorityFact{ + PrimaryReplica: "r1", + PublishTarget: "192.168.1.184:3260", + }, + Replicas: []ops.ReplicaFact{{ + ReplicaID: "r1", + KubernetesNode: "m02", + Role: "primary", + Observed: true, + }}, + CSIStages: []ops.CSIStageFact{{NodeName: "m02", Target: "192.168.1.184:3260"}}, + Workload: &ops.WorkloadCheckFact{WriterVerified: true, ReaderVerified: true}, + })} + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, ops.ClusterEvidenceArtifact), raw, 0o644); err != nil { + t.Fatal(err) + } + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "operator-status", "--dry-run", "--from-bundle", dir, "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + out := stdout.String() + for _, want := range []string{ + "operator_status=dry_run cluster=kube-system/sw-block volumes=1", + "mutation_allowed=false", + "cluster_status volumes=1 ready=1 blocked=0 stale=0", + "volume_status name=demo-pvc volume_id=pvc-operator pvc=demo-pvc status=ready reason=first_volume_verified", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsOperatorStatusWritesCRDStatusWhenDryRunDisabled(t *testing.T) { + dir := t.TempDir() + cluster := ops.NewClusterEvidence(time.Date(2026, 6, 3, 10, 30, 0, 0, time.UTC)) + cluster.ManagedVolumes = []ops.ManagedVolumeProjection{ops.ProjectManagedVolume(ops.ManagedVolumeFacts{ + VolumeID: "pvc-write", + PVCName: "write-pvc", + PVC: &ops.PVCFact{Phase: "Bound"}, + Authority: &ops.AuthorityFact{ + PrimaryReplica: "r1", + PublishTarget: "192.168.1.184:3260", + }, + Replicas: []ops.ReplicaFact{{ + ReplicaID: "r1", + KubernetesNode: "m02", + Role: "primary", + Observed: true, + }}, + CSIStages: []ops.CSIStageFact{{NodeName: "m02", Target: "192.168.1.184:3260"}}, + Workload: &ops.WorkloadCheckFact{WriterVerified: true, ReaderVerified: true}, + })} + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, ops.ClusterEvidenceArtifact), raw, 0o644); err != nil { + t.Fatal(err) + } + + writer := &operatorStatusTestWriter{} + oldFactory := opsOperatorStatusWriterFactory + opsOperatorStatusWriterFactory = func() (ops.OperatorStatusWriter, error) { + return writer, nil + } + t.Cleanup(func() { opsOperatorStatusWriterFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "operator-status", "--from-bundle", t.TempDir()}, &stdout, &stderr) + if code == ops.VolumeStatusExitOK { + t.Fatalf("empty bundle unexpectedly succeeded stdout=%s stderr=%s", stdout.String(), stderr.String()) + } + + stdout.Reset() + stderr.Reset() + code = run([]string{"ops", "operator-status", "--from-bundle", dir, "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if writer.cluster.VolumeCount != 1 || len(writer.volumes) != 1 { + t.Fatalf("writer cluster=%+v volumes=%+v", writer.cluster, writer.volumes) + } + if writer.volumes[0].ref.Name != "write-pvc" || writer.volumes[0].status.Status != ops.ManagedVolumeStatusReady { + t.Fatalf("volume write=%+v", writer.volumes[0]) + } + out := stdout.String() + for _, want := range []string{ + "operator_status=write_status cluster=kube-system/sw-block volumes=1", + "mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsLifecycleOwnerDryRunDoesNotPatch(t *testing.T) { + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockVolumeKind, + Namespace: "kube-system", + Name: "demo-volume", + }, + }}, + } + oldFactory := opsLifecycleOwnerClientFactory + opsLifecycleOwnerClientFactory = func() (ops.LifecycleOwnerClient, ops.OperatorEventSink, error) { + return client, client, nil + } + t.Cleanup(func() { opsLifecycleOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "lifecycle-owner", "--dry-run", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.patches) != 0 || len(client.events) != 0 { + t.Fatalf("dry-run patched/events: patches=%+v events=%+v", client.patches, client.events) + } + out := stdout.String() + for _, want := range []string{ + "lifecycle_owner=dry_run namespace=kube-system volumes=1", + "finalizer_patches=0", + "finalizer_added=1", + "events=0", + "mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsLifecycleOwnerWritesProtectionFinalizer(t *testing.T) { + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockVolumeKind, + Namespace: "kube-system", + Name: "demo-volume", + }, + Finalizers: []string{"example.com/foreign"}, + }}, + } + oldFactory := opsLifecycleOwnerClientFactory + opsLifecycleOwnerClientFactory = func() (ops.LifecycleOwnerClient, ops.OperatorEventSink, error) { + return client, client, nil + } + t.Cleanup(func() { opsLifecycleOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "lifecycle-owner", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.patches) != 1 { + t.Fatalf("patches=%+v", client.patches) + } + wantFinalizers := []string{"example.com/foreign", ops.SwBlockVolumeFinalizerName} + if fmt.Sprint(client.patches[0].finalizers) != fmt.Sprint(wantFinalizers) { + t.Fatalf("finalizers=%+v want %+v", client.patches[0].finalizers, wantFinalizers) + } + if len(client.events) != 1 || client.events[0].Reason != ops.ReasonDeleteFinalizerAdded { + t.Fatalf("events=%+v", client.events) + } + out := stdout.String() + for _, want := range []string{ + "lifecycle_owner=finalizer_mutation namespace=kube-system volumes=1", + "finalizer_patches=1", + "finalizer_added=1", + "events=1", + "mutation_allowed=true", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsLifecycleOwnerReleasesProtectionFinalizerWhenDeleteSafetyAllows(t *testing.T) { + deletingAt := time.Date(2026, 6, 15, 2, 0, 0, 0, time.UTC) + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockVolumeKind, + Namespace: "kube-system", + Name: "demo-volume", + }, + Finalizers: []string{"example.com/foreign", ops.SwBlockVolumeFinalizerName}, + DeletionTimestamp: &deletingAt, + Status: ops.SwBlockVolumeCRDStatus{DeleteSafety: &ops.SwBlockVolumeCRDDeleteSafety{ + Decision: ops.ManagedVolumeActionDecisionAllowed, + State: ops.DeleteSafetyStateReleasable, + Reason: ops.ReasonDeleteFinalizerReleasable, + FinalizerReleaseAllowed: true, + }}, + }}, + } + oldFactory := opsLifecycleOwnerClientFactory + opsLifecycleOwnerClientFactory = func() (ops.LifecycleOwnerClient, ops.OperatorEventSink, error) { + return client, client, nil + } + t.Cleanup(func() { opsLifecycleOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "lifecycle-owner", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.patches) != 1 { + t.Fatalf("patches=%+v", client.patches) + } + if got, want := fmt.Sprint(client.patches[0].finalizers), fmt.Sprint([]string{"example.com/foreign"}); got != want { + t.Fatalf("finalizers=%s want %s", got, want) + } + out := stdout.String() + for _, want := range []string{ + "finalizer_patches=1", + "finalizer_released=1", + "events=1", + "mutation_allowed=true", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsAuthorityExecutorObservesDisabledContractsWithoutMutation(t *testing.T) { + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockVolumeKind, + Namespace: "kube-system", + Name: "returned", + }, + Status: ops.SwBlockVolumeCRDStatus{ExecutorContracts: []ops.SwBlockVolumeCRDExecutorContract{{ + ActionType: ops.ManagedVolumeActionReintegrateReturned, + ReplicaID: "r1", + Decision: ops.ReturnedReplicaExecutorContractDisabled, + Reason: ops.ReturnedReplicaExecutorContractReasonExecutorDisabled, + OwnerExecutor: "authority_recovery_executor", + ExecutionEnabled: false, + MutationAllowed: false, + AllowedMutationClass: []string{"ack_eligibility"}, + ForbiddenMutationClass: []string{"frontend_publication", "rebuild_traffic", "failback"}, + TerminalEvidenceRequired: []string{"ack_eligibility_known", "frontend_fenced_after_execution"}, + }}}, + }}, + } + oldFactory := opsAuthorityExecutorClientFactory + opsAuthorityExecutorClientFactory = func() (ops.AuthorityExecutorClient, error) { + return client, nil + } + t.Cleanup(func() { opsAuthorityExecutorClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "authority-executor", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.patches) != 0 || len(client.events) != 0 { + t.Fatalf("authority executor must not patch or emit events: patches=%+v events=%+v", client.patches, client.events) + } + out := stdout.String() + for _, want := range []string{ + "authority_executor=disabled namespace=kube-system volumes=1 contracts=1", + "disabled_contracts=1", + "terminal_evidence_required=1", + "allowed_mutation_class=ack_eligibility", + "execution_requested=false", + "execution_policy_enabled=false", + "mutation_attempts=0", + "ack_eligibility_mutation_attempts=0", + "mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsAuthorityExecutorRejectsExecutionFlag(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "authority-executor", "--enable-execution"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if !strings.Contains(stderr.String(), "reason=executor_policy_disabled") || + !strings.Contains(stderr.String(), "mutation_attempts=0") || + !strings.Contains(stderr.String(), "ack_eligibility_mutation_attempts=0") { + t.Fatalf("stderr=%s", stderr.String()) + } +} + +func TestOpsAuthorityExecutorRejectsUnsupportedMutationClass(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "authority-executor", "--allowed-mutation-class", "frontend_publication"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if !strings.Contains(stderr.String(), "unsupported mutation class") || + !strings.Contains(stderr.String(), "reason=unsupported_mutation_class") { + t.Fatalf("stderr=%s", stderr.String()) + } +} + +func TestOpsAuthorityExecutorWritesRebuildPlannedStatus(t *testing.T) { + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockVolumeKind, + Namespace: "kube-system", + Name: "rebuild", + }, + Status: ops.SwBlockVolumeCRDStatus{ + VolumeID: "pvc-rebuild", + PVCName: "rebuild-pvc", + ReplicaReintegrations: []ops.SwBlockVolumeCRDReturnedReplica{{ + ReplicaID: "r1", + State: ops.ReturnedReplicaStateRecovering, + ReasonCode: ops.ReasonCandidateFrontierBehind, + FrontendFenced: true, + FrontendPrimaryReady: false, + AckEligibilityKnown: true, + AckEligible: false, + DurableFrontierKnown: true, + DurableFrontierLSN: 51, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 52, + EvidenceRefs: []string{"rebuild.txt"}, + }}, + ExecutorContracts: []ops.SwBlockVolumeCRDExecutorContract{{ + ActionType: ops.ManagedVolumeActionRebuildReturned, + ReplicaID: "r1", + Decision: ops.ReturnedReplicaExecutorContractDisabled, + Reason: ops.ReturnedReplicaExecutorContractReasonExecutorDisabled, + OwnerExecutor: "authority_recovery_executor", + ExecutionEnabled: false, + MutationAllowed: false, + PreflightDecision: ops.ReturnedReplicaExecutorPreflightReady, + PreflightReason: ops.ReturnedReplicaExecutorPreflightReasonSatisfied, + AllowedMutationClass: []string{ops.AuthorityExecutorAllowedMutationRebuildTraffic}, + ForbiddenMutationClass: []string{"ack_eligibility", "frontend_publication", "failback"}, + TerminalEvidenceRequired: []string{"frontend_fenced_before_rebuild", "primary_unchanged", "durable_frontier_caught_up", "no_frontend_publication", "no_cross_volume_identity_change"}, + EvidenceRefs: []string{"rebuild-contract.txt"}, + }}, + }, + }}, + rebuilds: []ops.SwBlockReplicaRebuildObject{{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockReplicaRebuildKind, + Namespace: "kube-system", + Name: "rebuild-r1", + }, + Spec: ops.SwBlockReplicaRebuildSpec{ + VolumeName: "rebuild", + VolumeID: "pvc-rebuild", + PVCName: "rebuild-pvc", + ReplicaID: "r1", + }, + }}, + } + oldFactory := opsAuthorityExecutorClientFactory + opsAuthorityExecutorClientFactory = func() (ops.AuthorityExecutorClient, error) { + return client, nil + } + t.Cleanup(func() { opsAuthorityExecutorClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "authority-executor", "--namespace", "kube-system", "--allowed-mutation-class", "rebuild_traffic", "--enable-execution", "--execution-policy"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.eligibilityWrites) != 0 || len(client.rebuildWrites) != 1 { + t.Fatalf("eligibility_writes=%+v rebuild_writes=%+v", client.eligibilityWrites, client.rebuildWrites) + } + write := client.rebuildWrites[0] + if write.ref.Name != "rebuild-r1" { + t.Fatalf("write ref=%+v", write.ref) + } + if write.status.State != "planned" || + write.status.ReasonCode != ops.AuthorityExecutorReasonRebuildPlanned || + write.status.RebuildTrafficStarted || + !write.status.NoFrontendPublication || + !write.status.NoCrossVolumeIdentityChange { + t.Fatalf("rebuild status=%+v", write.status) + } + out := stdout.String() + for _, want := range []string{ + "authority_executor=executed", + "allowed_mutation_class=rebuild_traffic", + "mutation_attempts=1", + "ack_eligibility_mutation_attempts=0", + "rebuild_progress_mutation_attempts=1", + "mutation_allowed=true", + "storage_mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsAuthorityExecutorRebuildRuntimeURLWritesCaughtUpStatus(t *testing.T) { + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockVolumeKind, + Namespace: "kube-system", + Name: "rebuild", + }, + Status: ops.SwBlockVolumeCRDStatus{ + VolumeID: "pvc-rebuild", + PVCName: "rebuild-pvc", + ReplicaReintegrations: []ops.SwBlockVolumeCRDReturnedReplica{{ + ReplicaID: "r1", + State: ops.ReturnedReplicaStateRecovering, + ReasonCode: ops.ReasonCandidateFrontierBehind, + FrontendFenced: true, + FrontendPrimaryReady: false, + AckEligibilityKnown: true, + AckEligible: false, + DurableFrontierKnown: true, + DurableFrontierLSN: 51, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 52, + EvidenceRefs: []string{"rebuild.txt"}, + }}, + ExecutorContracts: []ops.SwBlockVolumeCRDExecutorContract{{ + ActionType: ops.ManagedVolumeActionRebuildReturned, + ReplicaID: "r1", + Decision: ops.ReturnedReplicaExecutorContractDisabled, + Reason: ops.ReturnedReplicaExecutorContractReasonExecutorDisabled, + OwnerExecutor: "authority_recovery_executor", + ExecutionEnabled: false, + MutationAllowed: false, + PreflightDecision: ops.ReturnedReplicaExecutorPreflightReady, + PreflightReason: ops.ReturnedReplicaExecutorPreflightReasonSatisfied, + AllowedMutationClass: []string{ops.AuthorityExecutorAllowedMutationRebuildTraffic}, + ForbiddenMutationClass: []string{"ack_eligibility", "frontend_publication", "failback"}, + TerminalEvidenceRequired: []string{"frontend_fenced_before_rebuild", "primary_unchanged", "durable_frontier_caught_up", "no_frontend_publication", "no_cross_volume_identity_change"}, + EvidenceRefs: []string{"rebuild-contract.txt"}, + }}, + }, + }}, + rebuilds: []ops.SwBlockReplicaRebuildObject{{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockReplicaRebuildKind, + Namespace: "kube-system", + Name: "rebuild-r1", + }, + Spec: ops.SwBlockReplicaRebuildSpec{ + VolumeName: "rebuild", + VolumeID: "pvc-rebuild", + PVCName: "rebuild-pvc", + ReplicaID: "r1", + RuntimeEndpoint: "http://127.0.0.1:23260/rebuild/runtime", + TargetDataAddr: "127.0.0.1:19103", + SessionID: 1001, + Epoch: 7, + EndpointVersion: 3, + FromLSN: 52, + FrontierHintLSN: 52, + BasePinLSN: 60, + }, + }}, + } + oldFactory := opsAuthorityExecutorClientFactory + opsAuthorityExecutorClientFactory = func() (ops.AuthorityExecutorClient, error) { + return client, nil + } + t.Cleanup(func() { opsAuthorityExecutorClientFactory = oldFactory }) + + var got ops.AuthorityRebuildRuntimeRequest + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Fatalf("method=%s", r.Method) + } + if err := json.NewDecoder(r.Body).Decode(&got); err != nil { + t.Fatalf("decode request: %v", err) + } + _ = json.NewEncoder(w).Encode(ops.AuthorityRebuildRuntimeResult{ + DurableFrontierKnown: true, + DurableFrontierLSN: 52, + EvidenceRefs: []string{"http-runtime.txt"}, + }) + })) + defer server.Close() + + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "authority-executor", + "--namespace", "kube-system", + "--allowed-mutation-class", "rebuild_traffic", + "--enable-execution", + "--execution-policy", + "--rebuild-runtime-url", server.URL, + }, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if got.VolumeName != "rebuild" || + got.VolumeID != "pvc-rebuild" || + got.PVCName != "rebuild-pvc" || + got.ReplicaID != "r1" || + got.RuntimeEndpoint != "http://127.0.0.1:23260/rebuild/runtime" || + got.TargetDataAddr != "127.0.0.1:19103" || + got.SessionID != 1001 || + got.Epoch != 7 || + got.EndpointVersion != 3 || + got.FromLSN != 52 || + got.FrontierHintLSN != 52 || + got.BasePinLSN != 60 || + got.DurableFrontierLSN != 51 || + got.RequiredFrontierLSN != 52 || + !got.NoFrontendPublication || + !got.NoCrossVolumeMutation { + t.Fatalf("runtime request=%+v", got) + } + if len(client.eligibilityWrites) != 0 || len(client.rebuildWrites) != 2 { + t.Fatalf("eligibility_writes=%+v rebuild_writes=%+v", client.eligibilityWrites, client.rebuildWrites) + } + running := client.rebuildWrites[0].status + if running.State != "running" || + running.ReasonCode != ops.AuthorityExecutorReasonRebuildRunning || + !running.RebuildTrafficStarted || + !running.NoFrontendPublication { + t.Fatalf("running status=%+v", running) + } + caughtUp := client.rebuildWrites[1].status + if caughtUp.State != "caught_up" || + caughtUp.ReasonCode != ops.AuthorityExecutorReasonRebuildCaughtUp || + !caughtUp.DurableFrontierCaughtUp || + caughtUp.DurableFrontierLSN != 52 || + !cmdStringSliceContains(caughtUp.EvidenceRefs, "http-runtime.txt") || + !caughtUp.NoFrontendPublication || + !caughtUp.NoCrossVolumeIdentityChange { + t.Fatalf("caught_up status=%+v", caughtUp) + } + out := stdout.String() + for _, want := range []string{ + "authority_executor=executed", + "allowed_mutation_class=rebuild_traffic", + "mutation_attempts=1", + "rebuild_progress_mutation_attempts=1", + "mutation_allowed=true", + "storage_mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsAuthorityExecutorRejectsRebuildRuntimeURLForAckEligibility(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "authority-executor", "--rebuild-runtime-url", "http://127.0.0.1:1/runtime"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if !strings.Contains(stderr.String(), "--rebuild-runtime-url requires --allowed-mutation-class rebuild_traffic") || + !strings.Contains(stderr.String(), "reason=unsupported_runtime_mutation_class") { + t.Fatalf("stderr=%s", stderr.String()) + } +} + +func TestOpsRebuildTargetOwnerCreatesTarget(t *testing.T) { + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockVolumeKind, + Namespace: "kube-system", + Name: "demo-pvc", + }, + Status: ops.SwBlockVolumeCRDStatus{ + VolumeID: "pvc-demo", + PVCName: "demo-pvc", + ReplicaReintegrations: []ops.SwBlockVolumeCRDReturnedReplica{{ + ReplicaID: "r2", + State: ops.ReturnedReplicaStateRecovering, + ReasonCode: ops.ReasonCandidateFrontierBehind, + FrontendFenced: true, + FrontendPrimaryReady: false, + DurableFrontierKnown: true, + DurableFrontierLSN: 51, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 53, + RuntimeEndpoint: "http://127.0.0.1:23260/rebuild/runtime", + TargetDataAddr: "127.0.0.1:19103", + SessionID: 1001, + Epoch: 7, + EndpointVersion: 3, + FromLSN: 52, + FrontierHintLSN: 53, + BasePinLSN: 60, + }}, + ExecutorContracts: []ops.SwBlockVolumeCRDExecutorContract{{ + ActionType: ops.ManagedVolumeActionRebuildReturned, + ReplicaID: "r2", + Decision: ops.ReturnedReplicaExecutorContractDisabled, + Reason: ops.ReturnedReplicaExecutorContractReasonExecutorDisabled, + PreflightDecision: ops.ReturnedReplicaExecutorPreflightReady, + PreflightReason: ops.ReturnedReplicaExecutorPreflightReasonSatisfied, + AllowedMutationClass: []string{ops.AuthorityExecutorAllowedMutationRebuildTraffic}, + }}, + }, + }}, + } + oldFactory := opsRebuildTargetOwnerClientFactory + opsRebuildTargetOwnerClientFactory = func() (ops.RebuildTargetOwnerClient, error) { + return client, nil + } + t.Cleanup(func() { opsRebuildTargetOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "rebuild-target-owner", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.rebuildCreates) != 1 { + t.Fatalf("rebuildCreates=%+v", client.rebuildCreates) + } + created := client.rebuildCreates[0] + if created.Ref.Name != "demo-pvc-r2-rebuild" || + created.Spec.VolumeName != "demo-pvc" || + created.Spec.ReplicaID != "r2" || + created.Spec.RuntimeEndpoint != "http://127.0.0.1:23260/rebuild/runtime" || + created.Spec.TargetDataAddr != "127.0.0.1:19103" || + created.Spec.SessionID != 1001 || + created.Spec.Epoch != 7 || + created.Spec.EndpointVersion != 3 || + created.Spec.FromLSN != 52 || + created.Spec.FrontierHintLSN != 53 || + created.Spec.BasePinLSN != 60 { + t.Fatalf("created=%+v", created) + } + out := stdout.String() + for _, want := range []string{ + "rebuild_target_owner=target_mutation", + "namespace=kube-system", + "volumes=1", + "contracts=1", + "targets_planned=1", + "targets_existing=0", + "targets_created=1", + "runtime_target_ready=1", + "runtime_target_missing=0", + "mutation_allowed=true", + "storage_mutation_allowed=false", + "frontend_publication_allowed=false", + "failback_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsRebuildTargetOwnerDryRunDoesNotCreateTarget(t *testing.T) { + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + Name: "demo-pvc", + }, + Status: ops.SwBlockVolumeCRDStatus{ + VolumeID: "pvc-demo", + PVCName: "demo-pvc", + ReplicaReintegrations: []ops.SwBlockVolumeCRDReturnedReplica{{ + ReplicaID: "r2", + State: ops.ReturnedReplicaStateRecovering, + ReasonCode: ops.ReasonCandidateFrontierBehind, + FrontendFenced: true, + FrontendPrimaryReady: false, + DurableFrontierKnown: true, + DurableFrontierLSN: 51, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 53, + RuntimeEndpoint: "http://127.0.0.1:23260/rebuild/runtime", + TargetDataAddr: "127.0.0.1:19103", + SessionID: 1001, + Epoch: 7, + EndpointVersion: 3, + FromLSN: 52, + FrontierHintLSN: 53, + BasePinLSN: 60, + }}, + ExecutorContracts: []ops.SwBlockVolumeCRDExecutorContract{{ + ActionType: ops.ManagedVolumeActionRebuildReturned, + ReplicaID: "r2", + Decision: ops.ReturnedReplicaExecutorContractDisabled, + Reason: ops.ReturnedReplicaExecutorContractReasonExecutorDisabled, + PreflightDecision: ops.ReturnedReplicaExecutorPreflightReady, + PreflightReason: ops.ReturnedReplicaExecutorPreflightReasonSatisfied, + AllowedMutationClass: []string{ops.AuthorityExecutorAllowedMutationRebuildTraffic}, + }}, + }, + }}, + } + oldFactory := opsRebuildTargetOwnerClientFactory + opsRebuildTargetOwnerClientFactory = func() (ops.RebuildTargetOwnerClient, error) { + return client, nil + } + t.Cleanup(func() { opsRebuildTargetOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "rebuild-target-owner", "--dry-run", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.rebuildCreates) != 0 { + t.Fatalf("dry-run creates=%+v", client.rebuildCreates) + } + out := stdout.String() + for _, want := range []string{ + "rebuild_target_owner=dry_run", + "targets_planned=1", + "targets_created=0", + "runtime_target_ready=1", + "runtime_target_missing=0", + "mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsRebuildTargetOwnerDoesNotCreateTargetWhenRuntimeFactsMissing(t *testing.T) { + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + Name: "demo-pvc", + }, + Status: ops.SwBlockVolumeCRDStatus{ + VolumeID: "pvc-demo", + PVCName: "demo-pvc", + ReplicaReintegrations: []ops.SwBlockVolumeCRDReturnedReplica{{ + ReplicaID: "r2", + State: ops.ReturnedReplicaStateRecovering, + ReasonCode: ops.ReasonCandidateFrontierBehind, + FrontendFenced: true, + FrontendPrimaryReady: false, + DurableFrontierKnown: true, + DurableFrontierLSN: 51, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 53, + }}, + ExecutorContracts: []ops.SwBlockVolumeCRDExecutorContract{{ + ActionType: ops.ManagedVolumeActionRebuildReturned, + ReplicaID: "r2", + Decision: ops.ReturnedReplicaExecutorContractDisabled, + Reason: ops.ReturnedReplicaExecutorContractReasonExecutorDisabled, + PreflightDecision: ops.ReturnedReplicaExecutorPreflightReady, + PreflightReason: ops.ReturnedReplicaExecutorPreflightReasonSatisfied, + AllowedMutationClass: []string{ops.AuthorityExecutorAllowedMutationRebuildTraffic}, + }}, + }, + }}, + } + oldFactory := opsRebuildTargetOwnerClientFactory + opsRebuildTargetOwnerClientFactory = func() (ops.RebuildTargetOwnerClient, error) { + return client, nil + } + t.Cleanup(func() { opsRebuildTargetOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "rebuild-target-owner", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.rebuildCreates) != 0 { + t.Fatalf("unexpected creates=%+v", client.rebuildCreates) + } + out := stdout.String() + for _, want := range []string{ + "rebuild_target_owner=target_mutation", + "targets_planned=0", + "targets_created=0", + "runtime_target_ready=0", + "runtime_target_missing=1", + "mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsFailbackTargetOwnerCreatesTarget(t *testing.T) { + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{cmdFailbackTargetVolume()}, + } + oldFactory := opsFailbackTargetOwnerClientFactory + opsFailbackTargetOwnerClientFactory = func() (ops.FailbackTargetOwnerClient, error) { + return client, nil + } + t.Cleanup(func() { opsFailbackTargetOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "failback-target-owner", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.failbackCreates) != 1 { + t.Fatalf("failbackCreates=%+v", client.failbackCreates) + } + created := client.failbackCreates[0] + if created.Ref.Name != "demo-pvc-r1-failback" || + created.Spec.VolumeName != "demo-pvc" || + created.Spec.VolumeID != "pvc-demo" || + created.Spec.PVCName != "demo-pvc" || + created.Spec.ReplicaID != "r1" || + created.Spec.TargetDataAddr != "data-r1" || + created.Spec.TargetCtrlAddr != "ctrl-r1" || + created.Spec.ExpectedCurrentReplicaID != "r2" || + created.Spec.ExpectedCurrentEpoch != 7 || + !created.Spec.AckEligible || + !created.Spec.FrontendFencedBeforeFailback || + !created.Spec.DurableFrontierCovered || + !created.Spec.NoCrossVolumeIdentityChange || + created.Spec.FailbackDecision != ops.AuthorityExecutorFailbackDecisionDisabled || + created.Spec.FailbackReason != ops.AuthorityExecutorFailbackReasonDisabled || + created.Spec.FailbackMutationAllowed { + t.Fatalf("created=%+v", created) + } + out := stdout.String() + for _, want := range []string{ + "failback_target_owner=target_mutation", + "namespace=kube-system", + "volumes=1", + "contracts=1", + "targets_planned=1", + "targets_existing=0", + "targets_created=1", + "terminal_evidence_ready=1", + "terminal_evidence_missing=0", + "failback_attempts=0", + "mutation_allowed=true", + "storage_mutation_allowed=false", + "frontend_publication_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsFailbackTargetOwnerDryRunDoesNotCreateTarget(t *testing.T) { + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{cmdFailbackTargetVolume()}, + } + oldFactory := opsFailbackTargetOwnerClientFactory + opsFailbackTargetOwnerClientFactory = func() (ops.FailbackTargetOwnerClient, error) { + return client, nil + } + t.Cleanup(func() { opsFailbackTargetOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "failback-target-owner", "--dry-run", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.failbackCreates) != 0 { + t.Fatalf("dry-run creates=%+v", client.failbackCreates) + } + out := stdout.String() + for _, want := range []string{ + "failback_target_owner=dry_run", + "targets_planned=1", + "targets_created=0", + "terminal_evidence_ready=1", + "mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsFailbackTargetOwnerCreatesActivatedTargetWithExplicitPolicy(t *testing.T) { + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{cmdFailbackTargetVolume()}, + } + oldFactory := opsFailbackTargetOwnerClientFactory + opsFailbackTargetOwnerClientFactory = func() (ops.FailbackTargetOwnerClient, error) { + return client, nil + } + t.Cleanup(func() { opsFailbackTargetOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "failback-target-owner", "--namespace", "kube-system", "--activate-targets", "--activation-policy", "--runtime-endpoint", "blockmaster.kube-system.svc:9333"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.failbackCreates) != 1 { + t.Fatalf("failbackCreates=%+v", client.failbackCreates) + } + created := client.failbackCreates[0] + if created.Spec.FailbackDecision != ops.AuthorityExecutorFailbackDecisionEnabled || + created.Spec.FailbackReason != ops.AuthorityExecutorFailbackReasonRequested || + !created.Spec.FailbackMutationAllowed || + created.Spec.RuntimeEndpoint != "blockmaster.kube-system.svc:9333" || + created.Spec.ExpectedCurrentReplicaID != "r2" || + created.Spec.ExpectedCurrentEpoch != 7 { + t.Fatalf("created=%+v", created) + } + out := stdout.String() + for _, want := range []string{ + "activate_targets=true", + "activation_policy=true", + "failback_attempts=0", + "storage_mutation_allowed=false", + "frontend_publication_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsFailbackExecutorWritesDisabledStatus(t *testing.T) { + client := &lifecycleOwnerTestClient{ + failbacks: []ops.SwBlockReplicaFailbackObject{cmdFailbackTarget()}, + } + oldFactory := opsFailbackExecutorClientFactory + opsFailbackExecutorClientFactory = func() (ops.FailbackExecutorClient, error) { + return client, nil + } + t.Cleanup(func() { opsFailbackExecutorClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "failback-executor", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.failbackStatusWrites) != 1 { + t.Fatalf("failbackStatusWrites=%+v", client.failbackStatusWrites) + } + status := client.failbackStatusWrites[0].status + if status.State != ops.FailbackStateBlocked || + status.ReasonCode != ops.AuthorityExecutorFailbackReasonDisabled || + status.FailbackMutationAllowed || + status.FailbackStarted || + status.AuthorityEpochAdvanced || + status.SinglePrimaryAfterFailback || + status.PublishTargetSwappedAfterFailback { + t.Fatalf("status=%+v", status) + } + out := stdout.String() + for _, want := range []string{ + "failback_executor=write_status", + "namespace=kube-system", + "targets=1", + "status_writes=1", + "invalid_targets=0", + "failback_attempts=0", + "status_mutation_allowed=true", + "authority_mutation_allowed=false", + "frontend_publication_allowed=false", + "mutation_allowed=true", + "storage_mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsFailbackExecutorDryRunDoesNotWriteStatus(t *testing.T) { + client := &lifecycleOwnerTestClient{ + failbacks: []ops.SwBlockReplicaFailbackObject{cmdFailbackTarget()}, + } + oldFactory := opsFailbackExecutorClientFactory + opsFailbackExecutorClientFactory = func() (ops.FailbackExecutorClient, error) { + return client, nil + } + t.Cleanup(func() { opsFailbackExecutorClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "failback-executor", "--dry-run", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.failbackStatusWrites) != 0 { + t.Fatalf("dry-run writes=%+v", client.failbackStatusWrites) + } + out := stdout.String() + for _, want := range []string{ + "failback_executor=dry_run", + "targets=1", + "status_writes=0", + "failback_attempts=0", + "status_mutation_allowed=false", + "authority_mutation_allowed=false", + "frontend_publication_allowed=false", + "mutation_allowed=false", + "storage_mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsFrontendPublicationTargetOwnerCreatesTarget(t *testing.T) { + client := &lifecycleOwnerTestClient{ + eligibilities: []ops.SwBlockReplicaEligibilityObject{cmdFrontendPublicationEligibility()}, + } + oldFactory := opsFrontendPublicationTargetOwnerClientFactory + opsFrontendPublicationTargetOwnerClientFactory = func() (ops.FrontendPublicationTargetOwnerClient, error) { + return client, nil + } + t.Cleanup(func() { opsFrontendPublicationTargetOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "frontend-publication-target-owner", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.frontendPublicationCreates) != 1 { + t.Fatalf("frontendPublicationCreates=%+v", client.frontendPublicationCreates) + } + created := client.frontendPublicationCreates[0] + if created.Ref.Name != "demo-pvc-r2-frontend-publication" || + created.Spec.VolumeName != "demo-pvc" || + created.Spec.ReplicaID != "r2" || + created.Spec.SourceEligibilityName != "demo-pvc-r2-ack" || + !created.Spec.AckEligibilityKnown || + !created.Spec.AckEligible || + !created.Spec.FrontendFencedAfterExecution || + !created.Spec.PrimaryUnchanged || + !created.Spec.DurableFrontierCovered || + !created.Spec.NoCrossVolumeIdentityChange || + created.Spec.FrontendPublicationDecision != ops.AuthorityExecutorPublicationDecisionDisabled || + created.Spec.FrontendPublicationReason != ops.AuthorityExecutorFrontendPublicationReasonDisabled || + created.Spec.FrontendPublicationMutationAllowed { + t.Fatalf("created=%+v", created) + } + out := stdout.String() + for _, want := range []string{ + "frontend_publication_target_owner=target_mutation", + "namespace=kube-system", + "eligibilities=1", + "ready_eligibilities=1", + "targets_planned=1", + "targets_existing=0", + "targets_created=1", + "invalid_eligibilities=0", + "frontend_publication_attempts=0", + "failback_attempts=0", + "mutation_allowed=true", + "storage_mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsFrontendPublicationTargetOwnerCreatesTargetFromFailback(t *testing.T) { + client := &lifecycleOwnerTestClient{ + failbacks: []ops.SwBlockReplicaFailbackObject{cmdTerminalFailbackTarget()}, + } + oldFactory := opsFrontendPublicationTargetOwnerClientFactory + opsFrontendPublicationTargetOwnerClientFactory = func() (ops.FrontendPublicationTargetOwnerClient, error) { + return client, nil + } + t.Cleanup(func() { opsFrontendPublicationTargetOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "frontend-publication-target-owner", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.frontendPublicationCreates) != 1 { + t.Fatalf("frontendPublicationCreates=%+v", client.frontendPublicationCreates) + } + created := client.frontendPublicationCreates[0] + if created.Ref.Name != "demo-pvc-r1-frontend-publication" || + created.Spec.VolumeName != "demo-pvc" || + created.Spec.ReplicaID != "r1" || + created.Spec.TargetDataAddr != "data-r1" || + created.Spec.TargetCtrlAddr != "ctrl-r1" || + created.Spec.SourceFailbackName != "demo-pvc-r1-failback" || + created.Spec.SourceEligibilityName != "" || + !created.Spec.FailbackCompleted || + !created.Spec.AuthorityEpochAdvanced || + !created.Spec.SinglePrimaryAfterFailback || + !created.Spec.PublishTargetSwappedAfterFailback || + !created.Spec.NoCrossVolumeIdentityChange || + created.Spec.FrontendPublicationDecision != ops.AuthorityExecutorPublicationDecisionDisabled || + created.Spec.FrontendPublicationReason != ops.AuthorityExecutorFrontendPublicationReasonDisabled || + created.Spec.FrontendPublicationMutationAllowed { + t.Fatalf("created=%+v", created) + } + out := stdout.String() + for _, want := range []string{ + "failbacks=1", + "terminal_failbacks=1", + "targets_planned=1", + "targets_created=1", + "invalid_failbacks=0", + "frontend_publication_attempts=0", + "failback_attempts=0", + "storage_mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsFrontendPublicationTargetOwnerDryRunDoesNotCreateTarget(t *testing.T) { + client := &lifecycleOwnerTestClient{ + eligibilities: []ops.SwBlockReplicaEligibilityObject{cmdFrontendPublicationEligibility()}, + } + oldFactory := opsFrontendPublicationTargetOwnerClientFactory + opsFrontendPublicationTargetOwnerClientFactory = func() (ops.FrontendPublicationTargetOwnerClient, error) { + return client, nil + } + t.Cleanup(func() { opsFrontendPublicationTargetOwnerClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "frontend-publication-target-owner", "--dry-run", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.frontendPublicationCreates) != 0 { + t.Fatalf("dry-run creates=%+v", client.frontendPublicationCreates) + } + out := stdout.String() + for _, want := range []string{ + "frontend_publication_target_owner=dry_run", + "targets_planned=1", + "targets_created=0", + "frontend_publication_attempts=0", + "failback_attempts=0", + "mutation_allowed=false", + "storage_mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsFailbackExecutorExecutionPolicyBlocks(t *testing.T) { + client := &lifecycleOwnerTestClient{ + failbacks: []ops.SwBlockReplicaFailbackObject{cmdFailbackExecutableTarget()}, + } + oldFactory := opsFailbackExecutorClientFactory + opsFailbackExecutorClientFactory = func() (ops.FailbackExecutorClient, error) { + return client, nil + } + t.Cleanup(func() { opsFailbackExecutorClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "failback-executor", "--enable-execution", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if !strings.Contains(stderr.String(), "failback execution is disabled by product policy") || + !strings.Contains(stderr.String(), "failback_attempts=0") { + t.Fatalf("stderr=%s", stderr.String()) + } + if len(client.failbackStatusWrites) != 0 { + t.Fatalf("policy-disabled execution wrote status: %+v", client.failbackStatusWrites) + } +} + +func TestOpsFailbackExecutorRuntimeURLWritesFailedBackStatus(t *testing.T) { + client := &lifecycleOwnerTestClient{ + failbacks: []ops.SwBlockReplicaFailbackObject{cmdFailbackExecutableTarget()}, + } + var got ops.FailbackRuntimeRequest + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := json.NewDecoder(r.Body).Decode(&got); err != nil { + t.Fatalf("decode request: %v", err) + } + _ = json.NewEncoder(w).Encode(ops.FailbackRuntimeResult{ + FailbackStarted: true, + AuthorityEpochAdvanced: true, + SinglePrimaryAfterFailback: true, + PublishTargetSwappedAfterFailback: true, + NoStorageMutation: true, + NoCrossVolumeIdentityChange: true, + EvidenceRefs: []string{"runtime.txt"}, + }) + })) + defer server.Close() + oldFactory := opsFailbackExecutorClientFactory + opsFailbackExecutorClientFactory = func() (ops.FailbackExecutorClient, error) { + return client, nil + } + t.Cleanup(func() { opsFailbackExecutorClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "failback-executor", + "--enable-execution", + "--execution-policy", + "--failback-runtime-url", server.URL, + "--namespace", "kube-system", + }, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if got.VolumeName != "demo-pvc" || + got.ReplicaID != "r1" || + got.RuntimeEndpoint != "http://127.0.0.1:23260/runtime/failback" || + got.TargetDataAddr != "data-r1" || + got.TargetCtrlAddr != "ctrl-r1" || + got.ExpectedCurrentReplicaID != "r2" || + got.ExpectedCurrentEpoch != 7 || + !got.AckEligible || + !got.FrontendFencedBeforeFailback { + t.Fatalf("runtime request=%+v", got) + } + if len(client.failbackStatusWrites) != 1 { + t.Fatalf("failbackStatusWrites=%+v", client.failbackStatusWrites) + } + status := client.failbackStatusWrites[0].status + if status.State != ops.FailbackStateFailedBack || + status.ReasonCode != ops.AuthorityExecutorFailbackReasonCompleted || + !status.FailbackStarted || + !status.AuthorityEpochAdvanced || + !status.SinglePrimaryAfterFailback || + !status.PublishTargetSwappedAfterFailback { + t.Fatalf("status=%+v", status) + } + out := stdout.String() + for _, want := range []string{ + "failback_executor=write_status", + "failback_attempts=1", + "execution_requested=true", + "execution_policy_enabled=true", + "authority_mutation_allowed=true", + "frontend_publication_allowed=false", + "storage_mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsFailbackExecutorGRPCRuntimeWritesFailedBackStatus(t *testing.T) { + client := &lifecycleOwnerTestClient{ + failbacks: []ops.SwBlockReplicaFailbackObject{cmdFailbackExecutableTarget()}, + } + oldFactory := opsFailbackExecutorClientFactory + opsFailbackExecutorClientFactory = func() (ops.FailbackExecutorClient, error) { + return client, nil + } + t.Cleanup(func() { opsFailbackExecutorClientFactory = oldFactory }) + + server := grpc.NewServer() + fake := &cmdFailbackService{} + control.RegisterFailbackServiceServer(server, fake) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + done := make(chan error, 1) + go func() { + done <- server.Serve(ln) + }() + t.Cleanup(func() { + server.Stop() + _ = ln.Close() + <-done + }) + + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "failback-executor", + "--namespace", "kube-system", + "--enable-execution", + "--execution-policy", + "--failback-runtime-grpc-addr", ln.Addr().String(), + }, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + got := fake.request + if got == nil || + got.GetVolumeId() != "pvc-demo" || + got.GetReplicaId() != "r1" || + got.GetTargetDataAddr() != "data-r1" || + got.GetTargetCtrlAddr() != "ctrl-r1" || + got.GetExpectedCurrentReplicaId() != "r2" || + got.GetExpectedCurrentEpoch() != 7 || + !got.GetAckEligible() || + !got.GetFrontendFencedBeforeFailback() || + !got.GetDurableFrontierCovered() || + !got.GetNoCrossVolumeIdentityChange() { + t.Fatalf("grpc request=%+v", got) + } + if len(client.failbackStatusWrites) != 1 { + t.Fatalf("failbackStatusWrites=%+v", client.failbackStatusWrites) + } + status := client.failbackStatusWrites[0].status + if status.State != ops.FailbackStateFailedBack || + status.ReasonCode != ops.AuthorityExecutorFailbackReasonCompleted || + !status.FailbackStarted || + !status.AuthorityEpochAdvanced || + !status.SinglePrimaryAfterFailback || + !status.PublishTargetSwappedAfterFailback { + t.Fatalf("status=%+v", status) + } + out := stdout.String() + for _, want := range []string{ + "failback_executor=write_status", + "failback_attempts=1", + "execution_requested=true", + "execution_policy_enabled=true", + "authority_mutation_allowed=true", + "frontend_publication_allowed=false", + "storage_mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsFailbackExecutorRejectsGRPCRuntimeWithoutEnable(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "failback-executor", "--failback-runtime-grpc-addr", "127.0.0.1:9333"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if !strings.Contains(stderr.String(), "--failback-runtime-grpc-addr requires --enable-execution") { + t.Fatalf("stderr=%s", stderr.String()) + } +} + +func TestOpsFailbackExecutorRejectsAmbiguousRuntimeTransports(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "failback-executor", + "--enable-execution", + "--execution-policy", + "--failback-runtime-url", "http://127.0.0.1:23260/runtime", + "--failback-runtime-grpc-addr", "127.0.0.1:9333", + }, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if !strings.Contains(stderr.String(), "mutually exclusive") { + t.Fatalf("stderr=%s", stderr.String()) + } +} + +func TestOpsFrontendPublicationExecutorWritesDisabledStatus(t *testing.T) { + client := &lifecycleOwnerTestClient{ + frontendTargets: []ops.SwBlockFrontendPublicationObject{cmdFrontendPublicationTarget()}, + } + oldFactory := opsFrontendPublicationExecutorClientFactory + opsFrontendPublicationExecutorClientFactory = func() (ops.FrontendPublicationExecutorClient, error) { + return client, nil + } + t.Cleanup(func() { opsFrontendPublicationExecutorClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "frontend-publication-executor", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.frontendPublicationStatusWrites) != 1 { + t.Fatalf("frontendPublicationStatusWrites=%+v", client.frontendPublicationStatusWrites) + } + status := client.frontendPublicationStatusWrites[0].status + if status.State != ops.FrontendPublicationStateBlocked || + status.ReasonCode != ops.AuthorityExecutorFrontendPublicationReasonDisabled || + status.PublicationMutationAllowed || + status.FrontendPublished || + status.FailbackStarted || + !status.NoStorageMutation { + t.Fatalf("status=%+v", status) + } + out := stdout.String() + for _, want := range []string{ + "frontend_publication_executor=write_status", + "namespace=kube-system", + "targets=1", + "status_writes=1", + "invalid_targets=0", + "frontend_publication_attempts=0", + "failback_attempts=0", + "status_mutation_allowed=true", + "frontend_publication_mutation_allowed=false", + "mutation_allowed=true", + "storage_mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsFrontendPublicationExecutorDryRunDoesNotWriteStatus(t *testing.T) { + client := &lifecycleOwnerTestClient{ + frontendTargets: []ops.SwBlockFrontendPublicationObject{cmdFrontendPublicationTarget()}, + } + oldFactory := opsFrontendPublicationExecutorClientFactory + opsFrontendPublicationExecutorClientFactory = func() (ops.FrontendPublicationExecutorClient, error) { + return client, nil + } + t.Cleanup(func() { opsFrontendPublicationExecutorClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "frontend-publication-executor", "--dry-run", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(client.frontendPublicationStatusWrites) != 0 { + t.Fatalf("dry-run writes=%+v", client.frontendPublicationStatusWrites) + } + out := stdout.String() + for _, want := range []string{ + "frontend_publication_executor=dry_run", + "targets=1", + "status_writes=0", + "frontend_publication_attempts=0", + "failback_attempts=0", + "status_mutation_allowed=false", + "frontend_publication_mutation_allowed=false", + "mutation_allowed=false", + "storage_mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsFrontendPublicationExecutorRejectsRuntimeWithoutEnable(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "frontend-publication-executor", "--frontend-publication-runtime-url", "http://127.0.0.1:23260/runtime"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if !strings.Contains(stderr.String(), "--frontend-publication-runtime-url requires --enable-execution") { + t.Fatalf("stderr=%s", stderr.String()) + } +} + +func TestOpsFrontendPublicationExecutorPolicyBlocksExecution(t *testing.T) { + client := &lifecycleOwnerTestClient{ + frontendTargets: []ops.SwBlockFrontendPublicationObject{cmdFrontendPublicationFailbackExecutableTarget()}, + } + oldFactory := opsFrontendPublicationExecutorClientFactory + opsFrontendPublicationExecutorClientFactory = func() (ops.FrontendPublicationExecutorClient, error) { + return client, nil + } + t.Cleanup(func() { opsFrontendPublicationExecutorClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "frontend-publication-executor", "--enable-execution", "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if !strings.Contains(stderr.String(), "execution is disabled by product policy") { + t.Fatalf("stderr=%s", stderr.String()) + } + if len(client.frontendPublicationStatusWrites) != 0 { + t.Fatalf("policy blocked execution wrote status: %+v", client.frontendPublicationStatusWrites) + } +} + +func TestOpsFrontendPublicationExecutorExecutesFailbackTargetWithExplicitPolicy(t *testing.T) { + client := &lifecycleOwnerTestClient{ + frontendTargets: []ops.SwBlockFrontendPublicationObject{cmdFrontendPublicationFailbackExecutableTarget()}, + } + oldFactory := opsFrontendPublicationExecutorClientFactory + opsFrontendPublicationExecutorClientFactory = func() (ops.FrontendPublicationExecutorClient, error) { + return client, nil + } + t.Cleanup(func() { opsFrontendPublicationExecutorClientFactory = oldFactory }) + + var got ops.FrontendPublicationRuntimeRequest + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := json.NewDecoder(r.Body).Decode(&got); err != nil { + t.Fatalf("decode runtime request: %v", err) + } + _ = json.NewEncoder(w).Encode(ops.FrontendPublicationRuntimeResult{ + FrontendPublished: true, + FailbackStarted: false, + NoStorageMutation: true, + NoCrossVolumeIdentityChange: true, + EvidenceRefs: []string{"frontend-after-failback.txt"}, + }) + })) + defer server.Close() + + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "frontend-publication-executor", + "--enable-execution", + "--execution-policy", + "--frontend-publication-runtime-url", server.URL, + "--namespace", "kube-system", + }, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if got.SourceFailbackName != "demo-pvc-r1-failback" || + got.TargetDataAddr != "data-r1" || + got.TargetCtrlAddr != "ctrl-r1" || + !got.FailbackCompleted || + !got.AuthorityEpochAdvanced || + !got.SinglePrimaryAfterFailback || + !got.PublishTargetSwappedAfterFailback || + got.AckEligible || + got.PrimaryUnchanged { + t.Fatalf("runtime request=%+v", got) + } + if len(client.frontendPublicationStatusWrites) != 1 { + t.Fatalf("frontendPublicationStatusWrites=%+v", client.frontendPublicationStatusWrites) + } + status := client.frontendPublicationStatusWrites[0].status + if status.State != ops.FrontendPublicationStatePublished || + status.ReasonCode != ops.AuthorityExecutorFrontendPublicationReasonPublished || + status.PublicationMutationAllowed || + !status.FrontendPublished || + status.FailbackStarted || + !status.NoStorageMutation || + !status.NoCrossVolumeIdentityChange { + t.Fatalf("status=%+v", status) + } + out := stdout.String() + for _, want := range []string{ + "frontend_publication_executor=write_status", + "targets=1", + "status_writes=1", + "invalid_targets=0", + "frontend_publication_attempts=1", + "failback_attempts=0", + "storage_mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsAuthorityExecutorExecutionPolicyBlocksWhenAckTargetMissing(t *testing.T) { + client := &lifecycleOwnerTestClient{ + volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockVolumeKind, + Namespace: "kube-system", + Name: "returned", + }, + Status: ops.SwBlockVolumeCRDStatus{ + VolumeID: "pvc-1", + PVCName: "demo", + ReplicaReintegrations: []ops.SwBlockVolumeCRDReturnedReplica{{ + ReplicaID: "r1", + State: ops.ReturnedReplicaStateFenced, + ReasonCode: ops.ReasonReturnedReplicaFrontendFenced, + FrontendFenced: true, + FrontendPrimaryReady: false, + AckEligibilityKnown: true, + AckEligible: false, + DurableFrontierKnown: true, + DurableFrontierLSN: 52, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 52, + }}, + ExecutorContracts: []ops.SwBlockVolumeCRDExecutorContract{{ + ActionType: ops.ManagedVolumeActionReintegrateReturned, + ReplicaID: "r1", + Decision: ops.ReturnedReplicaExecutorContractDisabled, + Reason: ops.ReturnedReplicaExecutorContractReasonExecutorDisabled, + OwnerExecutor: "authority_recovery_executor", + ExecutionEnabled: false, + MutationAllowed: false, + PreflightDecision: ops.ReturnedReplicaExecutorPreflightReady, + PreflightReason: ops.ReturnedReplicaExecutorPreflightReasonSatisfied, + AllowedMutationClass: []string{ops.AuthorityExecutorAllowedMutationAckEligibility}, + ForbiddenMutationClass: []string{"frontend_publication", "rebuild_traffic", "failback"}, + }}, + }, + }}, + } + oldFactory := opsAuthorityExecutorClientFactory + opsAuthorityExecutorClientFactory = func() (ops.AuthorityExecutorClient, error) { + return client, nil + } + t.Cleanup(func() { opsAuthorityExecutorClientFactory = oldFactory }) + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "authority-executor", "--enable-execution", "--execution-policy"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + out := stdout.String() + for _, want := range []string{ + "authority_executor=blocked", + "execution_requested=true", + "execution_policy_enabled=true", + "ack_eligibility_target_missing=1", + "mutation_attempts=0", + "ack_eligibility_mutation_attempts=0", + "mutation_allowed=false", + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsClusterMasterAPIUsesSharedInClusterNodeEvidenceEnrichment(t *testing.T) { + masterAddr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + oldFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return fakeNodeEvidenceEnricher{}, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "cluster", "--master-api", masterAddr, "-o", "json"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + out := stdout.String() + for _, want := range []string{ + `"kubernetes_node": "m02"`, + `"ready": false`, + `"reason": "node_not_ready"`, + } { + if !strings.Contains(out, want) { + t.Fatalf("stdout missing %q:\n%s", want, out) + } + } +} + +func TestOpsReportMasterAPIUsesSharedInClusterNodeEvidenceEnrichment(t *testing.T) { + masterAddr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + oldFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return fakeNodeEvidenceEnricher{}, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + + outDir := t.TempDir() + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "report", "--master-api", masterAddr, "--out", outDir}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + raw, err := os.ReadFile(filepath.Join(outDir, ops.ObservationReportJSONArtifact)) + if err != nil { + t.Fatal(err) + } + out := string(raw) + for _, want := range []string{ + `"kubernetes_node": "m02"`, + `"ready": false`, + `"reason": "node_not_ready"`, + } { + if !strings.Contains(out, want) { + t.Fatalf("report missing %q:\n%s", want, out) + } + } +} + +func TestLoadObservationVolumeUsesSharedInClusterNodeEvidenceEnrichment(t *testing.T) { + oldFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return fakeNodeEvidenceEnricher{}, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + oldRunCommand := opsInventoryRunCommand + opsInventoryRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl -n default get pvc -o json": cmdSinglePVCListJSON, + "kubectl get pv -o json": cmdSinglePVListJSON, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": cmdSingleDeploymentListJSON, + }) + t.Cleanup(func() { opsInventoryRunCommand = oldRunCommand }) + + var stderr bytes.Buffer + cluster, _, code := loadObservationVolume("sw-block ops explain", []string{"volume", "--namespace", "default", "--product-revision", "product-rev", "pvc-live"}, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s cluster=%+v", code, stderr.String(), cluster) + } + if len(cluster.Nodes) != 1 || cluster.Nodes[0].KubernetesNode != "m02" { + t.Fatalf("cluster nodes=%+v", cluster.Nodes) + } + if !cmdConditionReason(cluster.Nodes[0].Conditions, ops.ReasonNodeNotReady) { + t.Fatalf("volume loader did not enrich node evidence: %+v", cluster.Nodes[0]) + } +} + +func TestOpsExplainProjectsDeletingCRFromCleanupSummary(t *testing.T) { + oldInventoryRun := opsInventoryRunCommand + opsInventoryRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl -n default get pvc -o json": `{"items":[]}`, + "kubectl get pv -o json": `{"items":[]}`, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": `{"items":[]}`, + }) + t.Cleanup(func() { opsInventoryRunCommand = oldInventoryRun }) + + oldNodeFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return fakeNodeEvidenceEnricher{}, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldNodeFactory }) + + deletingAt := time.Date(2026, 6, 17, 8, 0, 0, 0, time.UTC) + oldVolumeSourceFactory := opsSwBlockVolumeSourceFactory + opsSwBlockVolumeSourceFactory = func() (ops.OperatorSwBlockVolumeSource, error) { + return &lifecycleOwnerTestClient{volumes: []ops.SwBlockVolumeObject{{ + Ref: ops.OperatorObjectRef{ + Namespace: "default", + Name: "delete-pvc", + }, + Finalizers: []string{ops.SwBlockVolumeFinalizerName}, + DeletionTimestamp: &deletingAt, + Spec: ops.SwBlockVolumeSpec{PVCName: "delete-pvc"}, + Status: ops.SwBlockVolumeCRDStatus{ + VolumeID: "pvc-delete", + PVCName: "delete-pvc", + }, + }}}, nil + } + t.Cleanup(func() { opsSwBlockVolumeSourceFactory = oldVolumeSourceFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + + cleanupSummary := filepath.Join(t.TempDir(), "cleanup-summary.txt") + cleanupObservedAt := time.Now().UTC().Format(time.RFC3339) + if err := os.WriteFile(cleanupSummary, []byte(strings.Join([]string{ + "cleanup_status=failed", + "iscsi_residue_count=1", + "failure_count=1", + "reason_codes=iscsi_node_records_present", + "cleanup_observed_at=" + cleanupObservedAt, + }, "\n")), 0o600); err != nil { + t.Fatal(err) + } + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "explain", "volume", "--namespace", "default", "--cleanup-summary", cleanupSummary, "delete-pvc"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + out := stdout.String() + for _, want := range []string{ + "managed_volume pvc-delete status=blocked reason=iscsi_node_records_present", + "managed_volume_delete_safety state=blocked decision=rejected reason=iscsi_node_records_present", + "managed_volume_action safe_k8s.release_swblockvolume_finalizer mode=dry_run", + } { + if !strings.Contains(out, want) { + t.Fatalf("explain missing %q:\n%s", want, out) + } + } +} + +func TestOpsDashboardMasterAPIUsesSharedInClusterNodeEvidenceEnrichment(t *testing.T) { + masterAddr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + oldFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return fakeNodeEvidenceEnricher{}, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + + addr := freeTCPAddr(t) + var stdout, stderr bytes.Buffer + done := make(chan int, 1) + go func() { + done <- run([]string{ + "ops", "dashboard", + "--master-api", masterAddr, + "--listen", addr, + "--serve-duration", "1500ms", + }, &stdout, &stderr) + }() + + body := waitForHTTPContains(t, "http://"+addr+"/cluster-evidence.json", `"reason": "node_not_ready"`) + if !strings.Contains(body, `"kubernetes_node": "m02"`) || !strings.Contains(body, `"ready": false`) { + t.Fatalf("dashboard cluster evidence missing enriched node:\n%s", body) + } + select { + case code := <-done: + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + case <-time.After(2 * time.Second): + t.Fatalf("dashboard command did not stop; stdout=%s stderr=%s", stdout.String(), stderr.String()) + } +} + +func TestLiveNodeEvidenceUsesHelmNamespaceWhenAppNamespaceDefaults(t *testing.T) { + recorder := &recordingNodeEvidenceEnricher{} + oldFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return recorder, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + + _, err := enrichLiveObservationCluster("default", time.Second, true, ops.ClusterEvidence{}) + if err != nil { + t.Fatalf("enrich: %v", err) + } + if recorder.namespace != "kube-system" { + t.Fatalf("node evidence namespace=%q want kube-system", recorder.namespace) + } +} + +func TestLiveNodeEvidenceNamespaceHonorsHelmNamespaceOverride(t *testing.T) { + recorder := &recordingNodeEvidenceEnricher{} + oldFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return recorder, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + t.Setenv("SW_BLOCK_HELM_NAMESPACE", "sw-system") + + _, err := enrichLiveObservationCluster("default", time.Second, true, ops.ClusterEvidence{}) + if err != nil { + t.Fatalf("enrich: %v", err) + } + if recorder.namespace != "sw-system" { + t.Fatalf("node evidence namespace=%q want sw-system", recorder.namespace) + } +} + +func TestLiveNodeEvidenceUsesExplicitNonDefaultNamespace(t *testing.T) { + recorder := &recordingNodeEvidenceEnricher{} + oldFactory := opsNodeEvidenceEnricherFactory + opsNodeEvidenceEnricherFactory = func() (ops.OperatorNodeEvidenceEnricher, error) { + return recorder, nil + } + t.Cleanup(func() { opsNodeEvidenceEnricherFactory = oldFactory }) + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + + _, err := enrichLiveObservationCluster("sw-system", time.Second, true, ops.ClusterEvidence{}) + if err != nil { + t.Fatalf("enrich: %v", err) + } + if recorder.namespace != "sw-system" { + t.Fatalf("node evidence namespace=%q want sw-system", recorder.namespace) + } +} + +type fakeNodeEvidenceEnricher struct{} + +func (fakeNodeEvidenceEnricher) EnrichNodeEvidence(_ context.Context, _ string, cluster ops.ClusterEvidence) (ops.ClusterEvidence, error) { + cluster.Nodes = []ops.NodeEvidence{{ + NodeName: "m02", + KubernetesNode: "m02", + Ready: false, + Schedulable: true, + Conditions: []ops.ObservationCondition{{ + Type: ops.ConditionReady, + Status: "Unknown", + Reason: ops.ReasonNodeNotReady, + Severity: "warning", + Message: "Kubernetes node Ready condition is not True", + }}, + }} + return cluster, nil +} + +type recordingNodeEvidenceEnricher struct { + namespace string +} + +func (r *recordingNodeEvidenceEnricher) EnrichNodeEvidence(_ context.Context, namespace string, cluster ops.ClusterEvidence) (ops.ClusterEvidence, error) { + r.namespace = namespace + return cluster, nil +} + +func cmdConditionReason(conditions []ops.ObservationCondition, reason string) bool { + for _, condition := range conditions { + if condition.Reason == reason { + return true + } + } + return false +} + +type operatorStatusTestWriter struct { + cluster ops.SwBlockClusterCRDStatus + volumes []operatorStatusTestVolumeWrite +} + +type operatorStatusTestVolumeWrite struct { + ref ops.OperatorObjectRef + status ops.SwBlockVolumeCRDStatus +} + +func cmdFrontendPublicationEligibility() ops.SwBlockReplicaEligibilityObject { + return ops.SwBlockReplicaEligibilityObject{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockReplicaEligibilityKind, + Namespace: "kube-system", + Name: "demo-pvc-r2-ack", + }, + Spec: ops.SwBlockReplicaEligibilitySpec{ + VolumeName: "demo-pvc", + VolumeID: "pvc-demo", + PVCName: "demo-pvc", + ReplicaID: "r2", + }, + Status: ops.SwBlockReplicaEligibilityCRDStatus{ + ReasonCode: ops.ReturnedReplicaExecutorPreflightReasonAckEligible, + AckEligibilityKnown: true, + AckEligible: true, + FrontendFencedAfterExecution: true, + PrimaryUnchanged: true, + DurableFrontierCovered: true, + NoCrossVolumeIdentityChange: true, + FrontendPublicationDecision: ops.AuthorityExecutorPublicationDecisionDisabled, + FrontendPublicationReason: ops.AuthorityExecutorFrontendPublicationReasonDisabled, + FrontendPublicationMutationAllowed: false, + }, + } +} + +func cmdFrontendPublicationTarget() ops.SwBlockFrontendPublicationObject { + return ops.SwBlockFrontendPublicationObject{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockFrontendPublicationKind, + Namespace: "kube-system", + Name: "demo-pvc-r2-frontend-publication", + }, + Spec: ops.SwBlockFrontendPublicationSpec{ + VolumeName: "demo-pvc", + VolumeID: "pvc-demo", + PVCName: "demo-pvc", + ReplicaID: "r2", + SourceEligibilityName: "demo-pvc-r2-ack", + AckEligibilityKnown: true, + AckEligible: true, + FrontendFencedAfterExecution: true, + PrimaryUnchanged: true, + DurableFrontierCovered: true, + NoCrossVolumeIdentityChange: true, + FrontendPublicationDecision: ops.AuthorityExecutorPublicationDecisionDisabled, + FrontendPublicationReason: ops.AuthorityExecutorFrontendPublicationReasonDisabled, + FrontendPublicationMutationAllowed: false, + }, + } +} + +func cmdFrontendPublicationFailbackExecutableTarget() ops.SwBlockFrontendPublicationObject { + return ops.SwBlockFrontendPublicationObject{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockFrontendPublicationKind, + Namespace: "kube-system", + Name: "demo-pvc-r1-frontend-publication", + }, + Spec: ops.SwBlockFrontendPublicationSpec{ + VolumeName: "demo-pvc", + VolumeID: "pvc-demo", + PVCName: "demo-pvc", + ReplicaID: "r1", + TargetDataAddr: "data-r1", + TargetCtrlAddr: "ctrl-r1", + SourceFailbackName: "demo-pvc-r1-failback", + NoCrossVolumeIdentityChange: true, + FailbackCompleted: true, + AuthorityEpochAdvanced: true, + SinglePrimaryAfterFailback: true, + PublishTargetSwappedAfterFailback: true, + FrontendPublicationDecision: ops.AuthorityExecutorPublicationDecisionEnabled, + FrontendPublicationReason: "frontend_publication_requested", + FrontendPublicationMutationAllowed: true, + RuntimeEndpoint: "http://127.0.0.1:23260/runtime/frontend-publication", + }, + } +} + +func cmdFailbackTarget() ops.SwBlockReplicaFailbackObject { + return ops.SwBlockReplicaFailbackObject{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockReplicaFailbackKind, + Namespace: "kube-system", + Name: "demo-pvc-r1-failback", + }, + Spec: ops.SwBlockReplicaFailbackSpec{ + VolumeName: "demo-pvc", + VolumeID: "pvc-demo", + PVCName: "demo-pvc", + ReplicaID: "r1", + TargetDataAddr: "data-r1", + TargetCtrlAddr: "ctrl-r1", + AckEligible: true, + FrontendFencedBeforeFailback: true, + DurableFrontierCovered: true, + NoCrossVolumeIdentityChange: true, + FailbackDecision: ops.AuthorityExecutorFailbackDecisionDisabled, + FailbackReason: ops.AuthorityExecutorFailbackReasonDisabled, + FailbackMutationAllowed: false, + }, + } +} + +func cmdFailbackExecutableTarget() ops.SwBlockReplicaFailbackObject { + target := cmdFailbackTarget() + target.Spec.FailbackDecision = ops.AuthorityExecutorFailbackDecisionEnabled + target.Spec.FailbackReason = "failback_requested" + target.Spec.FailbackMutationAllowed = true + target.Spec.RuntimeEndpoint = "http://127.0.0.1:23260/runtime/failback" + target.Spec.ExpectedCurrentReplicaID = "r2" + target.Spec.ExpectedCurrentEpoch = 7 + return target +} + +func cmdTerminalFailbackTarget() ops.SwBlockReplicaFailbackObject { + target := cmdFailbackTarget() + target.Status = ops.SwBlockReplicaFailbackCRDStatus{ + Executor: "failback-executor", + State: ops.FailbackStateFailedBack, + ReasonCode: ops.AuthorityExecutorFailbackReasonCompleted, + FailbackMutationAllowed: false, + FailbackStarted: true, + AuthorityEpochAdvanced: true, + SinglePrimaryAfterFailback: true, + PublishTargetSwappedAfterFailback: true, + NoCrossVolumeIdentityChange: true, + } + return target +} + +func cmdFailbackTargetVolume() ops.SwBlockVolumeObject { + return ops.SwBlockVolumeObject{ + Ref: ops.OperatorObjectRef{ + APIVersion: ops.SwBlockVolumeAPIVersion, + Kind: ops.SwBlockVolumeKind, + Namespace: "kube-system", + Name: "demo-pvc", + }, + Status: ops.SwBlockVolumeCRDStatus{ + VolumeID: "pvc-demo", + PVCName: "demo-pvc", + PrimaryReplicaID: "r2", + AuthorityEpoch: 7, + ReplicaReintegrations: []ops.SwBlockVolumeCRDReturnedReplica{{ + ReplicaID: "r1", + State: ops.ReturnedReplicaStateFenced, + FrontendFenced: true, + FrontendPrimaryReady: false, + AckEligibilityKnown: true, + AckEligible: true, + DurableFrontierKnown: true, + DurableFrontierLSN: 52, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 52, + TargetDataAddr: "data-r1", + TargetCtrlAddr: "ctrl-r1", + }}, + ExecutorContracts: []ops.SwBlockVolumeCRDExecutorContract{{ + ActionType: ops.ManagedVolumeActionFailbackReturned, + ReplicaID: "r1", + Decision: ops.ReturnedReplicaExecutorContractDisabled, + Reason: ops.ReturnedReplicaExecutorContractReasonExecutorDisabled, + PreflightDecision: ops.ReturnedReplicaExecutorPreflightReady, + PreflightReason: ops.ReturnedReplicaExecutorPreflightReasonSatisfied, + AllowedMutationClass: []string{"failback"}, + }}, + }, + } +} + +func (w *operatorStatusTestWriter) WriteClusterStatus(_ context.Context, _ ops.OperatorObjectRef, status ops.SwBlockClusterCRDStatus) error { + w.cluster = status + return nil +} + +func (w *operatorStatusTestWriter) WriteVolumeStatus(_ context.Context, ref ops.OperatorObjectRef, status ops.SwBlockVolumeCRDStatus) error { + w.volumes = append(w.volumes, operatorStatusTestVolumeWrite{ref: ref, status: status}) + return nil +} + +type lifecycleOwnerTestClient struct { + volumes []ops.SwBlockVolumeObject + eligibilities []ops.SwBlockReplicaEligibilityObject + rebuilds []ops.SwBlockReplicaRebuildObject + failbacks []ops.SwBlockReplicaFailbackObject + frontendTargets []ops.SwBlockFrontendPublicationObject + patches []lifecycleOwnerTestPatch + events []ops.OperatorKubernetesEvent + eligibilityWrites []lifecycleOwnerTestEligibilityWrite + rebuildWrites []lifecycleOwnerTestRebuildWrite + rebuildCreates []ops.SwBlockReplicaRebuildObject + failbackCreates []ops.SwBlockReplicaFailbackObject + failbackStatusWrites []lifecycleOwnerTestFailbackWrite + frontendPublicationCreates []ops.SwBlockFrontendPublicationObject + frontendPublicationStatusWrites []lifecycleOwnerTestFrontendPublicationWrite +} + +type cmdFailbackService struct { + control.UnimplementedFailbackServiceServer + request *control.FailbackRequest +} + +func (s *cmdFailbackService) ExecuteFailback(_ context.Context, req *control.FailbackRequest) (*control.FailbackResponse, error) { + s.request = req + return &control.FailbackResponse{ + FailbackStarted: true, + AuthorityEpochAdvanced: true, + SinglePrimaryAfterFailback: true, + PublishTargetSwappedAfterFailback: true, + NoStorageMutation: true, + NoCrossVolumeIdentityChange: true, + EvidenceRefs: []string{"grpc-runtime.txt"}, + }, nil +} + +type lifecycleOwnerTestPatch struct { + ref ops.OperatorObjectRef + finalizers []string +} + +type lifecycleOwnerTestEligibilityWrite struct { + ref ops.OperatorObjectRef + status ops.SwBlockReplicaEligibilityCRDStatus +} + +type lifecycleOwnerTestRebuildWrite struct { + ref ops.OperatorObjectRef + status ops.SwBlockReplicaRebuildCRDStatus +} + +type lifecycleOwnerTestFailbackWrite struct { + ref ops.OperatorObjectRef + status ops.SwBlockReplicaFailbackCRDStatus +} + +type lifecycleOwnerTestFrontendPublicationWrite struct { + ref ops.OperatorObjectRef + status ops.SwBlockFrontendPublicationCRDStatus +} + +func (c *lifecycleOwnerTestClient) ListSwBlockVolumes(_ context.Context, _ string) ([]ops.SwBlockVolumeObject, error) { + return append([]ops.SwBlockVolumeObject(nil), c.volumes...), nil +} + +func (c *lifecycleOwnerTestClient) ListSwBlockReplicaEligibilities(_ context.Context, _ string) ([]ops.SwBlockReplicaEligibilityObject, error) { + return append([]ops.SwBlockReplicaEligibilityObject(nil), c.eligibilities...), nil +} + +func (c *lifecycleOwnerTestClient) ListSwBlockReplicaRebuilds(_ context.Context, _ string) ([]ops.SwBlockReplicaRebuildObject, error) { + return append([]ops.SwBlockReplicaRebuildObject(nil), c.rebuilds...), nil +} + +func (c *lifecycleOwnerTestClient) ListSwBlockReplicaFailbacks(_ context.Context, _ string) ([]ops.SwBlockReplicaFailbackObject, error) { + return append([]ops.SwBlockReplicaFailbackObject(nil), c.failbacks...), nil +} + +func (c *lifecycleOwnerTestClient) ListSwBlockFrontendPublications(_ context.Context, _ string) ([]ops.SwBlockFrontendPublicationObject, error) { + return append([]ops.SwBlockFrontendPublicationObject(nil), c.frontendTargets...), nil +} + +func (c *lifecycleOwnerTestClient) WriteReplicaEligibilityStatus(_ context.Context, ref ops.OperatorObjectRef, status ops.SwBlockReplicaEligibilityCRDStatus) error { + c.eligibilityWrites = append(c.eligibilityWrites, lifecycleOwnerTestEligibilityWrite{ref: ref, status: status}) + return nil +} + +func (c *lifecycleOwnerTestClient) WriteReplicaRebuildStatus(_ context.Context, ref ops.OperatorObjectRef, status ops.SwBlockReplicaRebuildCRDStatus) error { + c.rebuildWrites = append(c.rebuildWrites, lifecycleOwnerTestRebuildWrite{ref: ref, status: status}) + return nil +} + +func (c *lifecycleOwnerTestClient) WriteReplicaFailbackStatus(_ context.Context, ref ops.OperatorObjectRef, status ops.SwBlockReplicaFailbackCRDStatus) error { + c.failbackStatusWrites = append(c.failbackStatusWrites, lifecycleOwnerTestFailbackWrite{ref: ref, status: status}) + return nil +} + +func (c *lifecycleOwnerTestClient) WriteFrontendPublicationStatus(_ context.Context, ref ops.OperatorObjectRef, status ops.SwBlockFrontendPublicationCRDStatus) error { + c.frontendPublicationStatusWrites = append(c.frontendPublicationStatusWrites, lifecycleOwnerTestFrontendPublicationWrite{ref: ref, status: status}) + return nil +} + +func (c *lifecycleOwnerTestClient) CreateSwBlockReplicaRebuild(_ context.Context, _ string, obj ops.SwBlockReplicaRebuildObject) error { + c.rebuildCreates = append(c.rebuildCreates, obj) + return nil +} + +func (c *lifecycleOwnerTestClient) CreateSwBlockReplicaFailback(_ context.Context, _ string, obj ops.SwBlockReplicaFailbackObject) error { + c.failbackCreates = append(c.failbackCreates, obj) + return nil +} + +func (c *lifecycleOwnerTestClient) CreateSwBlockFrontendPublication(_ context.Context, _ string, obj ops.SwBlockFrontendPublicationObject) error { + c.frontendPublicationCreates = append(c.frontendPublicationCreates, obj) + return nil +} + +func (c *lifecycleOwnerTestClient) PatchSwBlockVolumeFinalizers(_ context.Context, ref ops.OperatorObjectRef, finalizers []string) error { + c.patches = append(c.patches, lifecycleOwnerTestPatch{ + ref: ref, + finalizers: append([]string(nil), finalizers...), + }) + return nil +} + +func (c *lifecycleOwnerTestClient) EmitEvent(_ context.Context, event ops.OperatorKubernetesEvent) error { + c.events = append(c.events, event) + return nil +} + +func TestOpsInventoryRejectsBadRequiredFrontierFlag(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "inventory", "--out", t.TempDir(), "--required-frontier", "pvc-a=not-a-number"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d want %d", code, ops.VolumeStatusExitInvalid) + } + if !strings.Contains(stderr.String(), "parse required frontier lsn") { + t.Fatalf("stderr=%s stdout=%s", stderr.String(), stdout.String()) + } +} + +func TestOpsInventoryRejectsBadClaimProfile(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "inventory", "--out", t.TempDir(), "--claim-profile", "wishful-ha"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d want %d", code, ops.VolumeStatusExitInvalid) + } + if !strings.Contains(stderr.String(), "--claim-profile") { + t.Fatalf("stderr=%s stdout=%s", stderr.String(), stdout.String()) + } + if !strings.Contains(stderr.String(), ops.PromotionClaimStage2ISCSIALUAMultipath) { + t.Fatalf("stderr should list stage2 profile: %s", stderr.String()) + } +} + +func TestOpsInventoryAcceptsStage2ClaimProfile(t *testing.T) { + oldRunCommand := opsInventoryRunCommand + opsInventoryRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl -n default get pvc -o json": `{"items":[]}`, + "kubectl get pv -o json": `{"items":[]}`, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": `{"items":[]}`, + }) + defer func() { opsInventoryRunCommand = oldRunCommand }() + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "inventory", "--out", t.TempDir(), "--claim-profile", ops.PromotionClaimStage2ISCSIALUAMultipath}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d want %d stderr=%s stdout=%s", code, ops.VolumeStatusExitOK, stderr.String(), stdout.String()) + } + if strings.Contains(stderr.String(), "--claim-profile") { + t.Fatalf("stage2 claim profile should pass validation: stderr=%s stdout=%s", stderr.String(), stdout.String()) + } +} + +func TestOpsGenerateHelmValuesSingleNodeFromKubernetes(t *testing.T) { + oldRunCommand := opsGenerateHelmValuesRunCommand + opsGenerateHelmValuesRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl get nodes -o wide --no-headers": cmdHelmNodeWide, + }) + defer func() { opsGenerateHelmValuesRunCommand = oldRunCommand }() + + outPath := filepath.Join(t.TempDir(), "values.yaml") + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "generate-helm-values", + "--out", outPath, + "--target-node", "m02", + "--node-limit", "1", + "--image", "ghcr.io/seaweedfs/seaweed-block:sha-test", + "--csi-image", "ghcr.io/seaweedfs/seaweed-block-csi:sha-test", + }, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "helm_values_status=ok", + "network_mode=loopback", + "ready_kubernetes_nodes=1", + "discovered_kubernetes_nodes=3", + "target_node=m02", + "restart_persistence_mode=ephemeral", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("stdout missing %q:\n%s", want, stdout.String()) + } + } + values, err := os.ReadFile(outPath) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "repository: ghcr.io/seaweedfs/seaweed-block", + "tag: sha-test", + "externalISCSI: false", + "externalNVMe: false", + "externalStatus: false", + "rejectLoopbackPublishTargets: false", + "restartPersistence:", + "mode: ephemeral", + "expectedSlotsPerVolume: 1", + "enabled: false", + "name: m02", + "kubernetesNode: m02", + "internalIP: 127.0.0.1", + "dataPort: 19101", + "controlPort: 19102", + "launcherDurableImplFlag: false", + "launcherReplicationAckFlag: false", + } { + if !strings.Contains(string(values), want) { + t.Fatalf("values missing %q:\n%s", want, values) + } + } +} + +func TestOpsGenerateHelmValuesMultiNodeExternalISCSI(t *testing.T) { + oldRunCommand := opsGenerateHelmValuesRunCommand + opsGenerateHelmValuesRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl get nodes -o wide --no-headers": cmdHelmNodeWide, + }) + defer func() { opsGenerateHelmValuesRunCommand = oldRunCommand }() + + outPath := filepath.Join(t.TempDir(), "values.yaml") + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "generate-helm-values", + "--out", outPath, + "--replication-factor", "3", + "--ack-profile", "sync-quorum", + "--chap-secret", "fixed-chap-secret", + "--stage2-multipath", + }, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "network_mode=external-iscsi", + "ready_kubernetes_nodes=3", + "external_iscsi=true", + "external_nvme=false", + "chap_enabled=true", + "protocol=iscsi", + "ack_profile=sync-quorum", + "restart_persistence_mode=ephemeral", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("stdout missing %q:\n%s", want, stdout.String()) + } + } + values, err := os.ReadFile(outPath) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "replicationFactor: 3", + "ackProfile: sync-quorum", + "expectedSlotsPerVolume: 3", + "externalISCSI: true", + "externalNVMe: false", + "externalStatus: false", + "rejectLoopbackPublishTargets: true", + "restartPersistence:", + "mode: ephemeral", + "enabled: true", + "secret: fixed-chap-secret", + "name: m01", + "internalIP: 192.168.1.181", + "dataPort: 19101", + "controlPort: 19102", + "name: m02", + "internalIP: 192.168.1.184", + "dataPort: 19103", + "controlPort: 19104", + "name: tp01", + "internalIP: 192.168.1.188", + "dataPort: 19105", + "controlPort: 19106", + "launcherDurableImplFlag: false", + "launcherReplicationAckFlag: false", + } { + if !strings.Contains(string(values), want) { + t.Fatalf("values missing %q:\n%s", want, values) + } + } + if strings.Contains(string(values), "dataPort: 3260") { + t.Fatalf("values must not assign dataPort 3260 because it collides with iSCSI listener port:\n%s", values) + } +} + +func TestOpsGenerateHelmValuesMultiNodeExternalNVMe(t *testing.T) { + oldRunCommand := opsGenerateHelmValuesRunCommand + opsGenerateHelmValuesRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl get nodes -o wide --no-headers": cmdHelmNodeWide, + }) + defer func() { opsGenerateHelmValuesRunCommand = oldRunCommand }() + + outPath := filepath.Join(t.TempDir(), "values.yaml") + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "generate-helm-values", + "--out", outPath, + "--replication-factor", "3", + "--protocol", "nvme", + }, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "network_mode=external-nvme", + "ready_kubernetes_nodes=3", + "external_iscsi=false", + "external_nvme=true", + "chap_enabled=false", + "protocol=nvme", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("stdout missing %q:\n%s", want, stdout.String()) + } + } + values, err := os.ReadFile(outPath) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "replicationFactor: 3", + "protocol: nvme", + "externalISCSI: false", + "externalNVMe: true", + "externalStatus: false", + "rejectLoopbackPublishTargets: true", + "enabled: false", + "create: false", + "secret: \"\"", + "name: m01", + "internalIP: 192.168.1.181", + "name: m02", + "internalIP: 192.168.1.184", + "name: tp01", + "internalIP: 192.168.1.188", + } { + if !strings.Contains(string(values), want) { + t.Fatalf("values missing %q:\n%s", want, values) + } + } + if strings.Contains(string(values), "externalISCSI: true") || strings.Contains(string(values), "secret: fixed-chap-secret") { + t.Fatalf("nvme values must not enable iSCSI or generate CHAP secret:\n%s", values) + } +} + +func TestOpsGenerateHelmValuesMultiNodeNVMeFrontendIPMap(t *testing.T) { + oldRunCommand := opsGenerateHelmValuesRunCommand + opsGenerateHelmValuesRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl get nodes -o wide --no-headers": cmdHelmNodeWide, + }) + defer func() { opsGenerateHelmValuesRunCommand = oldRunCommand }() + + outPath := filepath.Join(t.TempDir(), "values.yaml") + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "generate-helm-values", + "--out", outPath, + "--replication-factor", "3", + "--protocol", "nvme", + "--frontend-ip-map", "m01=10.0.0.181,m02=10.0.0.184,tp01=10.0.0.188", + "--frontend-network-class", "100gbe_tcp", + }, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "network_mode=external-nvme", + "frontend_ip_map=m01=10.0.0.181,m02=10.0.0.184,tp01=10.0.0.188", + "frontend_network_class=100gbe_tcp", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("stdout missing %q:\n%s", want, stdout.String()) + } + } + values, err := os.ReadFile(outPath) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "name: m01", + "internalIP: 192.168.1.181", + "managementIP: 192.168.1.181", + "frontendIP: 10.0.0.181", + "frontendNetworkClass: 100gbe_tcp", + "name: m02", + "internalIP: 192.168.1.184", + "managementIP: 192.168.1.184", + "frontendIP: 10.0.0.184", + "name: tp01", + "internalIP: 192.168.1.188", + "managementIP: 192.168.1.188", + "frontendIP: 10.0.0.188", + } { + if !strings.Contains(string(values), want) { + t.Fatalf("values missing %q:\n%s", want, values) + } + } +} + +func TestPhase165_OpsGenerateHelmValuesNVMERDMA(t *testing.T) { + oldRunCommand := opsGenerateHelmValuesRunCommand + opsGenerateHelmValuesRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl get nodes -o wide --no-headers": cmdHelmNodeWide, + }) + defer func() { opsGenerateHelmValuesRunCommand = oldRunCommand }() + + outPath := filepath.Join(t.TempDir(), "values.yaml") + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "generate-helm-values", "--out", outPath, "--replication-factor", "1", + "--protocol", "nvme", "--nvme-transport", "rdma", + "--frontend-ip-map", "m01=10.0.0.181,m02=10.0.0.184,tp01=10.0.0.188", + "--frontend-network-class", "100gbe_roce", + }, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{"network_mode=external-nvme", "protocol=nvme", "nvme_transport=rdma", "frontend_network_class=100gbe_roce"} { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("stdout missing %q:\n%s", want, stdout.String()) + } + } + values, err := os.ReadFile(outPath) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"protocol: nvme", "nvmeTransport: rdma", "externalNVMe: true", "frontendIP: 10.0.0.181", "frontendNetworkClass: 100gbe_roce"} { + if !strings.Contains(string(values), want) { + t.Fatalf("values missing %q:\n%s", want, values) + } + } +} + +func TestPhase165_OpsGenerateHelmValuesNVMERDMARequiresRoCEMap(t *testing.T) { + for _, args := range [][]string{ + {"--protocol", "iscsi", "--nvme-transport", "rdma"}, + {"--protocol", "nvme", "--nvme-transport", "rdma"}, + {"--protocol", "nvme", "--nvme-transport", "rdma", "--frontend-ip-map", "m01=10.0.0.181", "--frontend-network-class", "100gbe_tcp"}, + } { + var stdout, stderr bytes.Buffer + base := []string{"ops", "generate-helm-values", "--out", filepath.Join(t.TempDir(), "values.yaml")} + code := run(append(base, args...), &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("args=%v exit=%d want invalid stdout=%s stderr=%s", args, code, stdout.String(), stderr.String()) + } + } +} + +func TestOpsGenerateHelmValuesRejectsIncompleteFrontendIPMap(t *testing.T) { + oldRunCommand := opsGenerateHelmValuesRunCommand + opsGenerateHelmValuesRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl get nodes -o wide --no-headers": cmdHelmNodeWide, + }) + defer func() { opsGenerateHelmValuesRunCommand = oldRunCommand }() + + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "generate-helm-values", + "--out", filepath.Join(t.TempDir(), "values.yaml"), + "--replication-factor", "3", + "--protocol", "nvme", + "--frontend-ip-map", "m01=10.0.0.181,m02=10.0.0.184", + "--frontend-network-class", "100gbe_tcp", + }, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d want invalid stdout=%s stderr=%s", code, stdout.String(), stderr.String()) + } + if !strings.Contains(stderr.String(), `--frontend-ip-map missing selected node "tp01"`) { + t.Fatalf("stderr=%s", stderr.String()) + } +} + +func TestNodeEvidenceFromWirePreservesFrontendAddress(t *testing.T) { + node := nodeEvidenceFromWire(&control.NodeEvidence{ + NodeName: "m01", + InternalIp: "192.168.1.181", + FrontendIp: "10.0.0.1", + FrontendNetworkClass: "100gbe_tcp", + }) + if node.FrontendIP != "10.0.0.1" || node.FrontendNetworkClass != "100gbe_tcp" { + t.Fatalf("frontend address evidence dropped: %+v", node) + } +} + +func TestReplicaEvidenceFromWirePreservesFrontendTransport(t *testing.T) { + replica := replicaEvidenceFromWire(&control.ReplicaEvidence{ + FrontendProtocol: "nvme", + FrontendTransport: "rdma", + FrontendAddr: "10.0.0.3:4420", + }) + if replica.FrontendTransport != "rdma" { + t.Fatalf("frontend transport evidence dropped: %+v", replica) + } +} + +func TestOpsGenerateHelmValuesRestartPersistenceHostPath(t *testing.T) { + oldRunCommand := opsGenerateHelmValuesRunCommand + opsGenerateHelmValuesRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl get nodes -o wide --no-headers": cmdHelmNodeWide, + }) + defer func() { opsGenerateHelmValuesRunCommand = oldRunCommand }() + + outPath := filepath.Join(t.TempDir(), "values.yaml") + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "generate-helm-values", + "--out", outPath, + "--target-node", "m02", + "--node-limit", "1", + "--restart-persistence", "hostpath", + "--state-hostpath", "/var/lib/sw-block", + }, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "restart_persistence_mode=hostpath", + "state_hostpath=/var/lib/sw-block", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("stdout missing %q:\n%s", want, stdout.String()) + } + } + values, err := os.ReadFile(outPath) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "blockmaster:", + "stateHostPath: /var/lib/sw-block", + "restartPersistence:", + "mode: hostpath", + } { + if !strings.Contains(string(values), want) { + t.Fatalf("values missing %q:\n%s", want, values) + } + } +} + +func TestOpsGenerateHelmValuesRejectsUnknownRestartPersistence(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "generate-helm-values", + "--out", filepath.Join(t.TempDir(), "values.yaml"), + "--restart-persistence", "durable-magic", + }, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d want invalid stdout=%s stderr=%s", code, stdout.String(), stderr.String()) + } + if !strings.Contains(stderr.String(), "--restart-persistence=\"durable-magic\" invalid") { + t.Fatalf("stderr=%s", stderr.String()) + } +} + +func TestOpsGenerateHelmValuesRejectsRFAboveSelectedNodes(t *testing.T) { + oldRunCommand := opsGenerateHelmValuesRunCommand + opsGenerateHelmValuesRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl get nodes -o wide --no-headers": cmdHelmNodeWide, + }) + defer func() { opsGenerateHelmValuesRunCommand = oldRunCommand }() + + var stdout, stderr bytes.Buffer + code := run([]string{ + "ops", "generate-helm-values", + "--out", filepath.Join(t.TempDir(), "values.yaml"), + "--target-node", "m02", + "--replication-factor", "3", + }, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d want invalid stdout=%s stderr=%s", code, stdout.String(), stderr.String()) + } + if !strings.Contains(stderr.String(), "requires at least 3 selected Ready nodes; selected=1") { + t.Fatalf("stderr=%s", stderr.String()) + } +} + +func TestOpsDescribeVolumeFromBundle(t *testing.T) { + dir := writeCmdObservationBundle(t) + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "describe", "volume", "--from-bundle", dir, "pvc-observed"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "cluster status=degraded volumes=1", + "volume pvc-observed status=ok rf=3 ack=sync-quorum", + "primary r2 on m02 frontend=192.168.1.184:3260", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("stdout missing %q:\n%s", want, stdout.String()) + } + } +} + +func TestOpsDescribeVolumeFromBundlePrefersProductClusterEvidence(t *testing.T) { + dir := writeCmdProductClusterBundle(t) + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "describe", "volume", "--from-bundle", dir, "pvc-product"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "cluster status=ok volumes=1 nodes=1", + "volume pvc-product status=ok rf=3 ack=sync-quorum", + "primary r2 on m02 frontend=192.168.1.184:3260", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("stdout missing %q:\n%s", want, stdout.String()) + } + } + if strings.Contains(stdout.String(), "pvc-observed") { + t.Fatalf("describe should prefer product cluster evidence over fallback inventory:\n%s", stdout.String()) + } +} + +func TestOpsReportFromBundleWritesStaticReadOnlyArtifacts(t *testing.T) { + dir := writeCmdProductClusterBundle(t) + outDir := t.TempDir() + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "report", "--from-bundle", dir, "--out", outDir}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, name := range []string{ + ops.ObservationReportHTMLArtifact, + ops.ObservationReportJSONArtifact, + ops.ObservationReportJSONLArtifact, + ops.ObservationOperatorSnapshotArtifact, + ops.ObservationReportTextArtifact, + } { + if _, err := os.Stat(filepath.Join(outDir, name)); err != nil { + t.Fatalf("missing report artifact %s: %v", name, err) + } + } + html, err := os.ReadFile(filepath.Join(outDir, ops.ObservationReportHTMLArtifact)) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "sw-block read-only status", + "pvc-product", + "192.168.1.184:3260", + "This report is observation-only", + } { + if !strings.Contains(string(html), want) { + t.Fatalf("html missing %q:\n%s", want, html) + } + } + summary, err := os.ReadFile(filepath.Join(outDir, ops.ObservationReportTextArtifact)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(summary), "read_only=true") || !strings.Contains(string(summary), "volume=pvc-product") { + t.Fatalf("summary missing report evidence:\n%s", summary) + } + if !strings.Contains(stdout.String(), "report_status=ok") || + !strings.Contains(stdout.String(), "html=index.html") || + !strings.Contains(stdout.String(), "operator_snapshot=operator-snapshot.json") { + t.Fatalf("stdout missing report paths:\n%s", stdout.String()) + } +} + +func TestOpsReturnedReplicaFromBundleSurfacesAcrossReportExplainDashboard(t *testing.T) { + dir := writeCmdReturnedReplicaBundle(t) + outDir := t.TempDir() + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "report", "--from-bundle", dir, "--out", outDir}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("report exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + summary, err := os.ReadFile(filepath.Join(outDir, ops.ObservationReportTextArtifact)) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "managed_volume_returned_replica=pvc-returned replica=r1 state=fenced reason=returned_replica_frontend_fenced", + "managed_volume_executor_preflight=authority.reintegrate_returned_replica target=r1 decision=ready reason=preconditions_satisfied mode=dry_run executor=authority_recovery_executor mutation_allowed=false ack_eligibility_known=true required_lsn=4241 durable_lsn=4241", + "managed_volume_executor_contract=authority.reintegrate_returned_replica target=r1 decision=disabled reason=executor_policy_disabled executor=authority_recovery_executor execution_enabled=false mutation_allowed=false allowed_mutation=ack_eligibility terminal_evidence=ack_eligibility_known,ack_eligible_true,frontend_fenced_after_execution,primary_unchanged,durable_frontier_covered,no_cross_volume_identity_change", + "managed_volume_action=authority.reintegrate_returned_replica mode=dry_run side_effect=authority_mutating executor=authority_recovery_executor decision=allowed", + } { + if !strings.Contains(string(summary), want) { + t.Fatalf("report summary missing %q:\n%s", want, summary) + } + } + snapshot, err := os.ReadFile(filepath.Join(outDir, ops.ObservationOperatorSnapshotArtifact)) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + `"replica_reintegrations": [`, + `"executor_preflights": [`, + `"executor_contracts": [`, + `"state": "fenced"`, + `"reason_code": "returned_replica_frontend_fenced"`, + `"reason": "executor_policy_disabled"`, + `"execution_enabled": false`, + `"reason": "preconditions_satisfied"`, + `"type": "authority.reintegrate_returned_replica"`, + } { + if !strings.Contains(string(snapshot), want) { + t.Fatalf("operator snapshot missing %q:\n%s", want, snapshot) + } + } + + writer := &operatorStatusTestWriter{} + oldFactory := opsOperatorStatusWriterFactory + opsOperatorStatusWriterFactory = func() (ops.OperatorStatusWriter, error) { + return writer, nil + } + t.Cleanup(func() { opsOperatorStatusWriterFactory = oldFactory }) + stdout.Reset() + stderr.Reset() + code = run([]string{"ops", "operator-status", "--from-bundle", dir, "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("operator-status exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(writer.volumes) != 1 { + t.Fatalf("operator-status writes=%+v", writer.volumes) + } + returned := writer.volumes[0].status.ReplicaReintegrations + if len(returned) != 1 || returned[0].ReplicaID != "r1" || returned[0].State != ops.ReturnedReplicaStateFenced { + t.Fatalf("CRD returned replicas=%+v", returned) + } + contracts := writer.volumes[0].status.ExecutorContracts + if len(contracts) != 1 || + contracts[0].Decision != ops.ReturnedReplicaExecutorContractDisabled || + contracts[0].ExecutionEnabled || + contracts[0].MutationAllowed { + t.Fatalf("CRD executor contracts=%+v", contracts) + } + foundReintegrate := false + for _, action := range writer.volumes[0].status.AllowedActions { + if action.Type == ops.ManagedVolumeActionReintegrateReturned { + foundReintegrate = true + } + } + if !foundReintegrate { + t.Fatalf("CRD actions=%+v", writer.volumes[0].status.AllowedActions) + } + + stdout.Reset() + stderr.Reset() + code = run([]string{"ops", "explain", "volume", "--from-bundle", dir, "pvc-returned"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("explain exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "managed_volume_returned_replica=pvc-returned replica=r1 state=fenced reason=returned_replica_frontend_fenced", + "managed_volume_executor_preflight authority.reintegrate_returned_replica target=r1 decision=ready reason=preconditions_satisfied mode=dry_run executor=authority_recovery_executor mutation_allowed=false ack_eligibility_known=true required_lsn=4241 durable_lsn=4241", + "managed_volume_executor_contract authority.reintegrate_returned_replica target=r1 decision=disabled reason=executor_policy_disabled executor=authority_recovery_executor execution_enabled=false mutation_allowed=false allowed_mutation=ack_eligibility terminal_evidence=ack_eligibility_known,ack_eligible_true,frontend_fenced_after_execution,primary_unchanged,durable_frontier_covered,no_cross_volume_identity_change", + "managed_volume_action authority.reintegrate_returned_replica mode=dry_run", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("explain missing %q:\n%s", want, stdout.String()) + } + } + + addr := freeTCPAddr(t) + stdout.Reset() + stderr.Reset() + done := make(chan int, 1) + go func() { + done <- run([]string{ + "ops", "dashboard", + "--from-bundle", dir, + "--listen", addr, + "--serve-duration", "500ms", + }, &stdout, &stderr) + }() + body := waitForHTTPContains(t, "http://"+addr+"/operator-snapshot.json", `"replica_reintegrations": [`) + for _, want := range []string{ + `"reason_code": "returned_replica_frontend_fenced"`, + `"executor_preflights": [`, + `"executor_contracts": [`, + `"reason": "preconditions_satisfied"`, + `"reason": "executor_policy_disabled"`, + `"execution_enabled": false`, + `"type": "authority.reintegrate_returned_replica"`, + } { + if !strings.Contains(body, want) { + t.Fatalf("dashboard operator snapshot missing %q:\n%s", want, body) + } + } + select { + case code := <-done: + if code != ops.VolumeStatusExitOK { + t.Fatalf("dashboard exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + case <-time.After(2 * time.Second): + t.Fatalf("dashboard command did not stop; stdout=%s stderr=%s", stdout.String(), stderr.String()) + } +} + +func TestOpsReturnedReplicaRebuildFromBundleSurfacesAcrossReportExplainDashboard(t *testing.T) { + dir := writeCmdReturnedReplicaRebuildBundle(t) + outDir := t.TempDir() + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "report", "--from-bundle", dir, "--out", outDir}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("report exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + summary, err := os.ReadFile(filepath.Join(outDir, ops.ObservationReportTextArtifact)) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "managed_volume_returned_replica=pvc-rebuild replica=r1 state=recovering reason=candidate_frontier_behind", + "managed_volume_executor_preflight=authority.rebuild_returned_replica target=r1 decision=ready reason=preconditions_satisfied mode=dry_run executor=authority_recovery_executor mutation_allowed=false ack_eligibility_known=true required_lsn=4241 durable_lsn=4240", + "managed_volume_executor_contract=authority.rebuild_returned_replica target=r1 decision=disabled reason=executor_policy_disabled executor=authority_recovery_executor execution_enabled=false mutation_allowed=false allowed_mutation=rebuild_traffic terminal_evidence=frontend_fenced_before_rebuild,primary_unchanged,durable_frontier_caught_up,no_frontend_publication,no_cross_volume_identity_change", + "managed_volume_action=authority.rebuild_returned_replica mode=dry_run side_effect=authority_mutating executor=authority_recovery_executor decision=rejected reason=policy_disabled", + } { + if !strings.Contains(string(summary), want) { + t.Fatalf("report summary missing %q:\n%s", want, summary) + } + } + snapshot, err := os.ReadFile(filepath.Join(outDir, ops.ObservationOperatorSnapshotArtifact)) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + `"reason_code": "candidate_frontier_behind"`, + `"type": "authority.rebuild_returned_replica"`, + `"allowed_mutation_class": [`, + `"rebuild_traffic"`, + `"durable_frontier_caught_up"`, + `"decision_reason": "policy_disabled"`, + } { + if !strings.Contains(string(snapshot), want) { + t.Fatalf("operator snapshot missing %q:\n%s", want, snapshot) + } + } + + writer := &operatorStatusTestWriter{} + oldFactory := opsOperatorStatusWriterFactory + opsOperatorStatusWriterFactory = func() (ops.OperatorStatusWriter, error) { + return writer, nil + } + t.Cleanup(func() { opsOperatorStatusWriterFactory = oldFactory }) + stdout.Reset() + stderr.Reset() + code = run([]string{"ops", "operator-status", "--from-bundle", dir, "--namespace", "kube-system"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("operator-status exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if len(writer.volumes) != 1 { + t.Fatalf("operator-status writes=%+v", writer.volumes) + } + status := writer.volumes[0].status + if len(status.ExecutorPreflights) != 1 || + status.ExecutorPreflights[0].ActionType != ops.ManagedVolumeActionRebuildReturned || + status.ExecutorPreflights[0].Decision != ops.ReturnedReplicaExecutorPreflightReady { + t.Fatalf("CRD preflights=%+v", status.ExecutorPreflights) + } + if len(status.ExecutorContracts) != 1 || + status.ExecutorContracts[0].ActionType != ops.ManagedVolumeActionRebuildReturned || + status.ExecutorContracts[0].Decision != ops.ReturnedReplicaExecutorContractDisabled || + status.ExecutorContracts[0].ExecutionEnabled || + status.ExecutorContracts[0].MutationAllowed || + !cmdStringSliceContains(status.ExecutorContracts[0].AllowedMutationClass, "rebuild_traffic") { + t.Fatalf("CRD contracts=%+v", status.ExecutorContracts) + } + + stdout.Reset() + stderr.Reset() + code = run([]string{"ops", "explain", "volume", "--from-bundle", dir, "pvc-rebuild"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("explain exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "managed_volume_executor_preflight authority.rebuild_returned_replica target=r1 decision=ready reason=preconditions_satisfied mode=dry_run executor=authority_recovery_executor mutation_allowed=false ack_eligibility_known=true required_lsn=4241 durable_lsn=4240", + "managed_volume_executor_contract authority.rebuild_returned_replica target=r1 decision=disabled reason=executor_policy_disabled executor=authority_recovery_executor execution_enabled=false mutation_allowed=false allowed_mutation=rebuild_traffic terminal_evidence=frontend_fenced_before_rebuild,primary_unchanged,durable_frontier_caught_up,no_frontend_publication,no_cross_volume_identity_change", + "managed_volume_action authority.rebuild_returned_replica mode=dry_run", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("explain missing %q:\n%s", want, stdout.String()) + } + } + + addr := freeTCPAddr(t) + stdout.Reset() + stderr.Reset() + done := make(chan int, 1) + go func() { + done <- run([]string{ + "ops", "dashboard", + "--from-bundle", dir, + "--listen", addr, + "--serve-duration", "500ms", + }, &stdout, &stderr) + }() + body := waitForHTTPContains(t, "http://"+addr+"/operator-snapshot.json", `"type": "authority.rebuild_returned_replica"`) + for _, want := range []string{ + `"reason_code": "candidate_frontier_behind"`, + `"allowed_mutation_class": [`, + `"rebuild_traffic"`, + `"execution_enabled": false`, + `"decision_reason": "policy_disabled"`, + } { + if !strings.Contains(body, want) { + t.Fatalf("dashboard operator snapshot missing %q:\n%s", want, body) + } + } + select { + case code := <-done: + if code != ops.VolumeStatusExitOK { + t.Fatalf("dashboard exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + case <-time.After(2 * time.Second): + t.Fatalf("dashboard command did not stop; stdout=%s stderr=%s", stdout.String(), stderr.String()) + } +} + +func TestOpsReportFromBundleAllowsEmptyClusterEvidence(t *testing.T) { + dir := t.TempDir() + productDir := filepath.Join(dir, "demo", "product-observation") + if err := os.MkdirAll(productDir, 0o755); err != nil { + t.Fatal(err) + } + cluster := ops.NewClusterEvidence(time.Date(2026, 5, 17, 21, 0, 0, 0, time.UTC)) + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(productDir, ops.ClusterEvidenceArtifact), raw, 0o644); err != nil { + t.Fatal(err) + } + outDir := t.TempDir() + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "report", "--from-bundle", dir, "--out", outDir}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + summary, err := os.ReadFile(filepath.Join(outDir, ops.ObservationReportTextArtifact)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(summary), "volumes=0") || !strings.Contains(string(summary), "read_only=true") { + t.Fatalf("summary missing empty-cluster evidence:\n%s", summary) + } +} + +func TestOpsReportFromBundleSkipsCorruptClusterEvidenceCandidate(t *testing.T) { + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "a-stale", "status"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "a-stale", "status", ops.ClusterEvidenceArtifact), []byte("{not-json"), 0o644); err != nil { + t.Fatal(err) + } + validDir := filepath.Join(dir, "z-restart") + if err := os.MkdirAll(validDir, 0o755); err != nil { + t.Fatal(err) + } + cluster := ops.NewClusterEvidence(time.Date(2026, 5, 27, 12, 0, 0, 0, time.UTC)) + cluster.Volumes = []ops.VolumeEvidence{{ + VolumeID: "pvc-valid", + Namespace: "default", + PVCName: "demo-pvc", + ReplicationFactor: 1, + Status: ops.ObservationStatusOK, + PrimaryReplica: "r1", + PrimaryNode: "m02", + PublishTarget: "192.168.1.184:3260", + }} + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(validDir, ops.RestartClusterEvidenceArtifact), raw, 0o644); err != nil { + t.Fatal(err) + } + + outDir := t.TempDir() + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "report", "--from-bundle", dir, "--out", outDir}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + summary, err := os.ReadFile(filepath.Join(outDir, ops.ObservationReportTextArtifact)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(summary), "volume=pvc-valid") || strings.Contains(string(summary), "not-json") { + t.Fatalf("summary did not use valid evidence:\n%s", summary) + } + snapshot, err := os.ReadFile(filepath.Join(outDir, ops.ObservationOperatorSnapshotArtifact)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(snapshot), `"volume_id": "pvc-valid"`) || !strings.Contains(string(snapshot), `"read_only": true`) { + t.Fatalf("operator snapshot missing valid read-only evidence:\n%s", snapshot) + } +} + +func TestOpsDashboardFromBundleServesReadOnlyHTTP(t *testing.T) { + dir := writeCmdProductClusterBundle(t) + addr := freeTCPAddr(t) + var stdout, stderr bytes.Buffer + done := make(chan int, 1) + go func() { + done <- run([]string{ + "ops", "dashboard", + "--from-bundle", dir, + "--listen", addr, + "--serve-duration", "500ms", + }, &stdout, &stderr) + }() + + body := waitForHTTPContains(t, "http://"+addr+"/summary.txt", "managed_volume=pvc-product") + if !strings.Contains(body, "read_only=true") { + t.Fatalf("summary missing read_only=true:\n%s", body) + } + snapshot := waitForHTTPContains(t, "http://"+addr+"/operator-snapshot.json", `"read_only": true`) + if !strings.Contains(snapshot, `"mutation_allowed": false`) { + t.Fatalf("operator snapshot missing read-only boundary:\n%s", snapshot) + } + postResp, err := http.Post("http://"+addr+"/", "application/json", strings.NewReader(`{"action":"promote"}`)) + if err != nil { + t.Fatal(err) + } + defer postResp.Body.Close() + if postResp.StatusCode != http.StatusMethodNotAllowed { + t.Fatalf("post status=%d", postResp.StatusCode) + } + + select { + case code := <-done: + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + case <-time.After(2 * time.Second): + t.Fatalf("dashboard command did not stop; stdout=%s stderr=%s", stdout.String(), stderr.String()) + } + if !strings.Contains(stdout.String(), "dashboard_status=ok") || + !strings.Contains(stdout.String(), "read_only=true") { + t.Fatalf("stdout missing dashboard summary:\n%s", stdout.String()) + } +} + +func TestOpsDashboardMasterAPIServesLiveClusterEvidence(t *testing.T) { + masterAddr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + addr := freeTCPAddr(t) + var stdout, stderr bytes.Buffer + done := make(chan int, 1) + go func() { + done <- run([]string{ + "ops", "dashboard", + "--master-api", masterAddr, + "--listen", addr, + "--serve-duration", "1500ms", + }, &stdout, &stderr) + }() + + body := waitForHTTPContains(t, "http://"+addr+"/cluster-evidence.json", `"event_type": "csi_reattach_observed"`) + if !strings.Contains(body, `"managed_volumes"`) { + t.Fatalf("cluster evidence missing managed_volumes:\n%s", body) + } + snapshot := waitForHTTPContains(t, "http://"+addr+"/operator-snapshot.json", `"read_only": true`) + if !strings.Contains(snapshot, `"api_version": "block.seaweedfs.com/v1alpha1"`) { + t.Fatalf("operator snapshot missing api version:\n%s", snapshot) + } + + select { + case code := <-done: + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + case <-time.After(2 * time.Second): + t.Fatalf("dashboard command did not stop; stdout=%s stderr=%s", stdout.String(), stderr.String()) + } +} + +func TestOpsTimelineVolumeFromBundleJSONL(t *testing.T) { + dir := writeCmdObservationBundle(t) + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "timeline", "volume", "--from-bundle", dir, "-o", "jsonl", "pvc-observed"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + if !strings.Contains(stdout.String(), `"event_type":"authority_published"`) || + !strings.Contains(stdout.String(), `"reason_code":"candidate_covers_required_frontier"`) { + t.Fatalf("stdout missing timeline jsonl:\n%s", stdout.String()) + } +} + +func freeTCPAddr(t *testing.T) string { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := ln.Addr().String() + if err := ln.Close(); err != nil { + t.Fatal(err) + } + return addr +} + +func waitForHTTPContains(t *testing.T, url, want string) string { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + var lastErr error + for time.Now().Before(deadline) { + resp, err := http.Get(url) + if err != nil { + lastErr = err + time.Sleep(20 * time.Millisecond) + continue + } + body, readErr := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if readErr != nil { + lastErr = readErr + time.Sleep(20 * time.Millisecond) + continue + } + if resp.StatusCode == http.StatusOK && strings.Contains(string(body), want) { + return string(body) + } + lastErr = fmt.Errorf("status=%d body=%s", resp.StatusCode, body) + time.Sleep(20 * time.Millisecond) + } + t.Fatalf("timed out waiting for %s containing %q: %v", url, want, lastErr) + return "" +} + +func TestOpsExplainVolumeFromBundleBlockedImagePull(t *testing.T) { + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "demo"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "demo", ops.KubeSystemPodsDeploysArtifact), []byte(`NAME READY STATUS RESTARTS AGE IP NODE +pod/sw-block-csi-node-n948t 0/2 Init:ErrImagePull 0 2m3s 192.168.1.184 m02 +deployment.apps/sw-block-csi-controller 1/1 1 1 2m3s block-csi sw-block-csi:local +`), 0o644); err != nil { + t.Fatal(err) + } + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "explain", "volume", "--from-bundle", dir, "pvc-blocked"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "volume pvc-blocked status=blocked rf=3 reason=csi_node_image_pull_failed", + "waiting=ImagePullBackOff on node m02 image sw-block-csi:local", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("stdout missing %q:\n%s", want, stdout.String()) + } + } +} + +func TestOpsDescribeVolumeLiveInventory(t *testing.T) { + oldRunCommand := opsInventoryRunCommand + opsInventoryRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl -n default get pvc -o json": cmdSinglePVCListJSON, + "kubectl get pv -o json": cmdSinglePVListJSON, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": cmdSingleDeploymentListJSON, + }) + defer func() { opsInventoryRunCommand = oldRunCommand }() + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "describe", "volume", "pvc-live", "--namespace", "default", "--product-revision", "product-rev"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + for _, want := range []string{ + "cluster status=ok volumes=1 nodes=0", + "volume pvc-live status=ok rf=1 ack=best-effort", + "pvc default/app-live", + "primary r1 on m02 frontend=127.0.0.1:3260", + } { + if !strings.Contains(stdout.String(), want) { + t.Fatalf("stdout missing %q:\n%s", want, stdout.String()) + } + } +} + +func TestOpsClusterAndVolumesLiveInventory(t *testing.T) { + oldRunCommand := opsInventoryRunCommand + opsInventoryRunCommand = fixtureCmdKubectl(map[string]string{ + "kubectl -n default get pvc -o json": cmdSinglePVCListJSON, + "kubectl get pv -o json": cmdSinglePVListJSON, + "kubectl -n default get deploy -l app=sw-blockvolume -o json": cmdSingleDeploymentListJSON, + }) + defer func() { opsInventoryRunCommand = oldRunCommand }() + + var clusterOut, clusterErr bytes.Buffer + code := run([]string{"ops", "cluster", "--namespace", "default", "--product-revision", "product-rev"}, &clusterOut, &clusterErr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("cluster exit=%d stderr=%s stdout=%s", code, clusterErr.String(), clusterOut.String()) + } + if !strings.Contains(clusterOut.String(), "cluster status=ok volumes=1 nodes=0") || + !strings.Contains(clusterOut.String(), "volume pvc-live status=ok rf=1 ack=best-effort") { + t.Fatalf("cluster output missing evidence:\n%s", clusterOut.String()) + } + + var volumesOut, volumesErr bytes.Buffer + code = run([]string{"ops", "volumes", "--namespace", "default", "--product-revision", "product-rev"}, &volumesOut, &volumesErr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("volumes exit=%d stderr=%s stdout=%s", code, volumesErr.String(), volumesOut.String()) + } + if !strings.Contains(volumesOut.String(), "volume pvc-live status=ok rf=1 primary=r1 node=m02 frontend=127.0.0.1:3260") { + t.Fatalf("volumes output missing evidence:\n%s", volumesOut.String()) + } +} + +func cleanCmdResidueCommand(_ context.Context, name string, args ...string) ([]byte, error) { + switch name { + case "iscsiadm": + return []byte("iscsiadm: No active sessions.\n"), errors.New("exit status 21") + case "nvme": + return []byte(`{"Subsystems":[]}`), nil + case "ps", "tasklist": + return []byte("PID ARGS\n1 unrelated\n"), nil + default: + return nil, fmt.Errorf("unexpected command %s", name) + } +} + +const cmdHelmNodeWide = `m01 Ready worker 10d v1.34.4+k3s1 192.168.1.181 Ubuntu 24.04 6.8.0 containerd://2.0.0 +m02 Ready control-plane 10d v1.34.4+k3s1 192.168.1.184 Ubuntu 24.04 6.8.0 containerd://2.0.0 +tp01 Ready worker 10d v1.34.4+k3s1 192.168.1.188 Ubuntu 24.04 6.8.0 containerd://2.0.0 +bad1 Ready,SchedulingDisabled worker 10d v1.34.4+k3s1 192.168.1.199 Ubuntu 24.04 6.8.0 containerd://2.0.0 +bad2 NotReady worker 10d v1.34.4+k3s1 192.168.1.200 Ubuntu 24.04 6.8.0 containerd://2.0.0 +bad3 Ready worker 10d v1.34.4+k3s1 127.0.0.1 Ubuntu 24.04 6.8.0 containerd://2.0.0 +` + +const cmdSinglePVCListJSON = `{ + "items": [ + {"metadata":{"name":"app-live","namespace":"default","uid":"uid-live"},"spec":{"volumeName":"pvc-live","storageClassName":"sw-block-dynamic"},"status":{"phase":"Bound"}} + ] +}` + +const cmdSinglePVListJSON = `{ + "items": [ + {"metadata":{"name":"pvc-live"},"spec":{"claimRef":{"namespace":"default","name":"app-live","uid":"uid-live"},"csi":{"driver":"block.csi.seaweedfs.com","volumeHandle":"pvc-live"}}} + ] +}` + +const cmdSingleDeploymentListJSON = `{ + "items": [ + { + "metadata":{ + "name":"sw-blockvolume-pvc-live-r1", + "namespace":"default", + "labels":{"app":"sw-blockvolume","sw-block.seaweedfs.com/volume":"pvc-live","sw-block.seaweedfs.com/replica":"r1"}, + "ownerReferences":[{"kind":"PersistentVolumeClaim","name":"app-live","uid":"uid-live"}] + }, + "spec":{"template":{"spec":{"nodeSelector":{"kubernetes.io/hostname":"m02"},"containers":[{"name":"blockvolume","args":["--server-id=m02","--volume-id=pvc-live","--replica-id=r1","--data-addr=127.0.0.1:19101","--ctrl-addr=127.0.0.1:19102","--status-addr=127.0.0.1:23260","--iscsi-listen=127.0.0.1:3260","--iscsi-iqn=iqn.2026-05.io.seaweedfs:pvc-live"]}]}}}, + "status":{"replicas":1,"readyReplicas":1} + } + ] +}` + +func writeCmdObservationBundle(t *testing.T) string { + t.Helper() + dir := t.TempDir() + inventoryDir := filepath.Join(dir, "demo", "ops-inventory-reader-verified") + if err := os.MkdirAll(inventoryDir, 0o755); err != nil { + t.Fatal(err) + } + inventory := ops.BuildVolumeInventory(ops.VolumeInventoryInput{ + ProductRevision: "product-rev", + Volumes: []ops.VolumeInventoryVolumeInput{{ + VolumeID: "pvc-observed", + Namespace: "default", + PVCName: "sw-block-demo-pvc", + PVName: "pvc-observed", + ReplicationFactor: 3, + Replicas: []ops.VolumeInventoryReplicaInput{ + { + ReplicaID: "r2", + ServerID: "node-loss-r2", + NodeName: "m02", + Observed: true, + Protocol: "iscsi", + FrontendAddress: "192.168.1.184:3260", + AuthorityRole: "primary", + ReplicationRole: "none", + Healthy: true, + FrontendPrimaryReady: true, + Epoch: 2, + EndpointVersion: 1, + AckProfile: ops.PromotionAckProfileSyncQuorum, + ClaimProfile: ops.PromotionClaimBetaRecovery, + DurableLatched: true, + DurableOperational: true, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 52, + CandidateFrontierKnown: true, + CandidateFrontierLSN: 52, + }, + { + ReplicaID: "r3", + ServerID: "node-loss-r3", + NodeName: "tp01", + Observed: true, + Protocol: "iscsi", + FrontendAddress: "192.168.1.188:3260", + AuthorityRole: "unknown", + ReplicationRole: "replica_ready", + AckProfile: ops.PromotionAckProfileSyncQuorum, + ClaimProfile: ops.PromotionClaimBetaRecovery, + DurableLatched: true, + DurableOperational: true, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 52, + CandidateFrontierKnown: true, + CandidateFrontierLSN: 52, + }, + }, + }}, + }) + raw, err := ops.MarshalObservationJSON(inventory) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(inventoryDir, ops.VolumeInventoryArtifact), raw, 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "demo", ops.NodeLossRecoverySummaryArtifact), []byte(strings.Join([]string{ + "result=promoted", + "ack_profile=sync-quorum", + "promoted=r2@m02", + "before_frontend=192.168.1.181:3260", + "after_frontend=192.168.1.184:3260", + "reader_verified=true", + "pod_recreate_used=true", + "old_primary_stale_io_success_count=0", + }, "\n")), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "demo", ops.ControlPlaneTimelineArtifact), []byte("event=authority_published from=r1 to=r2 primary=r2 primary_count=1 volume=pvc-observed\n"), 0o644); err != nil { + t.Fatal(err) + } + return dir +} + +func writeCmdProductClusterBundle(t *testing.T) string { + t.Helper() + dir := writeCmdObservationBundle(t) + productDir := filepath.Join(dir, "demo", "product-observation") + if err := os.MkdirAll(productDir, 0o755); err != nil { + t.Fatal(err) + } + cluster := ops.NewClusterEvidence(time.Date(2026, 5, 17, 20, 0, 0, 0, time.UTC)) + cluster.ProductRevision = "product-cluster-rev" + cluster.Status = ops.ObservationStatusOK + cluster.Nodes = []ops.NodeEvidence{{ + NodeName: "m02", + InternalIP: "192.168.1.184", + Schedulable: true, + Ready: true, + ReplicaCount: 1, + MissingImages: nil, + }} + cluster.Volumes = []ops.VolumeEvidence{{ + VolumeID: "pvc-product", + Namespace: "default", + PVCName: "sw-block-example-pvc", + ReplicationFactor: 3, + AckProfile: ops.PromotionAckProfileSyncQuorum, + DesiredReplicas: 3, + ObservedReplicas: 3, + Status: ops.ObservationStatusOK, + PrimaryReplica: "r2", + PrimaryNode: "m02", + PublishTarget: "192.168.1.184:3260", + Replicas: []ops.ReplicaEvidence{{ + ReplicaID: "r2", + KubernetesNode: "m02", + Observed: true, + Role: "primary", + FrontendAddr: "192.168.1.184:3260", + }}, + }} + cluster.Events = []ops.ClusterEvent{{ + EventID: "master-1", + EventTime: time.Date(2026, 5, 17, 20, 1, 0, 0, time.UTC), + VolumeID: "pvc-product", + ReplicaID: "r2", + Type: ops.EventTypeCSIReattachObserved, + Severity: "info", + Reason: ops.EventTypeCSIReattachObserved, + Message: "CSI staged volume on node", + NewValue: "192.168.1.184:3260", + }} + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(productDir, ops.ClusterEvidenceArtifact), raw, 0o644); err != nil { + t.Fatal(err) + } + return dir +} + +func writeCmdReturnedReplicaBundle(t *testing.T) string { + t.Helper() + dir := t.TempDir() + productDir := filepath.Join(dir, "demo", "product-observation") + if err := os.MkdirAll(productDir, 0o755); err != nil { + t.Fatal(err) + } + cluster := ops.NewClusterEvidence(time.Date(2026, 6, 19, 8, 40, 0, 0, time.UTC)) + cluster.ProductRevision = "phase46-test" + cluster.Status = ops.ObservationStatusRecovering + cluster.Volumes = []ops.VolumeEvidence{{ + VolumeID: "pvc-returned", + Namespace: "default", + PVCName: "returned-pvc", + ReplicationFactor: 2, + Status: ops.ObservationStatusRecovering, + PrimaryReplica: "r2", + PrimaryNode: "m02", + PublishTarget: "192.168.1.184:3260", + Epoch: 2, + EndpointVersion: 1, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 4241, + Replicas: []ops.ReplicaEvidence{{ + ReplicaID: "r1", + KubernetesNode: "m01", + Observed: true, + Role: "previous_primary", + ReplicationRole: "replica_ready", + Healthy: false, + FrontendPrimaryReady: false, + AckEligibilityKnown: true, + AckEligible: false, + DurableFrontierKnown: true, + DurableFrontierLSN: 4241, + StalePrimaryFenced: true, + SupportBundlePath: "returned-replica-summary.txt", + }, { + ReplicaID: "r2", + KubernetesNode: "m02", + Observed: true, + Role: "primary", + Healthy: true, + FrontendPrimaryReady: true, + ReplicationRole: "none", + FrontendAddr: "192.168.1.184:3260", + DurableFrontierKnown: true, + DurableFrontierLSN: 4241, + }}, + }} + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(productDir, ops.ClusterEvidenceArtifact), raw, 0o644); err != nil { + t.Fatal(err) + } + return dir +} + +func writeCmdReturnedReplicaRebuildBundle(t *testing.T) string { + t.Helper() + dir := t.TempDir() + productDir := filepath.Join(dir, "demo", "product-observation") + if err := os.MkdirAll(productDir, 0o755); err != nil { + t.Fatal(err) + } + cluster := ops.NewClusterEvidence(time.Date(2026, 6, 23, 18, 0, 0, 0, time.UTC)) + cluster.ProductRevision = "phase56-test" + cluster.Status = ops.ObservationStatusRecovering + cluster.Volumes = []ops.VolumeEvidence{{ + VolumeID: "pvc-rebuild", + Namespace: "default", + PVCName: "rebuild-pvc", + ReplicationFactor: 3, + Status: ops.ObservationStatusRecovering, + PrimaryReplica: "r2", + PrimaryNode: "m02", + PublishTarget: "192.168.1.184:3260", + Epoch: 3, + EndpointVersion: 7, + RequiredFrontierKnown: true, + RequiredFrontierLSN: 4241, + Replicas: []ops.ReplicaEvidence{{ + ReplicaID: "r1", + KubernetesNode: "m01", + Observed: true, + Role: "previous_primary", + ReplicationRole: "replica_behind", + Healthy: false, + FrontendPrimaryReady: false, + AckEligibilityKnown: true, + AckEligible: false, + DurableFrontierKnown: true, + DurableFrontierLSN: 4240, + StalePrimaryFenced: true, + SupportBundlePath: "returned-replica-rebuild-summary.txt", + }, { + ReplicaID: "r2", + KubernetesNode: "m02", + Observed: true, + Role: "primary", + Healthy: true, + FrontendPrimaryReady: true, + ReplicationRole: "primary", + FrontendAddr: "192.168.1.184:3260", + DurableFrontierKnown: true, + DurableFrontierLSN: 4241, + }}, + }} + raw, err := ops.MarshalObservationJSON(cluster) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(productDir, ops.ClusterEvidenceArtifact), raw, 0o644); err != nil { + t.Fatal(err) + } + return dir +} + +func fixtureCmdKubectl(outputs map[string]string) func(context.Context, string, ...string) ([]byte, error) { + return func(_ context.Context, name string, args ...string) ([]byte, error) { + key := strings.TrimSpace(name + " " + strings.Join(args, " ")) + out, ok := outputs[key] + if !ok { + return nil, fmt.Errorf("unexpected command %q", key) + } + return []byte(out), nil + } +} + +func TestOpsStatusMissingRequiredArgsReturnsInvalid(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "status", "--volume", "v1"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d want %d", code, ops.VolumeStatusExitInvalid) + } + if !strings.Contains(stderr.String(), "--volume and --out are required") { + t.Fatalf("stderr=%s", stderr.String()) + } +} + +func TestOpsStatusRequiresMasterAndStatusAddr(t *testing.T) { + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "status", "--volume", "v1", "--out", t.TempDir(), "--status-addr", "127.0.0.1:1"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d want %d", code, ops.VolumeStatusExitInvalid) + } + if !strings.Contains(stderr.String(), "--master and --status-addr are both required") { + t.Fatalf("stderr=%s", stderr.String()) + } +} + +func TestOpsClusterReadsMasterAPIProductEvents(t *testing.T) { + masterAddr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "cluster", "--master-api", masterAddr, "-o", "json"}, &stdout, &stderr) + if code != ops.VolumeStatusExitOK { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, stderr.String(), stdout.String()) + } + var cluster ops.ClusterEvidence + if err := json.Unmarshal(stdout.Bytes(), &cluster); err != nil { + t.Fatalf("json: %v\n%s", err, stdout.String()) + } + if len(cluster.Events) != 1 || cluster.Events[0].Type != ops.EventTypeCSIReattachObserved { + t.Fatalf("events=%+v", cluster.Events) + } + if len(cluster.Volumes) != 1 || cluster.Volumes[0].VolumeID != "v1" || cluster.Volumes[0].PrimaryReplica != "r2" { + t.Fatalf("volumes=%+v", cluster.Volumes) + } + if len(cluster.ManagedVolumes) != 1 || cluster.ManagedVolumes[0].VolumeID != "v1" { + t.Fatalf("managed_volumes=%+v", cluster.ManagedVolumes) + } + if cluster.ManagedVolumes[0].States.Authority != ops.ManagedVolumeAuthorityPrimaryAvailable { + t.Fatalf("managed volume=%+v", cluster.ManagedVolumes[0]) + } +} + +func TestOpsClusterMasterAPIRejectsUnexpectedArgs(t *testing.T) { + masterAddr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + + var stdout, stderr bytes.Buffer + code := run([]string{"ops", "cluster", "--master-api", masterAddr, "extra"}, &stdout, &stderr) + if code != ops.VolumeStatusExitInvalid { + t.Fatalf("exit=%d want invalid stdout=%s stderr=%s", code, stdout.String(), stderr.String()) + } +} + +type cmdFakeEvidenceServer struct { + control.UnimplementedEvidenceServiceServer +} + +func (cmdFakeEvidenceServer) QueryVolumeStatus(context.Context, *control.StatusRequest) (*control.StatusResponse, error) { + return &control.StatusResponse{ + VolumeId: "v1", + ReplicaId: "r1", + Epoch: 7, + EndpointVersion: 2, + Assigned: true, + Frontends: []*control.FrontendTarget{ + {Protocol: "iscsi", Addr: "127.0.0.1:3260", Iqn: "iqn.2026-05.io.seaweedfs:v1", Lun: 0}, + }, + }, nil +} + +type cmdFakeClusterEvidenceServer struct { + control.UnimplementedClusterEvidenceServiceServer +} + +func (cmdFakeClusterEvidenceServer) GetClusterStatus(context.Context, *control.GetClusterStatusRequest) (*control.ClusterStatusResponse, error) { + return &control.ClusterStatusResponse{ + SchemaVersion: ops.ObservationSchemaVersion, + CapturedAt: timestamppb.Now(), + ProductRevision: "test-rev", + Status: ops.ObservationStatusOK, + Volumes: []*control.VolumeEvidence{{ + VolumeId: "v1", + ReplicationFactor: 3, + DesiredReplicas: 3, + ObservedReplicas: 3, + Status: ops.ObservationStatusOK, + PrimaryReplica: "r2", + PrimaryNode: "m02", + PublishTarget: "192.168.1.184:3260", + Epoch: 2, + EndpointVersion: 1, + }}, + Events: []*control.ClusterEvent{{ + EventId: "master-1", + EventTime: timestamppb.Now(), + VolumeId: "v1", + ReplicaId: "r2", + NodeName: "m02", + EventType: ops.EventTypeCSIReattachObserved, + Severity: "info", + Message: "CSI staged volume on node", + ReasonCode: ops.EventTypeCSIReattachObserved, + NewValue: "192.168.1.184:3260", + Epoch: 2, + EndpointVersion: 1, + EvidenceRef: "csi-node", + }}, + }, nil +} + +func startCmdFakeMaster(t *testing.T) (string, func()) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + control.RegisterEvidenceServiceServer(srv, cmdFakeEvidenceServer{}) + control.RegisterClusterEvidenceServiceServer(srv, cmdFakeClusterEvidenceServer{}) + go func() { _ = srv.Serve(ln) }() + return ln.Addr().String(), func() { + srv.Stop() + _ = ln.Close() + } +} + +func writeCmdJSON(t *testing.T, w http.ResponseWriter, v any) { + t.Helper() + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(v); err != nil { + t.Fatal(err) + } +} + +func cmdStringSliceContains(values []string, want string) bool { + for _, value := range values { + if value == want { + return true + } + } + return false +} diff --git a/seaweed-block/cmd/sw-block/master_helpers_test.go b/seaweed-block/cmd/sw-block/master_helpers_test.go new file mode 100644 index 0000000000..5d42e10142 --- /dev/null +++ b/seaweed-block/cmd/sw-block/master_helpers_test.go @@ -0,0 +1,59 @@ +package main + +import ( + "context" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +func lifecycleClient(t *testing.T, addr string) control.LifecycleServiceClient { + t.Helper() + c, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + return control.NewLifecycleServiceClient(c) +} + +func startDeleteMaster(t *testing.T, cfg master.Config) (*master.Host, func()) { + t.Helper() + // Normal lifecycle RPC fixtures have an assignment producer configured. + // Loop-off admission has its own real-master table in the master package. + cfg.LifecycleProductLoop = true + if cfg.WorkspaceRPC && cfg.LayoutCreateVolume == nil { + store := newMemChunkStore() + catalog, err := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + cfg.LayoutCreateVolume = func(ctx context.Context, spec lifecycle.VolumeSpec) error { + id, err := layout.ParseVolumeID(spec.LayoutID) + if err != nil { + return err + } + _, err = catalog.CreateVolume(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}, + layout.Geometry{SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes}) + return err + } + } + h, err := master.New(cfg) + if err != nil { + t.Fatal(err) + } + h.Start() + return h, func() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = h.Close(ctx) + } +} diff --git a/seaweed-block/cmd/sw-block/mini.go b/seaweed-block/cmd/sw-block/mini.go new file mode 100644 index 0000000000..f252e1cc38 --- /dev/null +++ b/seaweed-block/cmd/sw-block/mini.go @@ -0,0 +1,633 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "net" + "os" + "os/exec" + "os/signal" + "path/filepath" + "strconv" + "strings" + "syscall" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// sw-block mini starts the single-host configuration in one command, after +// SeaweedFS's `weed mini`: weed (when found), blockmaster and one +// blockvolume, with the standalone page's flags. It prints every command it +// runs, never runs sudo or nvme connect (it prints the connect command), and +// stops every child when interrupted or when one of them exits. + +const miniUsage = `usage: sw-block mini [--dir ./swb-mini] [--reuse] [--weed PATH] [--bin DIR] [--size 256MiB] [--nqn NQN] [--port-shift N] + +Starts weed mini (when a weed binary is found: --weed, else PATH), blockmaster +and one blockvolume (v1) on loopback, and prints every command it runs. With +weed the volume is walstore-chunk with the chunk control endpoint, so +snapshots work at once (a restore into a new volume needs the standalone +setup); without weed it is walstore (no snapshots). Ctrl-C stops everything +it started.` + +// miniPorts are the loopback ports mini uses: the standalone page's, and +// weed mini's defaults. Tests move them. +type miniPorts struct { + Master int // blockmaster + Data, Ctrl, Status int // blockvolume + NVMe int + // weed mini's listeners (HTTP and gRPC of master, volume and filer), + // all set explicitly: its S3, WebDAV and admin UI are turned off. + WeedMaster, WeedMasterG, WeedVolume, WeedVolumeG, WeedFiler, WeedFG int + // weed mini always runs its admin server (-admin.ui=false only hides the + // UI): its HTTP and worker gRPC ports are set too; its legacy pair is off. + WeedAdmin, WeedAdminG int +} + +// shifted moves every port by n (--port-shift), for a host where a default +// port is taken or to run a second mini beside the first. +func (p miniPorts) shifted(n int) miniPorts { + return miniPorts{Master: p.Master + n, Data: p.Data + n, Ctrl: p.Ctrl + n, Status: p.Status + n, NVMe: p.NVMe + n, + WeedMaster: p.WeedMaster + n, WeedMasterG: p.WeedMasterG + n, WeedVolume: p.WeedVolume + n, WeedVolumeG: p.WeedVolumeG + n, + WeedFiler: p.WeedFiler + n, WeedFG: p.WeedFG + n, WeedAdmin: p.WeedAdmin + n, WeedAdminG: p.WeedAdminG + n} +} + +// weed are weed mini's ports, as mini sets and checks them. +func (p miniPorts) weed() []int { + return []int{p.WeedMaster, p.WeedMasterG, p.WeedVolume, p.WeedVolumeG, p.WeedFiler, p.WeedFG, p.WeedAdmin, p.WeedAdminG} +} + +var defaultMiniPorts = miniPorts{Master: 9180, Data: 9201, Ctrl: 9202, Status: 9203, NVMe: 4420, + WeedMaster: 9333, WeedMasterG: 19333, WeedVolume: 9340, WeedVolumeG: 19340, WeedFiler: 8888, WeedFG: 18888, + WeedAdmin: 12535, WeedAdminG: 22535} + +// miniStartWait bounds each child's readiness, and miniResolveWait the +// layout id lookup; miniStopWait bounds a child's exit after SIGTERM. +var ( + miniStartWait = 30 * time.Second + miniResolveWait = 60 * time.Second + miniStopWait = 10 * time.Second +) + +type miniConfig struct { + Dir, Bin, Weed, NQN string + Reuse bool + SizeBytes uint64 + PortShift int + Ports miniPorts + // Explicit names the flags given on the command line (fs.Visit); a + // --reuse refuses one that differs from the recorded run. + Explicit map[string]bool +} + +// miniRecord is what a fresh start records in /mini.json and --reuse +// starts again with: the volume's size, the ports, the mode and its weed, +// and the NQN. +type miniRecord struct { + SizeBytes uint64 `json:"size_bytes"` + PortShift int `json:"port_shift"` + Weed string `json:"weed,omitempty"` // empty: walstore, no weed + NQN string `json:"nqn"` + Bin string `json:"bin"` // the directory of blockmaster and blockvolume, absolute +} + +const miniRecordFile = "mini.json" + +func writeMiniRecord(dir string, r miniRecord) error { + b, err := json.MarshalIndent(r, "", " ") + if err != nil { + return err + } + return os.WriteFile(filepath.Join(dir, miniRecordFile), append(b, '\n'), 0o644) +} + +// reuseMiniRecord loads the recorded run into c: a flag given now must agree +// with the record, and a recorded weed must still be there (never a silent +// fall back to walstore). +func reuseMiniRecord(c *miniConfig, weedFound string) (string, error) { + b, err := os.ReadFile(filepath.Join(c.Dir, miniRecordFile)) + if err != nil { + return "", fmt.Errorf("--reuse: %s has no %s (it was not started by sw-block mini): %w", c.Dir, miniRecordFile, err) + } + var r miniRecord + if err := json.Unmarshal(b, &r); err != nil { + return "", fmt.Errorf("--reuse: %s/%s: %w", c.Dir, miniRecordFile, err) + } + differs := func(flag string, now, then any) error { + if c.Explicit[flag] && fmt.Sprint(now) != fmt.Sprint(then) { + return fmt.Errorf("--reuse: --%s %v differs from this dir's run (%v); drop it to reuse the run as recorded", flag, now, then) + } + return nil + } + for _, e := range []error{differs("size", c.SizeBytes, r.SizeBytes), differs("port-shift", c.PortShift, r.PortShift), + differs("nqn", c.NQN, r.NQN), differs("weed", c.Weed, r.Weed), differs("bin", c.Bin, r.Bin)} { + if e != nil { + return "", e + } + } + if r.Weed != "" { + if st, err := os.Stat(r.Weed); err != nil || st.IsDir() { + return "", fmt.Errorf("--reuse: this dir's run used weed %s, which is not there now (pass it again with --weed, or start a new dir)", r.Weed) + } + } + if c.Explicit["weed"] == false && weedFound != "" && r.Weed == "" { + return "", fmt.Errorf("--reuse: this dir's run is walstore (no weed); a weed is found now: start a new dir for walstore-chunk") + } + c.SizeBytes, c.NQN, c.Weed = r.SizeBytes, r.NQN, r.Weed + if r.Bin != "" { + c.Bin = r.Bin + } + if r.PortShift != c.PortShift { + c.Ports = defaultMiniPorts.shifted(r.PortShift) + c.PortShift = r.PortShift + } + return r.Weed, nil +} + +const ( + miniVolume = "v1" + miniServer = "s1" + miniReplica = "r1" + miniBlockSize = 4096 + miniChunkPath = "/swblock/chunks" +) + +func loopback(port int) string { return net.JoinHostPort("127.0.0.1", strconv.Itoa(port)) } + +// miniWeedArgs is weed mini bound to loopback only (-ip.bind; -ip alone is +// just the advertised address), its data under the run's dir, every +// listener's port explicit, and its S3, WebDAV and admin UI off. +func miniWeedArgs(c miniConfig) []string { + port := func(f string, p int) string { return "-" + f + "=" + strconv.Itoa(p) } + return []string{"mini", "-dir=" + filepath.Join(c.Dir, "weed"), "-ip=127.0.0.1", "-ip.bind=127.0.0.1", + port("master.port", c.Ports.WeedMaster), port("master.port.grpc", c.Ports.WeedMasterG), + port("volume.port", c.Ports.WeedVolume), port("volume.port.grpc", c.Ports.WeedVolumeG), + port("filer.port", c.Ports.WeedFiler), port("filer.port.grpc", c.Ports.WeedFG), + port("admin.port", c.Ports.WeedAdmin), port("admin.port.grpc", c.Ports.WeedAdminG), "-admin.port.legacy=0", + "-s3=false", "-webdav=false", "-admin.ui=false"} +} + +// miniMasterArgs is blockmaster as the standalone page runs it: with a chunk +// store (chunk), the lifecycle store, the cluster spec and the workspace RPC +// the walstore-chunk volume needs; without, the page's walstore topology. +func miniMasterArgs(c miniConfig, chunk bool) []string { + if !chunk { + return []string{"--authority-store", filepath.Join(c.Dir, "master"), "--listen", loopback(c.Ports.Master), + "--topology", filepath.Join(c.Dir, "topology.yaml"), "--expected-slots-per-volume", "1"} + } + return []string{"--authority-store", filepath.Join(c.Dir, "master", "authority"), "--lifecycle-store", filepath.Join(c.Dir, "master", "lifecycle"), + "--cluster-spec", filepath.Join(c.Dir, "cluster-spec.yaml"), "--expected-slots-per-volume", "1", "--listen", loopback(c.Ports.Master), + "--workspace-rpc", "--chunk-filer", loopback(c.Ports.WeedFG), "--chunk-path", miniChunkPath} +} + +// miniVolumeArgs is blockvolume as swb_start runs it, plus, with a chunk +// store, the walstore-chunk settings and the volume's layout id. +func miniVolumeArgs(c miniConfig, chunk bool, layoutID string) []string { + return miniVolumeSpec(c, chunk, layoutID).args() +} + +// miniVolumeSpec is mini's v1: the same settings volume start writes for a +// unit (volumeSpec), on loopback under the run's dir. +func miniVolumeSpec(c miniConfig, chunk bool, layoutID string) volumeSpec { + v := volumeSpec{Master: loopback(c.Ports.Master), ServerID: miniServer, VolumeID: miniVolume, ReplicaID: miniReplica, + DataAddr: loopback(c.Ports.Data), CtrlAddr: loopback(c.Ports.Ctrl), StatusAddr: loopback(c.Ports.Status), + DurableRoot: filepath.Join(c.Dir, "vol"), Blocks: c.SizeBytes / miniBlockSize, + NVMeListen: loopback(c.Ports.NVMe), NQN: c.NQN} + if chunk { + v.Chunk, v.BlockSize, v.ChunkFiler, v.ChunkPath, v.LayoutID = true, miniBlockSize, loopback(c.Ports.WeedFG), miniChunkPath, layoutID + } + return v +} + +// miniTopology and miniClusterSpec place v1 on s1/r1. +func miniTopology() string { + return fmt.Sprintf("volumes:\n - volume_id: %s\n slots:\n - replica_id: %s\n server_id: %s\n", miniVolume, miniReplica, miniServer) +} + +func miniClusterSpec(c miniConfig) string { + return fmt.Sprintf("nodes:\n - server_id: %s\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n - id: %s\n size_bytes: %d\n replication_factor: 1\n placements:\n - server_id: %s\n replica_id: %s\n", + miniServer, loopback(c.Ports.Data), loopback(c.Ports.Ctrl), miniVolume, c.SizeBytes, miniServer, miniReplica) +} + +// miniBanner is the fallback's first lines. +func miniBanner() string { + return `sw-block mini: no SeaweedFS "weed" binary found (--weed, or PATH). +sw-block mini: starting walstore: NO snapshots, NO restore. This is NOT the supported configuration. +sw-block mini: get weed from https://github.com/seaweedfs/seaweedfs/releases and pass --weed PATH. +` +} + +func parseSize(s string) (uint64, error) { + units := []struct { + suffix string + mult uint64 + }{{"GiB", 1 << 30}, {"MiB", 1 << 20}, {"KiB", 1 << 10}, {"G", 1 << 30}, {"M", 1 << 20}, {"K", 1 << 10}, {"", 1}} + for _, u := range units { + if strings.HasSuffix(s, u.suffix) { + n, err := strconv.ParseUint(strings.TrimSuffix(s, u.suffix), 10, 64) + if err != nil || n == 0 || n > ^uint64(0)/u.mult { + return 0, fmt.Errorf("invalid --size %q", s) + } + b := n * u.mult + if b%miniBlockSize != 0 { + return 0, fmt.Errorf("--size %q is not a multiple of %d bytes", s, miniBlockSize) + } + return b, nil + } + } + return 0, fmt.Errorf("invalid --size %q", s) +} + +// miniChild is one started process. +type miniChild struct { + name string + cmd *exec.Cmd + done chan struct{} + err error +} + +func (c *miniChild) exited() bool { + select { + case <-c.done: + return true + default: + return false + } +} + +type miniRun struct { + cfg miniConfig + out, log io.Writer + children []*miniChild +} + +// start prints the command, then starts it with its output in /.log. +func (r *miniRun) start(name, bin string, args []string) (*miniChild, error) { + fmt.Fprintf(r.out, "+ %s %s\n", bin, strings.Join(args, " ")) + lf, err := os.Create(filepath.Join(r.cfg.Dir, name+".log")) + if err != nil { + return nil, err + } + cmd := exec.Command(bin, args...) + cmd.Stdout, cmd.Stderr, cmd.Stdin = lf, lf, nil + if err := cmd.Start(); err != nil { + lf.Close() + return nil, fmt.Errorf("start %s: %w", name, err) + } + c := &miniChild{name: name, cmd: cmd, done: make(chan struct{})} + go func() { + c.err = cmd.Wait() + lf.Close() + close(c.done) + }() + r.children = append(r.children, c) + return c, nil +} + +// ready waits until every port listens, while c is alive, bounded. +func (r *miniRun) ready(ctx context.Context, c *miniChild, ports ...int) error { + deadline := time.Now().Add(miniStartWait) + for { + if d := r.dead(); d != nil { + return fmt.Errorf("%s exited during startup: %v (see %s.log)", d.name, d.err, d.name) + } + up := true + for _, p := range ports { + conn, err := net.DialTimeout("tcp", loopback(p), 200*time.Millisecond) + if err != nil { + up = false + break + } + conn.Close() + } + if up { + return nil + } + if time.Now().After(deadline) { + return fmt.Errorf("%s not ready within %s (ports %v; see %s.log)", c.name, miniStartWait, ports, c.name) + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(250 * time.Millisecond): + } + } +} + +// dead is the first child that has exited, if any. +func (r *miniRun) dead() *miniChild { + for _, c := range r.children { + if c.exited() { + return c + } + } + return nil +} + +// stop ends every child still running, the last started first: SIGTERM, +// a bounded wait, then SIGKILL. It is safe to call again. +func (r *miniRun) stop() { + for i := len(r.children) - 1; i >= 0; i-- { + c := r.children[i] + if c.exited() { + continue + } + fmt.Fprintf(r.out, "sw-block mini: stopping %s (pid %d)\n", c.name, c.cmd.Process.Pid) + if err := c.cmd.Process.Signal(syscall.SIGTERM); err != nil { + _ = c.cmd.Process.Kill() + } + select { + case <-c.done: + case <-time.After(miniStopWait): + fmt.Fprintf(r.out, "sw-block mini: %s did not exit within %s: killing it\n", c.name, miniStopWait) + _ = c.cmd.Process.Kill() + <-c.done + } + } +} + +// tail prints the last lines of each child's log. +func (r *miniRun) tail(n int) { + for _, c := range r.children { + b, err := os.ReadFile(filepath.Join(r.cfg.Dir, c.name+".log")) + if err != nil { + continue + } + lines := strings.Split(strings.TrimRight(string(b), "\n"), "\n") + if len(lines) > n { + lines = lines[len(lines)-n:] + } + fmt.Fprintf(r.log, "--- %s.log (last %d lines)\n%s\n", c.name, len(lines), strings.Join(lines, "\n")) + } +} + +func runMini(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block mini", flag.ContinueOnError) + fs.SetOutput(stderr) + fs.Usage = func() { fmt.Fprintln(stderr, miniUsage) } + cfg := miniConfig{Ports: defaultMiniPorts} + var size string + var shift int + fs.StringVar(&cfg.Dir, "dir", "./swb-mini", "data directory (refused if it exists, unless --reuse)") + fs.BoolVar(&cfg.Reuse, "reuse", false, "start again on an existing --dir") + fs.StringVar(&cfg.Weed, "weed", "", "SeaweedFS weed binary (default: weed on PATH)") + fs.StringVar(&cfg.Bin, "bin", "", "directory holding blockmaster and blockvolume (default: sw-block's own)") + fs.StringVar(&size, "size", "256MiB", "size of volume v1") + fs.StringVar(&cfg.NQN, "nqn", "nqn.2026-05.io.seaweedfs:v1", "NVMe subsystem NQN of v1") + fs.IntVar(&shift, "port-shift", 0, "move every port by this many (for a host where a default port is taken)") + if err := fs.Parse(args); err != nil || fs.NArg() != 0 { + if err == nil { + fs.Usage() + } + return ops.VolumeStatusExitInvalid + } + if shift < 0 || shift > 10000 { + fmt.Fprintf(stderr, "sw-block mini: --port-shift %d out of range 0..10000\n", shift) + return ops.VolumeStatusExitInvalid + } + cfg.Ports, cfg.PortShift = cfg.Ports.shifted(shift), shift + cfg.Explicit = map[string]bool{} + fs.Visit(func(f *flag.Flag) { cfg.Explicit[f.Name] = true }) + var err error + if cfg.SizeBytes, err = parseSize(size); err != nil { + fmt.Fprintf(stderr, "sw-block mini: %v\n", err) + return ops.VolumeStatusExitInvalid + } + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer cancel() + code, err := mini(ctx, cfg, stdout, stderr) + if err != nil { + fmt.Fprintf(stderr, "sw-block mini: %v\n", err) + } + return code +} + +// mini runs the configuration until ctx ends or a child exits. +func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, error) { + weed := cfg.Weed + if weed == "" { + weed, _ = exec.LookPath("weed") + } else if st, err := os.Stat(weed); err != nil || st.IsDir() { + return ops.VolumeStatusExitInvalid, fmt.Errorf("--weed %s not found", weed) + } + // A reuse takes the recorded run (its binaries included) before any + // lookup; a fresh start finds the binaries next to sw-block by default. + if cfg.Reuse { + if st, err := os.Stat(cfg.Dir); err != nil || !st.IsDir() { + return ops.VolumeStatusExitInvalid, fmt.Errorf("--reuse: %s is not an existing directory", cfg.Dir) + } + w, err := reuseMiniRecord(&cfg, weed) + if err != nil { + return ops.VolumeStatusExitInvalid, err + } + weed = w + } + if cfg.Bin == "" { + exe, err := os.Executable() + if err != nil { + return 1, fmt.Errorf("locate sw-block: %w (pass --bin)", err) + } + cfg.Bin = filepath.Dir(exe) + } + if abs, err := filepath.Abs(cfg.Bin); err == nil { + cfg.Bin = abs + } + master, volume := filepath.Join(cfg.Bin, "blockmaster"), filepath.Join(cfg.Bin, "blockvolume") + for _, b := range []string{master, volume} { + if st, err := os.Stat(b); err != nil || st.IsDir() { + return ops.VolumeStatusExitInvalid, fmt.Errorf("%s not found (pass --bin DIR)", b) + } + } + chunk := weed != "" + if !chunk { + fmt.Fprint(stdout, miniBanner()) + } + ports := []int{cfg.Ports.Master, cfg.Ports.Data, cfg.Ports.Ctrl, cfg.Ports.Status, cfg.Ports.NVMe} + if chunk { + ports = append(ports, cfg.Ports.weed()...) + } + for _, p := range ports { + l, err := net.Listen("tcp", loopback(p)) + if err != nil { + return ops.VolumeStatusExitInvalid, fmt.Errorf("port %d is in use: %v (move every port with --port-shift N)", p, err) + } + l.Close() + } + // The dir is claimed before anything is written: a fresh one by one + // exclusive mkdir, a reused one must exist; then a lock held for the run + // refuses a second mini on it. + if !cfg.Reuse { + if err := os.MkdirAll(filepath.Dir(filepath.Clean(cfg.Dir)), 0o755); err != nil { + return 1, err + } + if err := os.Mkdir(cfg.Dir, 0o755); err != nil { + if errors.Is(err, os.ErrExist) { + return ops.VolumeStatusExitInvalid, fmt.Errorf("%s exists: refusing to start over it (pass --reuse to start again on it, or another --dir)", cfg.Dir) + } + return 1, err + } + } + unlock, err := miniLock(cfg.Dir) + if err != nil { + return ops.VolumeStatusExitInvalid, err + } + defer unlock() + if !cfg.Reuse { + if err := writeMiniRecord(cfg.Dir, miniRecord{SizeBytes: cfg.SizeBytes, PortShift: cfg.PortShift, Weed: weed, NQN: cfg.NQN, Bin: cfg.Bin}); err != nil { + return 1, err + } + } + for _, d := range []string{filepath.Join(cfg.Dir, "master"), filepath.Join(cfg.Dir, "vol")} { + if err := os.MkdirAll(d, 0o755); err != nil { + return 1, err + } + } + r := &miniRun{cfg: cfg, out: stdout, log: stderr} + defer r.stop() + fail := func(err error) (int, error) { + r.tail(20) + return 1, err + } + if chunk { + if err := os.MkdirAll(filepath.Join(cfg.Dir, "weed"), 0o755); err != nil { + return 1, err + } + c, err := r.start("weed", weed, miniWeedArgs(cfg)) + if err != nil { + return fail(err) + } + if err := r.ready(ctx, c, cfg.Ports.weed()...); err != nil { + return fail(err) + } + if err := os.WriteFile(filepath.Join(cfg.Dir, "cluster-spec.yaml"), []byte(miniClusterSpec(cfg)), 0o644); err != nil { + return fail(err) + } + } else if err := os.WriteFile(filepath.Join(cfg.Dir, "topology.yaml"), []byte(miniTopology()), 0o644); err != nil { + return fail(err) + } + mc, err := r.start("blockmaster", master, miniMasterArgs(cfg, chunk)) + if err != nil { + return fail(err) + } + if err := r.ready(ctx, mc, cfg.Ports.Master); err != nil { + return fail(err) + } + layoutID := "" + if chunk { + fmt.Fprintf(stdout, "+ sw-block ops volume resolve --master %s %s\n", loopback(cfg.Ports.Master), miniVolume) + deadline := time.Now().Add(miniResolveWait) + for { + rctx, rcancel := context.WithTimeout(ctx, 5*time.Second) + id, err := resolveVolumeID(rctx, loopback(cfg.Ports.Master), miniVolume) + rcancel() + if err == nil { + layoutID = id.String() + break + } + if d := r.dead(); d != nil { + return fail(fmt.Errorf("%s exited while resolving %s's layout id: %v", d.name, miniVolume, d.err)) + } + if ctx.Err() != nil || time.Now().After(deadline) { + return fail(fmt.Errorf("resolve %s's layout id: %v", miniVolume, err)) + } + select { + case <-ctx.Done(): + case <-time.After(time.Second): + } + } + } + vc, err := r.start("blockvolume", volume, miniVolumeArgs(cfg, chunk, layoutID)) + if err != nil { + return fail(err) + } + if err := r.ready(ctx, vc, cfg.Ports.Status, cfg.Ports.NVMe); err != nil { + return fail(err) + } + miniNextSteps(stdout, cfg, chunk) + for { + for _, c := range r.children { + if c.exited() { + miniBeforeStop(stdout, cfg) + r.stop() + miniAfterStop(stdout, cfg) + return fail(fmt.Errorf("%s exited: %v; stopped the others", c.name, c.err)) + } + } + select { + case <-ctx.Done(): + fmt.Fprintln(stdout, "sw-block mini: interrupted: stopping") + miniBeforeStop(stdout, cfg) + r.stop() + miniAfterStop(stdout, cfg) + return 0, nil + case <-time.After(500 * time.Millisecond): + } + } +} + +// miniCommands are the sw-block commands mini prints for the user to run +// next (without the leading "sw-block"): only commands this binary has. +func miniCommands(c miniConfig, chunk bool) [][]string { + if !chunk { + return nil + } + m, f := loopback(c.Ports.Master), loopback(c.Ports.WeedFG) + return [][]string{ + {"ops", "workspace", "show", "--master", m, "--volume", miniVolume}, + {"ops", "chunk", "snapshots", "--master", m, "--volume", miniVolume, "--chunk-filer", f}, + {"ops", "chunk", "snapshot", "--volume", miniVolume, "--name", "first", "--status-addr", loopback(c.Ports.Status)}, + } +} + +func miniDisconnect(c miniConfig) string { + return "sudo nvme disconnect -n " + shQuote(c.NQN) +} + +// shQuote is s as one POSIX shell word: as is when it has only safe +// characters, else single-quoted, so a printed command with a path that has +// a space or a quote runs as printed. +func shQuote(s string) string { + if s != "" && strings.Trim(s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@%+=:,./_-") == "" { + return s + } + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} + +// miniResume is the command that starts the recorded run in c.Dir again. +func miniResume(c miniConfig) string { + return "sw-block mini --dir " + shQuote(c.Dir) + " --reuse" +} + +// miniNextSteps prints what to run next; mini runs none of it. +func miniNextSteps(w io.Writer, c miniConfig, chunk bool) { + mode := map[bool]string{true: "walstore-chunk on weed mini", false: "walstore, no snapshots"}[chunk] + fmt.Fprintf(w, "\nsw-block mini: running (%s). Ctrl-C stops everything it started. Logs: %s/*.log\n", mode, shQuote(c.Dir)) + fmt.Fprintln(w, "sw-block mini: trial setup: one host, loopback, no authentication.") + fmt.Fprintf(w, "\nAttach v1 (mini does not do this for you):\n sudo nvme connect -t tcp -a 127.0.0.1 -s %d -n %s --ctrl-loss-tmo=180 --reconnect-delay=2\n", c.Ports.NVMe, shQuote(c.NQN)) + fmt.Fprintf(w, "Before stopping mini: unmount anything on v1, then\n %s\n(else a mounted filesystem sits on a stopped target while the kernel retries for 3 minutes)\n", miniDisconnect(c)) + fmt.Fprintf(w, "\nStatus:\n curl -s 'http://%s/status?volume=%s'\n", loopback(c.Ports.Status), miniVolume) + if !chunk { + fmt.Fprintln(w, "\nsw-block mini: no chunk store: snapshots unavailable (run with weed for snapshots and restore)") + return + } + cmds := miniCommands(c, chunk) + fmt.Fprintf(w, "\nCheck the volume:\n sw-block %s\n sw-block %s\n", strings.Join(cmds[0], " "), strings.Join(cmds[1], " ")) + fmt.Fprintf(w, "\nSnapshot:\n sw-block %s\n", strings.Join(cmds[2], " ")) + fmt.Fprintf(w, "\nSeaweedFS itself: weed shell -master=%s\n", loopback(c.Ports.WeedMaster)) +} + +// miniBeforeStop reminds the user, before the target goes away, to have +// disconnected v1. +func miniBeforeStop(w io.Writer, c miniConfig) { + fmt.Fprintf(w, "sw-block mini: if v1 is connected: unmount it, then %s\n", miniDisconnect(c)) +} + +// miniAfterStop says where the data is and how to resume it. +func miniAfterStop(w io.Writer, c miniConfig) { + fmt.Fprintf(w, "sw-block mini: stopped. The data stays in %s. This starts it again, with this run's size, ports, mode, NQN and binaries (recorded in %s):\n %s\n", c.Dir, miniRecordFile, miniResume(c)) +} diff --git a/seaweed-block/cmd/sw-block/mini_lock_unix.go b/seaweed-block/cmd/sw-block/mini_lock_unix.go new file mode 100644 index 0000000000..95b5a74bea --- /dev/null +++ b/seaweed-block/cmd/sw-block/mini_lock_unix.go @@ -0,0 +1,25 @@ +//go:build !windows + +package main + +import ( + "fmt" + "os" + "path/filepath" + "syscall" +) + +// miniLock takes /.mini.lock exclusively for the life of one mini, so +// a second mini (a fresh start or a --reuse) on the same dir is refused +// before it writes anything. The lock ends with the process. +func miniLock(dir string) (func(), error) { + f, err := os.OpenFile(filepath.Join(dir, ".mini.lock"), os.O_CREATE|os.O_RDWR, 0o644) + if err != nil { + return nil, err + } + if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + f.Close() + return nil, fmt.Errorf("%s is in use by another sw-block mini", dir) + } + return func() { _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN); f.Close() }, nil +} diff --git a/seaweed-block/cmd/sw-block/mini_lock_windows.go b/seaweed-block/cmd/sw-block/mini_lock_windows.go new file mode 100644 index 0000000000..68fe532ba0 --- /dev/null +++ b/seaweed-block/cmd/sw-block/mini_lock_windows.go @@ -0,0 +1,20 @@ +//go:build windows + +package main + +import ( + "fmt" + "os" + "path/filepath" +) + +// miniLock on Windows (mini is a Linux tool; this keeps the package +// building): an exclusive create of /.mini.lock, removed at the end. +func miniLock(dir string) (func(), error) { + p := filepath.Join(dir, ".mini.lock") + f, err := os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0o644) + if err != nil { + return nil, fmt.Errorf("%s is in use by another sw-block mini", dir) + } + return func() { f.Close(); _ = os.Remove(p) }, nil +} diff --git a/seaweed-block/cmd/sw-block/mini_test.go b/seaweed-block/cmd/sw-block/mini_test.go new file mode 100644 index 0000000000..e7cf351f08 --- /dev/null +++ b/seaweed-block/cmd/sw-block/mini_test.go @@ -0,0 +1,802 @@ +package main + +import ( + "bytes" + "context" + "fmt" + "io" + "net" + "os" + "os/signal" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" + "sync" + "syscall" + "testing" + "time" +) + +// TestMain lets the test binary stand in for blockmaster and blockvolume: +// with SWB_MINI_FAKE_CHILD set it listens on the ports its flags name and +// waits for SIGTERM (or, with SWB_MINI_FAKE_CHILD=die-, the named +// child exits a moment after it is ready). +func TestMain(m *testing.M) { + if mode := os.Getenv("SWB_MINI_FAKE_CHILD"); mode != "" { + os.Exit(fakeMiniChild(mode)) + } + os.Exit(m.Run()) +} + +func fakeMiniChild(mode string) int { + name := filepath.Base(os.Args[0]) + var ls []net.Listener + listen := func(addr string) bool { + l, err := net.Listen("tcp", addr) + if err != nil { + return false + } + ls = append(ls, l) + return true + } + for i, a := range os.Args { + if (a == "--listen" || a == "--status-addr" || a == "--nvme-listen") && i+1 < len(os.Args) && !listen(os.Args[i+1]) { + return 3 + } + if k, v, ok := strings.Cut(a, "="); ok && strings.HasPrefix(k, "-") && strings.Contains(k, ".port") && !listen("127.0.0.1:"+v) { + return 3 + } + } + defer func() { + for _, l := range ls { + l.Close() + } + }() + term := make(chan os.Signal, 1) + signal.Notify(term, syscall.SIGTERM) + if mode == "die-"+name { + time.Sleep(500 * time.Millisecond) + return 9 + } + <-term + return 0 +} + +// The standalone page's swb_start block, as flag -> value (a flag without a +// value maps to ""). +func pageFlags(t *testing.T, binary string) map[string]string { + t.Helper() + b, err := os.ReadFile(filepath.Join("..", "..", "docs", "standalone-deployment.md")) + if err != nil { + t.Fatal(err) + } + doc := strings.ReplaceAll(string(b), "\r\n", "\n") + i := strings.Index(doc, "../"+binary+" ") + if i < 0 { + t.Fatalf("no ../%s command in the page", binary) + } + line := doc[i:] + end := strings.Index(line, "&\n") + if end < 0 { + t.Fatalf("../%s command has no end", binary) + } + cmd := strings.ReplaceAll(line[:end], "\\\n", " ") + cmd = cmd[:strings.Index(cmd, ">")] + return flagMap(strings.Fields(cmd)[1:]) +} + +func flagMap(args []string) map[string]string { + out := map[string]string{} + for i := 0; i < len(args); i++ { + if !strings.HasPrefix(args[i], "--") { + continue + } + v := "" + if i+1 < len(args) && !strings.HasPrefix(args[i+1], "--") { + v = strings.Trim(args[i+1], `"`) + i++ + } + out[args[i-boolToInt(v != "")]] = v + } + return out +} + +func boolToInt(b bool) int { + if b { + return 1 + } + return 0 +} + +// isPath reports whether a page value is a path (mini puts paths under its +// --dir instead of the page's ./). +func isPath(v string) bool { return strings.HasPrefix(v, "./") } + +// Without weed, mini runs blockmaster and blockvolume with exactly the +// standalone page's swb_start flags: the same names and, apart from paths +// (under --dir) and the size-derived block count, the same values. +func TestMiniWalstoreFlagsAreThePage(t *testing.T) { + cfg := miniConfig{Dir: "/tmp/m", NQN: "nqn.2026-05.io.seaweedfs:v1", SizeBytes: 256 << 20, Ports: defaultMiniPorts} + for _, c := range []struct { + binary string + args []string + }{ + {"blockmaster", miniMasterArgs(cfg, false)}, + {"blockvolume", miniVolumeArgs(cfg, false, "")}, + } { + page, got := pageFlags(t, c.binary), flagMap(c.args) + for f, pv := range page { + gv, ok := got[f] + switch { + case !ok: + t.Errorf("%s: the page passes %s; mini does not", c.binary, f) + case f == "--nvme-subsysnqn" && pv == "$NQN": + if gv != cfg.NQN { + t.Errorf("%s %s: mini %q, want the NQN %q", c.binary, f, gv, cfg.NQN) + } + case isPath(pv): + if !strings.HasPrefix(gv, filepath.Clean(cfg.Dir)) { + t.Errorf("%s %s: mini %q is not under --dir", c.binary, f, gv) + } + case gv != pv: + t.Errorf("%s %s: mini %q, the page %q", c.binary, f, gv, pv) + } + } + for f := range got { + if _, ok := page[f]; !ok { + t.Errorf("%s: mini passes %s; the page's swb_start does not", c.binary, f) + } + } + } +} + +// With weed, every flag mini passes is one the page documents. +func TestMiniChunkFlagsAreDocumented(t *testing.T) { + b, err := os.ReadFile(filepath.Join("..", "..", "docs", "standalone-deployment.md")) + if err != nil { + t.Fatal(err) + } + doc := string(b) + cfg := miniConfig{Dir: "/tmp/m", NQN: "n", SizeBytes: 256 << 20, Ports: defaultMiniPorts} + for _, args := range [][]string{miniMasterArgs(cfg, true), miniVolumeArgs(cfg, true, "00112233445566778899aabbccddeeff")} { + for f := range flagMap(args) { + if !strings.Contains(doc, "`"+f) && !strings.Contains(doc, f+" ") { + t.Errorf("mini passes %s, which the standalone page does not document", f) + } + } + } +} + +func TestMiniSize(t *testing.T) { + for in, want := range map[string]uint64{"256MiB": 256 << 20, "1GiB": 1 << 30, "4096": 4096, "2M": 2 << 20} { + if got, err := parseSize(in); err != nil || got != want { + t.Errorf("parseSize(%q) = %d %v, want %d", in, got, err, want) + } + } + for _, in := range []string{"", "0", "-1MiB", "100", "1.5GiB", "abc", "17179869184GiB", "17179869185GiB", "18446744073709551615K"} { + if _, err := parseSize(in); err == nil { + t.Errorf("parseSize(%q) accepted", in) + } + } +} + +// fakeBin makes a directory whose blockmaster and blockvolume are copies of +// the test binary (see TestMain). +func fakeBin(t *testing.T) string { + t.Helper() + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(self) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + for _, n := range []string{"blockmaster", "blockvolume", "weed"} { + if err := os.WriteFile(filepath.Join(dir, n), raw, 0o755); err != nil { + t.Fatal(err) + } + } + return dir +} + +func freePorts(t *testing.T) miniPorts { + t.Helper() + var ps []int + var ls []net.Listener + for i := 0; i < 13; i++ { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + ls = append(ls, l) + ps = append(ps, l.Addr().(*net.TCPAddr).Port) + } + for _, l := range ls { + l.Close() + } + return miniPorts{Master: ps[0], Data: ps[1], Ctrl: ps[2], Status: ps[3], NVMe: ps[4], + WeedMaster: ps[5], WeedMasterG: ps[6], WeedVolume: ps[7], WeedVolumeG: ps[8], WeedFiler: ps[9], WeedFG: ps[10], + WeedAdmin: ps[11], WeedAdminG: ps[12]} +} + +// The refusals happen before anything starts: an existing --dir without +// --reuse, a missing binary, a busy port. Without weed the banner comes +// first. +func TestMiniRefusesBeforeStarting(t *testing.T) { + t.Setenv("PATH", t.TempDir()) // no weed on PATH + bin := fakeBin(t) + base := func() miniConfig { + return miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: bin, NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)} + } + t.Run("existing dir", func(t *testing.T) { + c := base() + if err := os.MkdirAll(c.Dir, 0o755); err != nil { + t.Fatal(err) + } + var out bytes.Buffer + code, err := mini(context.Background(), c, &out, io.Discard) + if code == 0 || err == nil || !strings.Contains(err.Error(), "--reuse") { + t.Fatalf("existing dir: code %d err %v; want a refusal naming --reuse", code, err) + } + if !strings.HasPrefix(out.String(), miniBanner()) { + t.Fatalf("the fallback banner is not the first output:\n%s", out.String()) + } + }) + t.Run("missing binary", func(t *testing.T) { + c := base() + c.Bin = t.TempDir() + if code, err := mini(context.Background(), c, io.Discard, io.Discard); code == 0 || err == nil || !strings.Contains(err.Error(), "blockmaster") { + t.Fatalf("missing blockmaster: code %d err %v", code, err) + } + }) + t.Run("busy port", func(t *testing.T) { + c := base() + l, err := net.Listen("tcp", loopback(c.Ports.NVMe)) + if err != nil { + t.Fatal(err) + } + defer l.Close() + code, err := mini(context.Background(), c, io.Discard, io.Discard) + if code == 0 || err == nil || !strings.Contains(err.Error(), strconv.Itoa(c.Ports.NVMe)) { + t.Fatalf("busy port: code %d err %v", code, err) + } + if _, err := os.Stat(c.Dir); err == nil { + t.Fatal("a refused start created --dir") + } + }) +} + +type syncBuf struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *syncBuf) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.Write(p) +} + +func (s *syncBuf) String() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.String() +} + +func waitOutput(t *testing.T, out *syncBuf, want string) { + t.Helper() + deadline := time.Now().Add(20 * time.Second) + for !strings.Contains(out.String(), want) { + if time.Now().After(deadline) { + t.Fatalf("no %q in mini's output:\n%s", want, out.String()) + } + time.Sleep(50 * time.Millisecond) + } +} + +// pidsOf returns the pid of each "+ /" child mini started, from +// the stop lines it printed. +var stoppedRE = regexp.MustCompile(`stopping (\w+) \(pid (\d+)\)`) + +// Ctrl-C stops every child, the last started first, and leaves none running; +// mini prints each command before it runs it and the connect command, which +// it does not run. +func TestMiniInterruptStopsEveryChild(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("signals and listening children: Linux") + } + t.Setenv("PATH", t.TempDir()) + t.Setenv("SWB_MINI_FAKE_CHILD", "serve") + c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: fakeBin(t), NQN: "nqn.test:v1", SizeBytes: 1 << 20, Ports: freePorts(t)} + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + out := &syncBuf{} + done := make(chan int, 1) + go func() { code, _ := mini(ctx, c, out, io.Discard); done <- code }() + joined := false + t.Cleanup(func() { // registered before any assertion: a failure never leaks mini or its children + cancel() + if !joined { + select { + case <-done: + case <-time.After(30 * time.Second): + t.Error("mini did not stop at cleanup") + } + } + }) + waitOutput(t, out, "sw-block mini: running") + for _, want := range []string{"+ " + filepath.Join(c.Bin, "blockmaster") + " ", "+ " + filepath.Join(c.Bin, "blockvolume") + " ", "sudo nvme connect -t tcp -a 127.0.0.1 -s " + strconv.Itoa(c.Ports.NVMe) + " -n nqn.test:v1", "sudo nvme disconnect -n nqn.test:v1", + "sw-block mini: no chunk store: snapshots unavailable", "trial setup: one host, loopback, no authentication"} { + if !strings.Contains(out.String(), want) { + t.Fatalf("output lacks %q:\n%s", want, out.String()) + } + } + cancel() + select { + case code := <-done: + joined = true + if code != 0 { + t.Fatalf("interrupted mini exited %d", code) + } + case <-time.After(30 * time.Second): + t.Fatal("mini did not stop") + } + for _, want := range []string{"if v1 is connected: unmount it, then sudo nvme disconnect -n nqn.test:v1", "The data stays in " + c.Dir, " " + miniResume(c) + "\n"} { + if !strings.Contains(out.String(), want) { + t.Fatalf("at stop, output lacks %q:\n%s", want, out.String()) + } + } + if strings.Contains(out.String(), "cluster.check") || strings.Contains(out.String(), "sw-block shell") { + t.Fatal("mini prints a check or a shell this binary does not have") + } + stops := stoppedRE.FindAllStringSubmatch(out.String(), -1) + if len(stops) != 2 || stops[0][1] != "blockvolume" || stops[1][1] != "blockmaster" { + t.Fatalf("stop order %v; want blockvolume then blockmaster", stops) + } + for _, s := range stops { + pid, _ := strconv.Atoi(s[2]) + if processAlive(pid) { + t.Fatalf("%s (pid %d) still runs after mini stopped", s[1], pid) + } + } +} + +// A child that exits stops the others, and mini exits non-zero. +func TestMiniDeadChildStopsTheRest(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("signals and listening children: Linux") + } + t.Setenv("PATH", t.TempDir()) + t.Setenv("SWB_MINI_FAKE_CHILD", "die-blockvolume") + c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: fakeBin(t), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)} + out := &syncBuf{} + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + code, err := mini(ctx, c, out, io.Discard) + if code == 0 || err == nil || !strings.Contains(err.Error(), "blockvolume") { + t.Fatalf("a dead blockvolume: code %d err %v; want a non-zero exit naming it", code, err) + } + stops := stoppedRE.FindAllStringSubmatch(out.String(), -1) + if len(stops) != 1 || stops[0][1] != "blockmaster" { + t.Fatalf("stopped %v; want blockmaster stopped after blockvolume died", stops) + } + pid, _ := strconv.Atoi(stops[0][2]) + if processAlive(pid) { + t.Fatalf("blockmaster (pid %d) still runs", pid) + } +} + +// processAlive reports whether pid still runs (signal 0). +func processAlive(pid int) bool { + p, err := os.FindProcess(pid) + if err != nil { + return false + } + return p.Signal(syscall.Signal(0)) == nil +} + +// Every sw-block command mini prints is one this binary parses: run against +// ports where nothing listens, it may fail to connect, never on its flags. +// A control with an unknown flag shows the check sees a flag error. +func TestMiniPrintedCommandsParse(t *testing.T) { + c := miniConfig{Dir: t.TempDir(), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)} + cmds := miniCommands(c, true) + if len(cmds) == 0 { + t.Fatal("no commands") + } + flagError := func(args []string) (bool, string) { + var errb bytes.Buffer + run(args, io.Discard, &errb) + e := errb.String() + return strings.Contains(e, "flag provided but not defined") || strings.Contains(e, "usage:"), e + } + for _, args := range cmds { + if bad, e := flagError(args); bad { + t.Errorf("sw-block %s: refused its own flags: %s", strings.Join(args, " "), e) + } + } + if bad, _ := flagError(append(append([]string{}, cmds[0]...), "--no-such-flag")); !bad { + t.Fatal("control: an unknown flag was not reported as a flag error") + } + if miniCommands(c, false) != nil { + t.Fatal("without weed mini prints sw-block commands that need a chunk store") + } +} + +// wantChunkCommands is the supported configuration's three commands, pinned +// value for value; only the run's dir, the minted layout id and the ports +// (here the defaults) vary between runs. +func wantChunkCommands(dir, id string) map[string][]string { + return map[string][]string{ + "weed": {"mini", "-dir=" + filepath.Join(dir, "weed"), "-ip=127.0.0.1", "-ip.bind=127.0.0.1", + "-master.port=9333", "-master.port.grpc=19333", "-volume.port=9340", "-volume.port.grpc=19340", + "-filer.port=8888", "-filer.port.grpc=18888", "-admin.port=12535", "-admin.port.grpc=22535", "-admin.port.legacy=0", + "-s3=false", "-webdav=false", "-admin.ui=false"}, + "blockmaster": {"--authority-store", filepath.Join(dir, "master", "authority"), "--lifecycle-store", filepath.Join(dir, "master", "lifecycle"), + "--cluster-spec", filepath.Join(dir, "cluster-spec.yaml"), "--expected-slots-per-volume", "1", "--listen", "127.0.0.1:9180", + "--workspace-rpc", "--chunk-filer", "127.0.0.1:18888", "--chunk-path", "/swblock/chunks"}, + "blockvolume": {"--master", "127.0.0.1:9180", "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1", + "--data-addr", "127.0.0.1:9201", "--ctrl-addr", "127.0.0.1:9202", "--status-addr", "127.0.0.1:9203", + "--durable-root", filepath.Join(dir, "vol"), "--durable-impl", "walstore-chunk", "--durable-blocks", "65536", "--durable-blocksize", "4096", + "--chunk-filer", "127.0.0.1:18888", "--chunk-path", "/swblock/chunks", "--chunk-control-endpoint", "--workspace-lease", "--layout-id", id, + "--nvme-listen", "127.0.0.1:4420", "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:v1"}, + } +} + +func sameArgs(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// With weed, mini's weed, blockmaster and blockvolume commands are exactly +// the pinned ones; controls: a changed value and a dropped required flag +// are seen. +func TestMiniChunkCommandsArePinned(t *testing.T) { + dir, id := "/tmp/m", "00112233445566778899aabbccddeeff" + cfg := miniConfig{Dir: dir, NQN: "nqn.2026-05.io.seaweedfs:v1", SizeBytes: 256 << 20, Ports: defaultMiniPorts} + got := map[string][]string{"weed": miniWeedArgs(cfg), "blockmaster": miniMasterArgs(cfg, true), "blockvolume": miniVolumeArgs(cfg, true, id)} + want := wantChunkCommands(dir, id) + for name, w := range want { + if !sameArgs(got[name], w) { + t.Errorf("%s with weed:\n got %q\n want %q", name, got[name], w) + } + } + slots := append([]string{}, want["blockmaster"]...) + slots[7] = "2" // --expected-slots-per-volume + if sameArgs(slots, want["blockmaster"]) { + t.Fatal("control: a changed value compares equal") + } + dropped := append([]string{}, want["weed"][:3]...) + dropped = append(dropped, want["weed"][4:]...) // without -ip.bind + if sameArgs(dropped, want["weed"]) { + t.Fatal("control: a dropped flag compares equal") + } +} + +// --port-shift moves every port, weed's included. +func TestMiniPortShiftMovesEveryPort(t *testing.T) { + a, b := defaultMiniPorts, defaultMiniPorts.shifted(1000) + all := func(p miniPorts) []int { return append([]int{p.Master, p.Data, p.Ctrl, p.Status, p.NVMe}, p.weed()...) } + pa, pb := all(a), all(b) + for i := range pa { + if pb[i] != pa[i]+1000 { + t.Fatalf("port %d not shifted: %d -> %d", i, pa[i], pb[i]) + } + } + if len(pa) != 13 { + t.Fatalf("%d ports; mini owns 13", len(pa)) + } +} + +// With weed, a busy port of weed's (here its master gRPC, one weed would +// otherwise pick by itself) is refused before anything starts. +func TestMiniRefusesABusyWeedPort(t *testing.T) { + bin := fakeBin(t) + c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: bin, Weed: filepath.Join(bin, "weed"), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)} + l, err := net.Listen("tcp", loopback(c.Ports.WeedMasterG)) + if err != nil { + t.Fatal(err) + } + defer l.Close() + code, err := mini(context.Background(), c, io.Discard, io.Discard) + if code == 0 || err == nil || !strings.Contains(err.Error(), strconv.Itoa(c.Ports.WeedMasterG)) { + t.Fatalf("busy weed master gRPC port: code %d err %v", code, err) + } +} + +// One mini per dir: a second start on a dir another mini holds is refused +// before it writes, fresh or with --reuse; --reuse of a dir that does not +// exist is refused too. +func TestMiniDirIsOwnedByOneMini(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + bin := fakeBin(t) + dir := filepath.Join(t.TempDir(), "run") + if err := os.Mkdir(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := writeMiniRecord(dir, miniRecord{SizeBytes: 1 << 20, NQN: "n"}); err != nil { + t.Fatal(err) + } + unlock, err := miniLock(dir) + if err != nil { + t.Fatal(err) + } + defer unlock() + c := miniConfig{Dir: dir, Bin: bin, NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t), Reuse: true} + if code, err := mini(context.Background(), c, io.Discard, io.Discard); code == 0 || err == nil || !strings.Contains(err.Error(), "in use") { + t.Fatalf("--reuse of a held dir: code %d err %v; want a refusal", code, err) + } + if entries, _ := os.ReadDir(dir); len(entries) != 2 { // the lock and the record only + t.Fatalf("the refused start wrote into the held dir: %v", entries) + } + c.Reuse = false + if code, err := mini(context.Background(), c, io.Discard, io.Discard); code == 0 || err == nil || !strings.Contains(err.Error(), "--reuse") { + t.Fatalf("fresh start on a held dir: code %d err %v; want a refusal", code, err) + } + c.Dir, c.Reuse = filepath.Join(t.TempDir(), "absent"), true + if code, err := mini(context.Background(), c, io.Discard, io.Discard); code == 0 || err == nil || !strings.Contains(err.Error(), "not an existing directory") { + t.Fatalf("--reuse of an absent dir: code %d err %v", code, err) + } +} + +// A weed that dies while mini waits for blockmaster's layout id stops the +// rest at once, not at the resolve's 60 s bound. +func TestMiniWeedDyingDuringStartupStopsTheRest(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("signals and listening children: Linux") + } + t.Setenv("SWB_MINI_FAKE_CHILD", "die-weed") + bin := fakeBin(t) + c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: bin, Weed: filepath.Join(bin, "weed"), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)} + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + out := &syncBuf{} + start := time.Now() + code, err := mini(ctx, c, out, io.Discard) + if code == 0 || err == nil || !strings.Contains(err.Error(), "weed") { + t.Fatalf("weed died during startup: code %d err %v; want a failure naming weed", code, err) + } + if took := time.Since(start); took > 20*time.Second { + t.Fatalf("the death was seen after %s; want at once", took) + } + for _, s := range stoppedRE.FindAllStringSubmatch(out.String(), -1) { + pid, _ := strconv.Atoi(s[2]) + if processAlive(pid) { + t.Fatalf("%s (pid %d) still runs", s[1], pid) + } + } +} + +// --reuse starts the recorded run again: its size, ports, mode (its weed) +// and NQN, whatever the defaults are; a flag that differs from the record +// is refused, and so are a recorded weed that is gone and a walstore run +// while a weed is found. +func TestMiniReuseRestoresTheRecordedRun(t *testing.T) { + weed := filepath.Join(t.TempDir(), "weed") + if err := os.WriteFile(weed, []byte("x"), 0o755); err != nil { + t.Fatal(err) + } + bin := t.TempDir() + rec := miniRecord{SizeBytes: 1 << 30, PortShift: 1000, Weed: weed, NQN: "nqn.custom:v1", Bin: bin} + dir := t.TempDir() + if err := writeMiniRecord(dir, rec); err != nil { + t.Fatal(err) + } + defaults := func() miniConfig { + return miniConfig{Dir: dir, NQN: "nqn.2026-05.io.seaweedfs:v1", SizeBytes: 256 << 20, Ports: defaultMiniPorts, Reuse: true, Explicit: map[string]bool{}} + } + c := defaults() + got, err := reuseMiniRecord(&c, "") + if err != nil { + t.Fatal(err) + } + if got != weed || c.Weed != weed || c.SizeBytes != rec.SizeBytes || c.NQN != rec.NQN || c.PortShift != 1000 || c.Ports != defaultMiniPorts.shifted(1000) || c.Bin != bin { + t.Fatalf("reuse loaded %+v (weed %q); want the recorded run %+v", c, got, rec) + } + c = defaults() + c.Explicit["size"] = true + if _, err := reuseMiniRecord(&c, ""); err == nil || !strings.Contains(err.Error(), "--size") { + t.Fatalf("a --size that differs from the record: %v; want a refusal", err) + } + c = defaults() + c.Bin, c.Explicit["bin"] = t.TempDir(), true + if _, err := reuseMiniRecord(&c, ""); err == nil || !strings.Contains(err.Error(), "--bin") { + t.Fatalf("a --bin that differs from the record: %v; want a refusal", err) + } + c = defaults() + c.SizeBytes, c.Explicit["size"] = rec.SizeBytes, true + if _, err := reuseMiniRecord(&c, ""); err != nil { + t.Fatalf("a --size equal to the record: %v", err) + } + if err := os.Remove(weed); err != nil { + t.Fatal(err) + } + c = defaults() + if _, err := reuseMiniRecord(&c, ""); err == nil || !strings.Contains(err.Error(), "not there now") { + t.Fatalf("a recorded weed that is gone: %v; want a refusal, not a walstore fall back", err) + } + if err := writeMiniRecord(dir, miniRecord{SizeBytes: 1 << 20, NQN: "n"}); err != nil { + t.Fatal(err) + } + c = defaults() + if _, err := reuseMiniRecord(&c, "/usr/bin/weed"); err == nil || !strings.Contains(err.Error(), "walstore") { + t.Fatalf("a walstore run reused while a weed is found: %v; want a refusal", err) + } + c = defaults() + if _, err := reuseMiniRecord(&miniConfig{Dir: t.TempDir(), Explicit: map[string]bool{}}, ""); err == nil { + t.Fatal("a dir without a record was reused") + } + _ = c +} + +// End to end through mini: a run started with an explicit --bin records it, +// and a bare --reuse finds the same binaries (none are next to the test +// binary), stopping before any start only on its busy port. +func TestMiniReuseFindsTheRecordedBinaries(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + bin := fakeBin(t) + dir := filepath.Join(t.TempDir(), "run") + ports := freePorts(t) + c := miniConfig{Dir: dir, Bin: bin, NQN: "n", SizeBytes: 1 << 20, Ports: ports, Explicit: map[string]bool{"bin": true}} + l, err := net.Listen("tcp", loopback(ports.NVMe)) // stop each run before it starts children + if err != nil { + t.Fatal(err) + } + defer l.Close() + if code, err := mini(context.Background(), c, io.Discard, io.Discard); code == 0 || err == nil || !strings.Contains(err.Error(), "in use") { + t.Fatalf("setup: the fresh run should stop at the busy port: %d %v", code, err) + } + // The busy port refused before the dir was claimed: claim it as a real + // first run would, with the record. + if err := os.Mkdir(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := writeMiniRecord(dir, miniRecord{SizeBytes: 1 << 20, NQN: "n", Bin: bin}); err != nil { + t.Fatal(err) + } + r := miniConfig{Dir: dir, NQN: "nqn.2026-05.io.seaweedfs:v1", SizeBytes: 256 << 20, Ports: ports, Reuse: true, Explicit: map[string]bool{}} + code, err := mini(context.Background(), r, io.Discard, io.Discard) + if err == nil || strings.Contains(err.Error(), "not found") || !strings.Contains(err.Error(), "in use") { + t.Fatalf("bare --reuse: %d %v; want the recorded binaries found (then the busy port)", code, err) + } +} + +// shellWords splits a line as a POSIX shell does for words: blanks separate, +// '...' is literal, "..." keeps blanks (backslash escapes \\ \" \$ \`), and a +// backslash outside quotes escapes the next character. +func shellWords(line string) ([]string, error) { + var words []string + var w strings.Builder + in, quote := false, byte(0) + for i := 0; i < len(line); i++ { + ch := line[i] + switch { + case quote == '\'': + if ch == '\'' { + quote = 0 + } else { + w.WriteByte(ch) + } + case quote == '"': + if ch == '"' { + quote = 0 + } else if ch == '\\' && i+1 < len(line) && strings.IndexByte("\\\"$`", line[i+1]) >= 0 { + i++ + w.WriteByte(line[i]) + } else { + w.WriteByte(ch) + } + case ch == '\'' || ch == '"': + quote, in = ch, true + case ch == '\\' && i+1 < len(line): + i++ + w.WriteByte(line[i]) + in = true + case ch == ' ' || ch == '\t': + if in { + words = append(words, w.String()) + w.Reset() + in = false + } + default: + w.WriteByte(ch) + in = true + } + } + if quote != 0 { + return nil, fmt.Errorf("unterminated %c quote", quote) + } + if in { + words = append(words, w.String()) + } + return words, nil +} + +func TestShQuoteRoundTrips(t *testing.T) { + for _, in := range []string{"plain", "/tmp/a b", "it's", `a"b`, "$HOME", "a\\b", "", "x;rm -rf y", "nqn.2026-05.io.seaweedfs:v1"} { + got, err := shellWords("cmd " + shQuote(in)) + if err != nil || len(got) != 2 || got[1] != in { + t.Errorf("shQuote(%q) = %s: the shell reads %q (%v)", in, shQuote(in), got, err) + } + } + if shQuote("nqn.2026-05.io.seaweedfs:v1") != "nqn.2026-05.io.seaweedfs:v1" { + t.Error("a safe word was quoted") + } +} + +// The printed resume line, run as printed (split as a shell splits it), on +// a dir with a space and a quote, reaches that dir's recorded run: it stops +// only at the lock this test holds, naming the dir. Control: the same line +// with the dir unquoted is not that command. +func TestMiniPrintedResumeRunsOnASpacedDir(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + bin := fakeBin(t) + dir := filepath.Join(t.TempDir(), "my run's dir") + if err := os.Mkdir(dir, 0o755); err != nil { + t.Fatal(err) + } + shift := -1 + for s := 3000; s <= 10000 && shift < 0; s += 37 { // a shift whose walstore ports are free here + p, free := defaultMiniPorts.shifted(s), true + for _, port := range []int{p.Master, p.Data, p.Ctrl, p.Status, p.NVMe} { + l, err := net.Listen("tcp", loopback(port)) + if err != nil { + free = false + break + } + l.Close() + } + if free { + shift = s + } + } + if shift < 0 { + t.Skip("no free shifted ports") + } + if err := writeMiniRecord(dir, miniRecord{SizeBytes: 1 << 20, PortShift: shift, NQN: "n", Bin: bin}); err != nil { + t.Fatal(err) + } + unlock, err := miniLock(dir) + if err != nil { + t.Fatal(err) + } + defer unlock() + var out bytes.Buffer + miniAfterStop(&out, miniConfig{Dir: dir}) + var line string + for _, l := range strings.Split(out.String(), "\n") { + if strings.HasPrefix(strings.TrimSpace(l), "sw-block mini ") { + line = strings.TrimSpace(l) + } + } + runLine := func(line string) (int, string) { + words, err := shellWords(line) + if err != nil { + return -1, err.Error() + } + if len(words) < 2 || words[0] != "sw-block" || words[1] != "mini" { + return -1, fmt.Sprintf("not a sw-block mini command: %q", words) + } + var errb bytes.Buffer + code := runMini(words[2:], io.Discard, &errb) + return code, errb.String() + } + code, e := runLine(line) + if code == 0 || !strings.Contains(e, dir+" is in use") { + t.Fatalf("the printed line %s: exit %d, %q; want it to reach %s (held here)", line, code, e, dir) + } + raw := "sw-block mini --dir " + dir + " --reuse" + if code, e := runLine(raw); strings.Contains(e, dir+" is in use") { + t.Fatalf("control: the unquoted line reached the dir too (exit %d)", code) + } +} diff --git a/seaweed-block/cmd/sw-block/retired_migration_test.go b/seaweed-block/cmd/sw-block/retired_migration_test.go new file mode 100644 index 0000000000..abeee49977 --- /dev/null +++ b/seaweed-block/cmd/sw-block/retired_migration_test.go @@ -0,0 +1,32 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "testing" +) + +func TestRetiredMigrationCommandRefusesWithoutMutation(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "legacy") + want := []byte("unmodified legacy volume") + if err := os.WriteFile(path, want, 0600); err != nil { + t.Fatal(err) + } + var out, errout bytes.Buffer + if code := run([]string{"migrate-v3", "--path", path}, &out, &errout); code == 0 { + t.Fatal("retired converter accepted input") + } + if !bytes.Contains(errout.Bytes(), []byte("unknown command")) { + t.Fatalf("converter still dispatched: %s", errout.Bytes()) + } + got, err := os.ReadFile(path) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("retired converter changed input: %v", err) + } + entries, err := os.ReadDir(dir) + if err != nil || len(entries) != 1 { + t.Fatalf("retired converter created sidecars: %v %v", entries, err) + } +} diff --git a/seaweed-block/cmd/sw-block/shell.go b/seaweed-block/cmd/sw-block/shell.go new file mode 100644 index 0000000000..0ebd29a309 --- /dev/null +++ b/seaweed-block/cmd/sw-block/shell.go @@ -0,0 +1,231 @@ +package main + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" +) + +type inspectionShell struct { + master, filer, chunkPath, statusAddr, serverID string + timeout, maxClockSkew time.Duration +} + +func runShell(args []string, input io.Reader, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block shell", flag.ContinueOnError) + fs.SetOutput(stderr) + s := inspectionShell{} + var command string + fs.StringVar(&s.master, "master", "", "blockmaster address") + fs.StringVar(&s.filer, "filer", "", "filer address, for direct store inspections") + fs.StringVar(&s.chunkPath, "chunkPath", defaultChunkPathCLI, "block metadata directory") + fs.StringVar(&s.statusAddr, "status-addr", "", "this host's loopback holder status address") + local, _ := os.Hostname() + fs.StringVar(&s.serverID, "server-id", local, "this host's blockvolume server-id") + fs.DurationVar(&s.timeout, "timeout", 10*time.Second, "bound for each command") + fs.DurationVar(&s.maxClockSkew, "max-clock-skew", 20*time.Second, "master's configured workspace skew bound") + fs.StringVar(&command, "c", "", "one command instead of reading stdin") + if fs.Parse(args) != nil || fs.NArg() != 0 || s.master == "" || s.timeout <= 0 || s.maxClockSkew <= 0 { + fmt.Fprintln(stderr, "usage: sw-block shell -master ADDR [-filer ADDR] [-status-addr ADDR -server-id ID] [-c 'cluster.status -o json']") + return 2 + } + if command != "" { + return s.execute(command, stdout, stderr) + } + interactive := false + if f, ok := input.(*os.File); ok { + if info, err := f.Stat(); err == nil { + interactive = info.Mode()&os.ModeCharDevice != 0 + } + } + scanner := bufio.NewScanner(input) + scanner.Buffer(make([]byte, 4096), 64<<10) + code := 0 + for { + if interactive { + fmt.Fprint(stdout, "sw-block> ") + } + if !scanner.Scan() { + break + } + line := strings.TrimSpace(scanner.Text()) + if line == "quit" || line == "exit" { + break + } + if line == "" { + continue + } + if c := s.execute(line, stdout, stderr); c != 0 { + code = c + } + } + if err := scanner.Err(); err != nil { + fmt.Fprintln(stderr, err) + return 2 + } + return code +} + +// Shell words support quoting, but never variable expansion or command execution. +func inspectionWords(line string) ([]string, error) { + var words []string + var word strings.Builder + var quote rune + escaped, active := false, false + for _, r := range line { + if escaped { + word.WriteRune(r) + escaped = false + active = true + continue + } + if r == '\\' && quote != '\'' { + escaped = true + active = true + continue + } + if quote != 0 { + if r == quote { + quote = 0 + } else { + word.WriteRune(r) + } + active = true + continue + } + if r == '\'' || r == '"' { + quote = r + active = true + continue + } + if r == ' ' || r == '\t' { + if active { + words = append(words, word.String()) + word.Reset() + active = false + } + continue + } + word.WriteRune(r) + active = true + } + if quote != 0 || escaped { + return nil, errors.New("unfinished quote or escape") + } + if active { + words = append(words, word.String()) + } + return words, nil +} + +func (s inspectionShell) execute(line string, stdout, stderr io.Writer) int { + words, err := inspectionWords(line) + if err != nil { + fmt.Fprintln(stderr, err) + return 2 + } + if len(words) == 0 { + return 0 + } + name, args := words[0], words[1:] + if name == "log.collect" { + return s.collectLogs(args, stdout, stderr) + } + if name == "help" { + fmt.Fprintln(stdout, "cluster.status, cluster.check [volume], volume.list, volume.status , volume.explain , snapshot.list , store.show , store.usage , volume.verify , log.collect -out DIR; each supports -o json; quit") + return 0 + } + format := "text" + var positional []string + for i := 0; i < len(args); i++ { + if args[i] == "-o" { + i++ + if i == len(args) { + return 2 + } + format = args[i] + } else { + positional = append(positional, args[i]) + } + } + if format != "text" && format != "json" { + fmt.Fprintln(stderr, "output must be text or json") + return 2 + } + if name == "cluster.check" { + if len(positional) > 1 { + fmt.Fprintln(stderr, "cluster.check accepts at most one volume") + return 2 + } + volume := "" + if len(positional) == 1 { + volume = positional[0] + } + return s.check(volume, format, stdout, stderr) + } + if name == "snapshot.list" || name == "store.show" || name == "store.usage" || name == "volume.verify" { + if len(positional) != 1 || s.filer == "" { + fmt.Fprintf(stderr, "%s requires a volume and shell -filer\n", name) + return 2 + } + run := map[string]func([]string, io.Writer, io.Writer) int{"snapshot.list": chunkSnapshots, "store.show": chunkShow, "store.usage": chunkUsage, "volume.verify": chunkVerify}[name] + return run([]string{"--master", s.master, "--chunk-filer", s.filer, "--chunk-path", s.chunkPath, "--timeout", s.timeout.String(), "--volume", positional[0]}, stdout, stderr) + } + if name != "cluster.status" && name != "volume.list" && name != "volume.status" && name != "volume.explain" { + fmt.Fprintf(stderr, "unknown inspection command %q; use help\n", name) + return 2 + } + want := 0 + if name == "volume.status" || name == "volume.explain" { + want = 1 + } + if len(positional) != want { + fmt.Fprintf(stderr, "%s needs %d volume arguments\n", name, want) + return 2 + } + ctx, cancel := context.WithTimeout(context.Background(), s.timeout) + defer cancel() + cluster, err := readMasterClusterEvidence(ctx, s.master) + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", name, err) + return 1 + } + var value any = cluster + text := ops.RenderClusterEvidenceText(cluster) + if name == "volume.list" { + value = cluster.Volumes + } + if want == 1 { + found := false + for _, v := range cluster.Volumes { + if v.VolumeID == positional[0] { + value = v + text = ops.RenderVolumeEvidenceText(v) + found = true + break + } + } + if !found { + fmt.Fprintf(stderr, "volume %q not found\n", positional[0]) + return 1 + } + } + if format == "json" { + if err := json.NewEncoder(stdout).Encode(value); err != nil { + fmt.Fprintln(stderr, err) + return 1 + } + } else { + fmt.Fprint(stdout, text) + } + return 0 +} diff --git a/seaweed-block/cmd/sw-block/shell_check.go b/seaweed-block/cmd/sw-block/shell_check.go new file mode 100644 index 0000000000..3fa0fd1b27 --- /dev/null +++ b/seaweed-block/cmd/sw-block/shell_check.go @@ -0,0 +1,531 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type inspectionCheck struct { + ID, Title, Reach, Cure string + Run func(*inspectionObservation) checkFinding +} + +type checkFinding struct{ Status, Finding string } +type inspectionResult struct { + ID, Title, Reach, Status, Finding string + Cure, See string `json:",omitempty"` +} + +func checkOK(s string) checkFinding { return checkFinding{"ok", s} } +func checkFail(s string) checkFinding { return checkFinding{"FAIL", s} } +func checkElsewhere(s string) checkFinding { return checkFinding{"not checked here", s} } + +type holderInspection struct { + VolumeID, ReplicaID, Version, NotReadyReason string + Epoch uint64 + FrontendPrimaryReady *bool +} +type durableInspection struct { + ProcessID string + Volumes []struct { + VolumeID string + Impl string + Chunk *struct { + Maintenance *struct { + PassesOK *uint64 `json:"passesOk"` + InProgress *bool `json:"inProgress"` + CurrentStartNs *int64 `json:"currentStartNs"` + LastPass *struct { + AtNs *int64 `json:"atNs"` + Planned *uint64 `json:"planned"` + Removed *uint64 `json:"removed"` + Error *string `json:"error"` + HeadGen *uint64 `json:"headGen"` + HeadGenError *string `json:"headGenError"` + PlannedChunks *uint64 `json:"plannedChunks"` + PlannedRoots *uint64 `json:"plannedRoots"` + PlannedSegments *uint64 `json:"plannedSegments"` + RemovedChunks *uint64 `json:"removedChunks"` + RemovedRoots *uint64 `json:"removedRoots"` + RemovedSegments *uint64 `json:"removedSegments"` + } `json:"lastPass"` + } + Attached bool + Stats *struct { + LastCutNs *int64 + CutsFailed *uint64 + PendingUnresolved *bool + } + ScheduledSnapshot *struct { + Overdue bool `json:"snapshot_overdue"` + LastFailure *struct{ Code string } `json:"lastFailure"` + } + CurrentCut *struct { + Phase string `json:"phase"` + AttemptStartedAt time.Time `json:"attempt_started_at"` + } + } + } +} +type inspectedVolume struct { + evidence ops.VolumeEvidence + lease *control.WorkspaceStatus + leaseErr error + holder holderInspection + durable durableInspection + holderErr, durableErr error + local bool +} +type inspectionObservation struct { + shell inspectionShell + cluster ops.ClusterEvidence + masterErr, lifecycleErr, filerErr error + filerChecked bool + started, ended time.Time + volumes []inspectedVolume + requested string +} + +func (s inspectionShell) check(volume, format string, stdout, stderr io.Writer) int { + ctx, cancel := context.WithTimeout(context.Background(), s.timeout) + defer cancel() + return s.checkContext(ctx, volume, format, stdout, stderr) +} + +func (s inspectionShell) checkContext(ctx context.Context, volume, format string, stdout, stderr io.Writer, volumeLimits ...int) int { + o := &inspectionObservation{shell: s, requested: volume, started: time.Now()} + o.cluster, o.masterErr = readMasterClusterEvidence(ctx, s.master) + o.ended = time.Now() + return s.checkObservation(ctx, o, format, stdout, stderr, volumeLimits...) +} + +func (s inspectionShell) checkObservation(ctx context.Context, o *inspectionObservation, format string, stdout, stderr io.Writer, volumeLimits ...int) int { + volume := o.requested + if o.masterErr == nil { + conn, err := link.DialMasterFromEnv(s.master) + o.lifecycleErr = err + if err == nil { + defer conn.Close() + client := control.NewWorkspaceServiceClient(conn) + // A nonexistent name still distinguishes a missing lifecycle store or disabled RPC. + _, err = client.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "__cluster_check__"}) + if status.Code(err) == codes.NotFound { + err = nil + } + o.lifecycleErr = err + volumes := o.cluster.Volumes + if len(volumeLimits) > 0 && volumeLimits[0] > 0 && len(volumes) > volumeLimits[0] { + volumes = volumes[:volumeLimits[0]] + } + for _, v := range volumes { + if volume != "" && v.VolumeID != volume { + continue + } + iv := inspectedVolume{evidence: v} + iv.lease, iv.leaseErr = client.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: v.VolumeID}) + iv.local = primaryInspectionHost(v) != "" && primaryInspectionHost(v) == s.serverID + if iv.local { + iv.holderErr = s.readHolder(ctx, "/status", v.VolumeID, &iv.holder) + if iv.holderErr == nil && (iv.holder.VolumeID != v.VolumeID || iv.holder.ReplicaID != v.PrimaryReplica || iv.holder.Epoch != v.Epoch) { + iv.holderErr = errors.New("holder status identity differs from master's primary") + } + iv.durableErr = s.readHolder(ctx, "/status/durable", v.VolumeID, &iv.durable) + } + o.volumes = append(o.volumes, iv) + } + } + } + if s.filer != "" { + o.filerChecked = true + f, closeF, err := dialChunkFiler(s.filer) + if err == nil { + err = checkSingleFiler(ctx, f) + _ = closeF() + } + o.filerErr = err + } + rows := make([]inspectionResult, 0, len(inspectionChecks)) + code := 0 + for _, c := range inspectionChecks { + f := c.Run(o) + if o.masterErr != nil && c.ID != "master.reachable" && c.ID != "filer.single" { + f = checkElsewhere("master did not answer; prerequisite unavailable") + } + r := inspectionResult{ID: c.ID, Title: c.Title, Reach: c.Reach, Status: f.Status, Finding: f.Finding} + r.Finding = strings.Join(strings.Fields(r.Finding), " ") + if f.Status == "FAIL" { + code = 1 + r.Cure = c.Cure + r.See = "docs/troubleshooting.md#" + strings.ReplaceAll(c.ID, ".", "") + } else if f.Status == "not checked here" && code == 0 { + code = 3 + } + rows = append(rows, r) + } + if format == "json" { + if err := json.NewEncoder(stdout).Encode(rows); err != nil { + fmt.Fprintln(stderr, err) + return 1 + } + } else { + for _, r := range rows { + fmt.Fprintf(stdout, "%s %s: %s\n", r.Status, r.ID, r.Finding) + if r.Status == "FAIL" { + fmt.Fprintf(stdout, " cure: %s; see %s\n", r.Cure, r.See) + } + } + } + return code +} + +func (s inspectionShell) readHolder(ctx context.Context, path, volume string, dst any) error { + if s.statusAddr == "" { + return errors.New("status page is off: start blockvolume with --status-addr 127.0.0.1:") + } + base := s.statusAddr + if !strings.Contains(base, "://") { + base = "http://" + base + } + u, err := url.Parse(base) + if err != nil { + return err + } + ip := net.ParseIP(u.Hostname()) + if u.Scheme != "http" || ip == nil || !ip.IsLoopback() || u.User != nil || u.RawQuery != "" || (u.Path != "" && u.Path != "/") { + return errors.New("holder status requires an explicit loopback HTTP address") + } + u.Path = path + q := url.Values{} + q.Set("volume", volume) + u.RawQuery = q.Encode() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + if err != nil { + return err + } + client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("status redirects are refused") }} + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("%s returned HTTP %d", path, resp.StatusCode) + } + raw, err := io.ReadAll(io.LimitReader(resp.Body, (2<<20)+1)) + if err != nil { + return err + } + if len(raw) > 2<<20 { + return errors.New("status exceeds 2 MiB") + } + return json.Unmarshal(raw, dst) +} + +func primaryInspectionHost(v ops.VolumeEvidence) string { + if v.PrimaryNode != "" { + return v.PrimaryNode + } + for _, r := range v.Replicas { + if r.ReplicaID == v.PrimaryReplica { + return r.ServerID + } + } + return "" +} +func (o *inspectionObservation) each(local bool, run func(inspectedVolume) checkFinding) checkFinding { + if len(o.volumes) == 0 { + return checkElsewhere("no selected volume evidence") + } + state := "ok" + allNotApplicable := true + parts := []string{} + for _, v := range o.volumes { + var f checkFinding + if local && !v.local { + host := primaryInspectionHost(v.evidence) + if host == "" { + host = "unknown holder host" + } + f = checkElsewhere("run on " + host) + } else { + f = run(v) + } + if f.Status != "not applicable" { + allNotApplicable = false + } + if f.Status == "FAIL" { + state = "FAIL" + } else if f.Status == "not checked here" && state != "FAIL" { + state = "not checked here" + } + parts = append(parts, v.evidence.VolumeID+": "+f.Status+" "+f.Finding) + } + if state == "ok" && allNotApplicable { + state = "not applicable" + } + return checkFinding{state, strings.Join(parts, "; ")} +} +func (o *inspectionObservation) reachable() checkFinding { + if o.masterErr != nil { + return checkFail(o.masterErr.Error()) + } + return checkOK(o.shell.master + " answered") +} +func (o *inspectionObservation) lifecycle() checkFinding { + if o.lifecycleErr != nil { + return checkFail(o.lifecycleErr.Error()) + } + return checkOK("workspace query accepted") +} +func (o *inspectionObservation) version() checkFinding { + if unknownInspectionVersion(o.cluster.ProductRevision) { + return checkFail("no version reported") + } + return checkOK(o.cluster.ProductRevision) +} +func unknownInspectionVersion(v string) bool { + return v == "" || strings.Contains(strings.ToLower(v), "unknown") +} +func (o *inspectionObservation) filer() checkFinding { + if !o.filerChecked { + return checkElsewhere("set shell -filer for the single-filer check") + } + if o.filerErr != nil { + return checkFail(o.filerErr.Error()) + } + return checkOK("one filer in its group at this moment") +} +func (o *inspectionObservation) heartbeat() checkFinding { + return o.each(false, func(v inspectedVolume) checkFinding { + if len(v.evidence.Replicas) == 0 { + return checkFail("no slot observations") + } + for _, r := range v.evidence.Replicas { + if !r.Observed { + return checkFail(r.ServerID + " not observed") + } + } + return checkOK("all slots observed; age not available") + }) +} +func (o *inspectionObservation) known() checkFinding { + if o.requested != "" && len(o.volumes) == 0 { + return checkFail(o.requested + " not found") + } + if len(o.volumes) == 0 { + return checkElsewhere("no volumes registered") + } + return checkOK(fmt.Sprintf("%d volume records", len(o.volumes))) +} +func (o *inspectionObservation) assigned() checkFinding { + return o.each(false, func(v inspectedVolume) checkFinding { + if v.evidence.Epoch == 0 || v.evidence.PrimaryReplica == "" { + return checkFail("no primary (epoch 0)") + } + return checkOK(fmt.Sprintf("%s@%d on %s", v.evidence.PrimaryReplica, v.evidence.Epoch, primaryInspectionHost(v.evidence))) + }) +} +func (o *inspectionObservation) lease() checkFinding { + return o.each(false, func(v inspectedVolume) checkFinding { + if v.evidence.ReplicationFactor != 1 { + return checkElsewhere("workspace lease check applies to RF1") + } + if v.leaseErr != nil { + return checkFail(v.leaseErr.Error()) + } + l := v.lease.GetLease() + if l == nil || l.GetEpoch() != v.evidence.Epoch || l.GetReplicaId() != v.evidence.PrimaryReplica || l.GetValidForNs() <= 0 || l.GetRevoking() { + return checkFail("lease absent, expired, revoking or differs from the observed primary") + } + return checkOK("granted, not revoking (master observation)") + }) +} +func (o *inspectionObservation) frontend() checkFinding { + return o.each(true, func(v inspectedVolume) checkFinding { + if v.holderErr != nil { + return checkFail(v.holderErr.Error()) + } + if v.holder.FrontendPrimaryReady == nil { + return checkFail("frontend readiness field unavailable") + } + if !*v.holder.FrontendPrimaryReady { + return checkFail(v.holder.NotReadyReason) + } + return checkOK("holder's frontend serves") + }) +} +func (o *inspectionObservation) chunkstore() checkFinding { + return o.each(true, func(v inspectedVolume) checkFinding { + if v.holderErr != nil { + return checkFail(v.holderErr.Error()) + } + if v.durableErr != nil { + return checkFail(v.durableErr.Error()) + } + for _, d := range v.durable.Volumes { + if d.VolumeID != v.evidence.VolumeID { + continue + } + switch d.Impl { + case "walstore-chunk": + if d.Chunk == nil { + return checkElsewhere("chunk store status unavailable") + } + return checkOK("chunk store configured; snapshot observations follow") + case "walstore": + return checkOK("local engine only: no snapshots; not the supported configuration (start with a filer, see sw-block mini --weed)") + default: + return checkElsewhere("chunk store implementation unavailable") + } + } + return checkElsewhere("selected volume absent from durable status") + }) +} +func (o *inspectionObservation) cut() checkFinding { + return o.each(true, func(v inspectedVolume) checkFinding { + if v.holderErr != nil { + return checkFail(v.holderErr.Error()) + } + if v.durableErr != nil { + return checkFail(v.durableErr.Error()) + } + for _, d := range v.durable.Volumes { + if d.VolumeID != v.evidence.VolumeID { + continue + } + if d.Impl == "walstore" { + return checkFinding{"not applicable", "no chunk store"} + } + if d.Chunk == nil || d.Chunk.Stats == nil { + return checkFail("cut counters unavailable") + } + c := d.Chunk + st := c.Stats + if st.LastCutNs == nil || st.CutsFailed == nil || st.PendingUnresolved == nil { + return checkFail("cut counter fields unavailable") + } + finding := fmt.Sprintf("last_cut_ns=%d historical_failures=%d", *st.LastCutNs, *st.CutsFailed) + if c.CurrentCut != nil { + finding += fmt.Sprintf(" cut in phase %s since %s", c.CurrentCut.Phase, c.CurrentCut.AttemptStartedAt.UTC().Format(time.RFC3339Nano)) + } + if *st.PendingUnresolved { + return checkFail(finding + " pending HEAD outcome unresolved") + } + if c.ScheduledSnapshot != nil && c.ScheduledSnapshot.Overdue { + code := "" + if c.ScheduledSnapshot.LastFailure != nil { + code = c.ScheduledSnapshot.LastFailure.Code + } + return checkFail(finding + " snapshot_overdue " + code) + } + if *st.CutsFailed > 0 { + return checkElsewhere(finding + "; one observation cannot prove a new failure; see the holder log") + } + if *st.LastCutNs == 0 { + return checkElsewhere(finding + "; no completed cut since start") + } + return checkOK(finding) + } + return checkFail("selected volume absent from durable status") + }) +} +func (o *inspectionObservation) cleaning() checkFinding { + return o.each(true, func(v inspectedVolume) checkFinding { + if v.holderErr != nil { + return checkFail(v.holderErr.Error()) + } + if v.durableErr != nil { + return checkFail(v.durableErr.Error()) + } + for _, d := range v.durable.Volumes { + if d.VolumeID != v.evidence.VolumeID { + continue + } + if d.Impl == "walstore" { + return checkFinding{"not applicable", "no chunk store"} + } + if d.Chunk == nil || d.Chunk.Maintenance == nil { + return checkElsewhere("last cleaning result not exposed by this build; see maintenance log") + } + m := d.Chunk.Maintenance + if m.PassesOK == nil || m.InProgress == nil || m.CurrentStartNs == nil { + return checkFail("maintenance counter fields unavailable") + } + if m.LastPass != nil && m.LastPass.Error != nil && *m.LastPass.Error != "" { + return checkFail("last cleaning pass: " + *m.LastPass.Error) + } + if *m.InProgress { + return checkElsewhere(fmt.Sprintf("cleaning in progress since %d; passesOk=%d", *m.CurrentStartNs, *m.PassesOK)) + } + p := m.LastPass + if p == nil { + return checkFail("no cleaning pass completed since start") + } + if p.AtNs == nil || p.Planned == nil || p.Removed == nil || p.HeadGen == nil || p.Error == nil || p.PlannedChunks == nil || p.PlannedRoots == nil || p.PlannedSegments == nil || p.RemovedChunks == nil || p.RemovedRoots == nil || p.RemovedSegments == nil { + return checkElsewhere("last cleaning result fields unavailable") + } + if *p.HeadGen == 0 && (p.HeadGenError == nil || *p.HeadGenError == "") { + return checkElsewhere("cleaning HEAD generation unavailable; no observed cleaning pass") + } + if *p.AtNs <= 0 || *m.PassesOK == 0 { + return checkFail("no successful cleaning pass recorded") + } + finding := fmt.Sprintf("last pass at_ns=%d planned=%d removed=%d plannedChunks=%d plannedRoots=%d plannedSegments=%d removedChunks=%d removedRoots=%d removedSegments=%d head_gen=%d passesOk=%d", *p.AtNs, *p.Planned, *p.Removed, *p.PlannedChunks, *p.PlannedRoots, *p.PlannedSegments, *p.RemovedChunks, *p.RemovedRoots, *p.RemovedSegments, *p.HeadGen, *m.PassesOK) + if p.HeadGenError != nil && *p.HeadGenError != "" { + finding += fmt.Sprintf(" headGenError=%q", *p.HeadGenError) + } + return checkOK(finding) + } + return checkFail("selected volume absent from durable status") + }) +} +func (o *inspectionObservation) versions() checkFinding { + return o.each(true, func(v inspectedVolume) checkFinding { + if v.holderErr != nil { + return checkFail(v.holderErr.Error()) + } + if unknownInspectionVersion(o.cluster.ProductRevision) || unknownInspectionVersion(v.holder.Version) { + return checkFail("master or holder revision unavailable") + } + if o.cluster.ProductRevision != v.holder.Version { + return checkFail("blockmaster " + o.cluster.ProductRevision + ", blockvolume " + v.holder.Version) + } + return checkOK(v.holder.Version) + }) +} +func (o *inspectionObservation) clock() checkFinding { + return o.each(true, func(v inspectedVolume) checkFinding { + if o.cluster.CapturedAt.IsZero() { + return checkFail("master time unavailable") + } + rtt := o.ended.Sub(o.started) + mid := o.started.Add(rtt / 2) + diff := mid.Sub(o.cluster.CapturedAt) + if diff < 0 { + diff = -diff + } + if diff < 0 { + return checkFail("clock difference exceeds the duration range") + } + finding := fmt.Sprintf("local clock difference %s plus RTT uncertainty %s; configured max skew %s", diff, rtt/2, o.shell.maxClockSkew) + limit := o.shell.maxClockSkew / 2 + if diff >= limit || rtt/2 >= limit-diff { + return checkFail(finding) + } + return checkOK(finding) + }) +} diff --git a/seaweed-block/cmd/sw-block/shell_check_rows.go b/seaweed-block/cmd/sw-block/shell_check_rows.go new file mode 100644 index 0000000000..1bc57a5958 --- /dev/null +++ b/seaweed-block/cmd/sw-block/shell_check_rows.go @@ -0,0 +1,19 @@ +package main + +// The order and cure paragraphs are pinned to docs/troubleshooting.md. +var inspectionChecks = []inspectionCheck{ + {ID: "master.reachable", Title: "master.reachable", Reach: "anywhere", Cure: "blockmaster did not answer at `-master`: check that it runs and that `-master` is its `--listen` address; a non-loopback address needs the client certificate the role file names.", Run: (*inspectionObservation).reachable}, + {ID: "master.lifecycle", Title: "master.lifecycle", Reach: "anywhere", Cure: "blockmaster runs without `--lifecycle-store`: walstore-chunk volumes need it, so start blockmaster with it and restart.", Run: (*inspectionObservation).lifecycle}, + {ID: "master.version", Title: "master.version", Reach: "anywhere", Cure: "blockmaster did not report its version: it is older than v1.0.1, so upgrade it first.", Run: (*inspectionObservation).version}, + {ID: "filer.single", Title: "filer.single", Reach: "master+filer", Cure: "sw-block needs exactly one filer in its filer group: remove the other filers of the group or give the block store its own group, then restart the volume hosts.", Run: (*inspectionObservation).filer}, + {ID: "host.heartbeat", Title: "host.heartbeat", Reach: "anywhere", Cure: "No fresh heartbeat from `` for this volume: check that its blockvolume unit runs and reaches `--master`, and that its clock is synchronized (a backward step beyond the freshness window expires its slots).", Run: (*inspectionObservation).heartbeat}, + {ID: "volume.known", Title: "volume.known", Reach: "anywhere", Cure: "blockmaster does not know ``: add it to the cluster spec (or register its volume record) and restart blockmaster.", Run: (*inspectionObservation).known}, + {ID: "volume.assigned", Title: "volume.assigned", Reach: "anywhere", Cure: "No primary assigned: check that `--server-id` and `--replica-id` match the volume's slot and that `--expected-slots-per-volume` equals its slot count.", Run: (*inspectionObservation).assigned}, + {ID: "volume.lease", Title: "volume.lease", Reach: "anywhere", Cure: "The holder waits for its lease: read `MasterWait.Reason` on its status page; `unreachable`, `credentials` or `identity refused` each name what to fix.", Run: (*inspectionObservation).lease}, + {ID: "volume.frontend", Title: "volume.frontend", Reach: "host", Cure: "The frontend does not serve: the status page's `NotReadyReason` names the step (listener not up yet, the durable backend admits no I/O, lease, profile).", Run: (*inspectionObservation).frontend}, + {ID: "volume.chunkstore", Title: "volume.chunkstore", Reach: "host", Cure: "Snapshots require a walstore-chunk backend: configure --durable-impl=walstore-chunk with its chunk store before taking snapshots.", Run: (*inspectionObservation).chunkstore}, + {ID: "volume.cut", Title: "volume.cut", Reach: "host", Cure: "Cuts are behind or failing: read `lastFailure.code` and the holder's log for `capture` errors; a cut that needs more than one 5-minute request is retried by the schedule.", Run: (*inspectionObservation).cut}, + {ID: "volume.cleaning", Title: "volume.cleaning", Reach: "host", Cure: "The volume's last cleaning pass failed or has not run: read its result on the holder's `/status/durable` and the holder's log; cleaning runs every `--chunk-maintenance-interval` and after a snapshot delete made by the holder.", Run: (*inspectionObservation).cleaning}, + {ID: "versions.equal", Title: "versions.equal", Reach: "host", Cure: "blockmaster and this volume's blockvolume run different releases: finish the upgrade in the documented order.", Run: (*inspectionObservation).versions}, + {ID: "clock.skew", Title: "clock.skew", Reach: "host", Cure: "This host's clock is far from blockmaster's: synchronize both to one time source (chrony, slewing, not stepping); beyond `--workspace-max-clock-skew` (20 s by default) the lease bound does not hold.", Run: (*inspectionObservation).clock}, +} diff --git a/seaweed-block/cmd/sw-block/shell_test.go b/seaweed-block/cmd/sw-block/shell_test.go new file mode 100644 index 0000000000..53cedeb2d1 --- /dev/null +++ b/seaweed-block/cmd/sw-block/shell_test.go @@ -0,0 +1,406 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "net" + "net/http" + "net/http/httptest" + "os" + "regexp" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" +) + +func requireInspectionOutput(t *testing.T, raw []byte) map[string]inspectionResult { + t.Helper() + want := []string{"master.reachable", "master.lifecycle", "master.version", "filer.single", "host.heartbeat", "volume.known", "volume.assigned", "volume.lease", "volume.frontend", "volume.chunkstore", "volume.cut", "volume.cleaning", "versions.equal", "clock.skew"} + var rows []inspectionResult + if err := json.Unmarshal(raw, &rows); err != nil { + t.Fatalf("invalid output: %v: %s", err, raw) + } + if len(rows) != len(want) { + t.Fatalf("output inventory got%d want%d: %s", len(rows), len(want), raw) + } + got := map[string]inspectionResult{} + for i, r := range rows { + if r.ID != want[i] { + t.Fatalf("output ID/order[%d]=%q want%q", i, r.ID, want[i]) + } + if _, exists := got[r.ID]; exists { + t.Fatalf("duplicate ID %s", r.ID) + } + got[r.ID] = r + } + return got +} + +func TestShellClusterStatusReadsTheMasterWithoutKubernetes(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-c", "cluster.status -o json"}, &out, &errout) + if code != 0 { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, &errout, &out) + } + var body map[string]any + if err := json.Unmarshal(out.Bytes(), &body); err != nil { + t.Fatal(err) + } + if body["schema_version"] == nil || body["volumes"] == nil { + t.Fatalf("not cluster evidence: %s", &out) + } +} + +func startInspectionMaster(t *testing.T) (string, func()) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + control.RegisterEvidenceServiceServer(srv, cmdFakeEvidenceServer{}) + control.RegisterClusterEvidenceServiceServer(srv, inspectionControlServer{}) + go func() { _ = srv.Serve(ln) }() + return ln.Addr().String(), func() { + srv.Stop() + _ = ln.Close() + } +} + +type inspectionControlServer struct { + cmdFakeClusterEvidenceServer + control.UnimplementedWorkspaceServiceServer + mode string +} + +func (s inspectionControlServer) GetClusterStatus(ctx context.Context, q *control.GetClusterStatusRequest) (*control.ClusterStatusResponse, error) { + r, err := s.cmdFakeClusterEvidenceServer.GetClusterStatus(ctx, q) + r.Volumes[0].ReplicationFactor = 1 + r.Volumes[0].PrimaryNode = "host-b" + r.Volumes[0].Replicas = []*control.ReplicaEvidence{{ReplicaId: "r2", ServerId: "host-b", Observed: true}} + for _, event := range r.Events { + event.NodeName = "host-b" + } + return r, err +} +func (s inspectionControlServer) QueryWorkspace(_ context.Context, q *control.WorkspaceVolume) (*control.WorkspaceStatus, error) { + if s.mode == "disabled" { + return nil, status.Error(codes.FailedPrecondition, "workspace RPC disabled") + } + if q.GetVolumeId() == "__cluster_check__" { + return nil, status.Error(codes.NotFound, "not found") + } + l := &control.WorkspaceLeaseFact{ReplicaId: "r2", Epoch: 2, ValidForNs: int64(time.Second)} + switch s.mode { + case "lease-expired": + l.ValidForNs = 0 + case "lease-revoking": + l.Revoking = true + case "lease-wrong-holder": + l.ReplicaId = "r3" + } + return &control.WorkspaceStatus{Lease: l}, nil +} +func TestShellCheckUsesTypedLeaseReadinessCutAndVersionAnswers(t *testing.T) { + for _, tc := range []struct{ mode, id string }{ + {"healthy", ""}, {"disabled", "master.lifecycle"}, {"lease-expired", "volume.lease"}, {"lease-revoking", "volume.lease"}, {"lease-wrong-holder", "volume.lease"}, + {"frontend-false", "volume.frontend"}, {"cut-pending", "volume.cut"}, {"snapshot-overdue", "volume.cut"}, {"missing-cut-fields", "volume.cut"}, {"version-missing", "versions.equal"}, {"version-mismatch", "versions.equal"}, + {"cleaning-error", "volume.cleaning"}, {"cleaning-not-run", "volume.cleaning"}, {"cleaning-running", "volume.cleaning"}, {"cleaning-missing", "volume.cleaning"}, + {"missing-cleaning-head-gen", "volume.cleaning"}, {"null-cleaning-head-gen", "volume.cleaning"}, {"missing-cleaning-breakdown", "volume.cleaning"}, {"retention-only", "volume.cleaning"}, {"missing-cleaning-error", "volume.cleaning"}, {"null-cleaning-error", "volume.cleaning"}, {"completed-empty", ""}, {"completed-head-gen-note", ""}, {"failed-head-gen-note", "volume.cleaning"}, {"no-chunk-store", "volume.cut"}, + } { + t.Run(tc.mode, func(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + s := inspectionControlServer{mode: tc.mode} + srv := grpc.NewServer() + control.RegisterClusterEvidenceServiceServer(srv, s) + control.RegisterWorkspaceServiceServer(srv, s) + go func() { _ = srv.Serve(ln) }() + defer srv.Stop() + defer ln.Close() + h := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/status" { + body := map[string]any{"VolumeID": "v1", "ReplicaID": "r2", "Epoch": 2, "FrontendPrimaryReady": tc.mode != "frontend-false", "Version": "test-rev"} + if tc.mode == "version-missing" { + delete(body, "Version") + } + if tc.mode == "version-mismatch" { + body["Version"] = "other-rev" + } + _ = json.NewEncoder(w).Encode(body) + return + } + stats := map[string]any{"LastCutNs": time.Now().UnixNano(), "CutsFailed": 0, "PendingUnresolved": tc.mode == "cut-pending"} + if tc.mode == "missing-cut-fields" { + delete(stats, "PendingUnresolved") + } + chunk := map[string]any{"Attached": true, "Stats": stats, "ScheduledSnapshot": map[string]any{"snapshot_overdue": tc.mode == "snapshot-overdue", "lastFailure": map[string]any{"code": "remote_unavailable"}}} + lastPass := map[string]any{"atNs": time.Now().UnixNano(), "planned": 11, "removed": 6, "plannedChunks": 3, "plannedRoots": 5, "plannedSegments": 3, "removedChunks": 2, "removedRoots": 1, "removedSegments": 3, "error": "", "headGen": 7, "headGenError": ""} + if tc.mode == "retention-only" || tc.mode == "completed-empty" { + lastPass["planned"] = 0 + lastPass["removed"] = 0 + for _, key := range []string{"plannedChunks", "plannedRoots", "plannedSegments", "removedChunks", "removedRoots", "removedSegments"} { + lastPass[key] = 0 + } + } + if tc.mode == "missing-cleaning-head-gen" { + delete(lastPass, "headGen") + } + if tc.mode == "null-cleaning-head-gen" { + lastPass["headGen"] = nil + } + if tc.mode == "missing-cleaning-breakdown" { + delete(lastPass, "removedRoots") + } + if tc.mode == "completed-head-gen-note" || tc.mode == "failed-head-gen-note" { + lastPass["headGen"] = 0 + lastPass["headGenError"] = "HEAD read unavailable after completed cleaning" + } + if tc.mode == "failed-head-gen-note" { + lastPass["error"] = "cleaning failed" + } + if tc.mode == "retention-only" { + lastPass["headGen"] = 0 + } + if tc.mode == "missing-cleaning-error" { + delete(lastPass, "error") + } + if tc.mode == "null-cleaning-error" { + lastPass["error"] = nil + } + if tc.mode == "cleaning-error" { + lastPass["error"] = "filer unavailable" + } + maintenance := map[string]any{"passesOk": 1, "lastPass": lastPass, "inProgress": tc.mode == "cleaning-running", "currentStartNs": time.Now().UnixNano()} + if tc.mode == "cleaning-not-run" { + delete(maintenance, "lastPass") + maintenance["passesOk"] = 0 + } + if tc.mode != "cleaning-missing" { + chunk["Maintenance"] = maintenance + } + var chunkValue any = chunk + impl := "walstore-chunk" + if tc.mode == "no-chunk-store" { + impl = "walstore" + chunkValue = nil + } + _ = json.NewEncoder(w).Encode(map[string]any{"Volumes": []any{map[string]any{"VolumeID": "v1", "Impl": impl, "Chunk": chunkValue}}}) + })) + defer h.Close() + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", ln.Addr().String(), "-server-id", "host-b", "-status-addr", h.URL, "-c", "cluster.check -o json"}, &out, &errout) + rows := requireInspectionOutput(t, out.Bytes()) + for _, r := range rows { + if r.Status == "FAIL" && (r.See != "docs/troubleshooting.md#"+strings.ReplaceAll(r.ID, ".", "") || r.Cure == "") { + t.Fatalf("failure lacks a working page link and cure: %+v", r) + } + } + if tc.id != "" { + want := "FAIL" + if tc.mode == "cleaning-running" || tc.mode == "cleaning-missing" || tc.mode == "retention-only" || tc.mode == "missing-cleaning-error" || tc.mode == "null-cleaning-error" || tc.mode == "missing-cleaning-head-gen" || tc.mode == "null-cleaning-head-gen" || tc.mode == "missing-cleaning-breakdown" || tc.mode == "no-chunk-store" { + want = "not checked here" + } + if tc.mode == "no-chunk-store" { + want = "not applicable" + } + r := rows[tc.id] + if r.Status != want { + t.Fatalf("typed outcome missing %+v want %s", r, want) + } + wantCode := 1 + if want == "not checked here" || want == "not applicable" { + wantCode = 3 + } + if code != wantCode { + t.Fatalf("exit=%d want%d out=%s", code, wantCode, &out) + } + if tc.mode == "no-chunk-store" { + capability := rows["volume.chunkstore"] + if capability.Status != "ok" || !strings.Contains(capability.Finding, "local engine only: no snapshots") { + t.Fatalf("local-engine capability wrong: %+v", capability) + } + for _, id := range []string{"volume.cut", "volume.cleaning"} { + r := rows[id] + if r.Status != "not applicable" || !strings.Contains(r.Finding, "no chunk store") { + t.Fatalf("local-engine operation not inapplicable: %+v", r) + } + } + } + return + } + if code != 3 { + t.Fatalf("expected incomplete only for missing filer, exit=%d out=%s", code, &out) + } + if tc.mode == "completed-head-gen-note" { + if finding := rows["volume.cleaning"].Finding; !strings.Contains(finding, "HEAD read unavailable after completed cleaning") { + t.Fatalf("completed cleaning lost generation-read note: %s", finding) + } + } + if tc.mode == "healthy" { + finding := rows["volume.cleaning"].Finding + for _, part := range []string{"planned=11", "removed=6", "plannedChunks=3", "plannedRoots=5", "plannedSegments=3", "removedChunks=2", "removedRoots=1", "removedSegments=3"} { + if !strings.Contains(finding, part) { + t.Fatalf("cleaning totals/breakdown omitted %s: %s", part, finding) + } + } + } + for _, r := range rows { + if r.ID != "filer.single" && r.Status != "ok" { + t.Fatalf("healthy typed source failed %+v", r) + } + } + }) + } +} + +type futureInspectionMaster struct{ inspectionControlServer } + +func (futureInspectionMaster) GetClusterStatus(ctx context.Context, q *control.GetClusterStatusRequest) (*control.ClusterStatusResponse, error) { + r, err := (inspectionControlServer{}).GetClusterStatus(ctx, q) + r.CapturedAt = timestamppb.New(time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)) + return r, err +} +func TestShellClockCannotCallAnOverflowingDifferenceOK(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + control.RegisterClusterEvidenceServiceServer(srv, futureInspectionMaster{}) + go func() { _ = srv.Serve(ln) }() + defer srv.Stop() + defer ln.Close() + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", ln.Addr().String(), "-server-id", "host-b", "-c", "cluster.check -o json"}, &out, &errout) + rows := requireInspectionOutput(t, out.Bytes()) + if r := rows["clock.skew"]; r.Status != "FAIL" || code != 1 { + t.Fatalf("impossible clock accepted: %+v exit%d", r, code) + } +} + +func TestShellCheckNeverCallsOffHostChecksOK(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + var out, errout bytes.Buffer + var requests atomic.Int32 + holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + http.Error(w, "must not read off-host", 500) + })) + defer holder.Close() + code := run([]string{"shell", "-master", addr, "-server-id", "laptop", "-status-addr", holder.URL, "-c", "cluster.check -o json"}, &out, &errout) + if code == 2 || code == 0 { + t.Fatalf("command absent: %s", &errout) + } + rows := requireInspectionOutput(t, out.Bytes()) + for _, r := range rows { + switch r.ID { + case "volume.frontend", "volume.chunkstore", "volume.cut", "volume.cleaning", "versions.equal", "clock.skew": + if r.Status != "not checked here" || !strings.Contains(r.Finding, "host-b") { + t.Fatalf("off-host claim: %+v", r) + } + } + } + if requests.Load() != 0 { + t.Fatal("read an off-host status page") + } +} + +func TestShellCheckCuresAndOrderMatchTheTroubleshootingPage(t *testing.T) { + raw, err := os.ReadFile("../../docs/troubleshooting.md") + if err != nil { + t.Fatal(err) + } + sections := regexp.MustCompile(`(?m)^## `).Split(strings.ReplaceAll(string(raw), "\r\n", "\n"), -1)[1:] + var checks []string + idHeading := regexp.MustCompile(`^[a-z]+\.[a-z]+$`) + for _, s := range sections { + name, _, _ := strings.Cut(s, "\n") + if idHeading.MatchString(strings.TrimSpace(name)) { + checks = append(checks, s) + } + } + if len(checks) != len(inspectionChecks) { + t.Fatal("page and command check counts differ") + } + for i, c := range inspectionChecks { + name, rest, _ := strings.Cut(checks[i], "\n") + paragraph, _, _ := strings.Cut(strings.TrimSpace(rest), "\n\n") + if strings.TrimSpace(name) != c.ID || strings.Join(strings.Fields(paragraph), " ") != c.Cure { + t.Fatalf("page/table mismatch at %s", c.ID) + } + } +} + +func TestShellReadsQuotedCommandsFromStdinAndKeepsFailures(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + var out, errout bytes.Buffer + code := runShell([]string{"-master", addr}, strings.NewReader("volume.delete 'v1'\nvolume.status 'v1' -o json\nquit\n"), &out, &errout) + if code != 2 || !strings.Contains(out.String(), `"volume_id":"v1"`) || !strings.Contains(errout.String(), "unknown inspection command") { + t.Fatalf("exit=%d out=%s err=%s", code, &out, &errout) + } + for _, bad := range []string{`volume.status 'v1`, `volume.status v1\`} { + if _, err := inspectionWords(bad); err == nil { + t.Fatalf("accepted %q", bad) + } + } +} + +func TestShellCheckRefusesWrongHolderAndDoesNotFollowStatusRedirects(t *testing.T) { + addr, closeMaster := startInspectionMaster(t) + defer closeMaster() + for _, mode := range []string{"missing", "wrong-epoch", "missing-readiness", "redirect"} { + t.Run(mode, func(t *testing.T) { + var redirected atomic.Int32 + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { redirected.Add(1) })) + defer target.Close() + h := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if mode == "redirect" { + http.Redirect(w, r, target.URL, 302) + return + } + if r.URL.Path == "/status" { + body := map[string]any{"VolumeID": "v1", "ReplicaID": "r2", "Epoch": 2, "FrontendPrimaryReady": true, "Version": "test-rev"} + if mode == "wrong-epoch" { + body["Epoch"] = 3 + } + if mode == "missing-readiness" { + delete(body, "FrontendPrimaryReady") + } + _ = json.NewEncoder(w).Encode(body) + return + } + fmtBody := map[string]any{"Volumes": []any{map[string]any{"VolumeID": "v1", "Chunk": map[string]any{"Stats": map[string]any{"LastCutNs": 1}}}}} + _ = json.NewEncoder(w).Encode(fmtBody) + })) + defer h.Close() + statusAddr := h.URL + if mode == "missing" { + statusAddr = "" + } + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-server-id", "host-b", "-status-addr", statusAddr, "-c", "cluster.check -o json"}, &out, &errout) + rows := requireInspectionOutput(t, out.Bytes()) + if r := rows["volume.frontend"]; r.Status != "FAIL" || code != 1 { + t.Fatalf("wrong holder accepted %+v exit%d", r, code) + } + if redirected.Load() != 0 { + t.Fatal("followed a status redirect") + } + }) + } +} diff --git a/seaweed-block/cmd/sw-block/snapshot_delete_legacy_refusal_test.go b/seaweed-block/cmd/sw-block/snapshot_delete_legacy_refusal_test.go new file mode 100644 index 0000000000..b62968ef89 --- /dev/null +++ b/seaweed-block/cmd/sw-block/snapshot_delete_legacy_refusal_test.go @@ -0,0 +1,78 @@ +package main + +import ( + "context" + "fmt" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// The v1.0 delete by name succeeded but its reply was lost, and the name was +// recreated in a v1.1 HEAD. Running the command again is a new intent: it +// resolves the name again. Pinned to an incarnation the name no longer +// holds (--gen) it is refused typed with the HEAD unchanged; unpinned it +// deletes the replacement, which is what was asked, and names the +// incarnation it removed (name@gen). An old client's name-only call on that +// HEAD is refused (TestSnapshotDeleteOldClientNameOnlyRefusesAV1Head), and +// retries inside one invocation keep their incarnation +// (TestSnapshotDeletePublicOperationKeepsTargetAcrossRecreation). +func TestSnapshotDeleteAfterALostLegacyReplyIsANewIntent(t *testing.T) { + ctx := context.Background() + memory := newMemChunkStore() + useMemChunkStore(t, memory) + volume := cliVolume(t, memory, "v1", "daily") + cat, err := chunkstore.NewBCatalog(memory, memory, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + st, err := cat.Store(volume) + if err != nil { + t.Fatal(err) + } + old, _, err := st.ReadHead(ctx) + if err != nil || old.Version != 0 { + t.Fatalf("legacy fixture: %+v %v", old, err) + } + args := cliArgs("snapshot-delete", volArgs("volume", volume), []string{"--name", "daily"}) + if code, out, _ := runChunk(args...); code != 0 { + t.Fatalf("legacy delete failed: %d %s", code, out) + } + // Discard that reply and recreate the name in a v1.1 HEAD. + h, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + replacement := old.Snapshots["daily"] + replacement.Gen = h.Gen + 1 + h.Version = layout.HeadVersion1 + if h.Snapshots == nil { + h.Snapshots = map[string]layout.Snapshot{} + } + h.Snapshots["daily"] = replacement + if err := st.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil { + t.Fatal(err) + } + before, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + pinned := append(append([]string(nil), args...), "--gen", "1") + code, out, _ := runChunk(pinned...) + if failure := chunkErrorOut(t, out); code == 0 || failure.Code != "snapshot_generation_mismatch" || failure.Retryable { + t.Fatalf("a delete pinned to another incarnation: exit=%d body=%s; want snapshot_generation_mismatch", code, out) + } + if after, _, err := st.ReadHead(ctx); err != nil || after.Gen != before.Gen || after.Snapshots["daily"].Gen != replacement.Gen { + t.Fatalf("the refused pinned delete changed the HEAD: before %+v after %+v %v", before, after, err) + } + code, out, logs := runChunk(args...) + want := fmt.Sprintf("daily@%d", replacement.Gen) + if code != 0 || !strings.Contains(logs, want) || !strings.Contains(out, fmt.Sprintf(`"gen":%d`, replacement.Gen)) { + t.Fatalf("a new delete of the replacement: exit=%d out=%s logs=%s; want it deleted, naming %s", code, out, logs, want) + } + if after, _, err := st.ReadHead(ctx); err != nil || len(after.Snapshots) != 0 { + t.Fatalf("after the new delete: %+v %v; want no snapshot", after, err) + } +} diff --git a/seaweed-block/cmd/sw-block/snapshot_delete_route_test.go b/seaweed-block/cmd/sw-block/snapshot_delete_route_test.go new file mode 100644 index 0000000000..5e4e9050bf --- /dev/null +++ b/seaweed-block/cmd/sw-block/snapshot_delete_route_test.go @@ -0,0 +1,247 @@ +package main + +import ( + "context" + "errors" + "regexp" + "strings" + "sync/atomic" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + filerpb "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// opCountingStore counts every write attempt (a failed or torn one too) +// under the snapshot-operation tree: its directory, INDEX and receipts. +type opCountingStore struct { + *memChunkStore + writes atomic.Int64 +} + +func (s *opCountingStore) count(dir, name string) { + if strings.Contains(dir+"/", "/operations/") || name == "operations" { + s.writes.Add(1) + } +} + +func (s *opCountingStore) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error { + s.count(dir, e.GetName()) + return s.memChunkStore.CreateEntry(ctx, dir, e, oExcl) +} + +func (s *opCountingStore) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error { + s.count(dir, e.GetName()) + return s.memChunkStore.UpdateEntry(ctx, dir, e, expected) +} + +func (s *opCountingStore) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error { + s.count(dir, name) + return s.memChunkStore.DeleteEntry(ctx, dir, name, expected) +} + +// useCountingStore routes the CLI's filer through a write counter over mem +// and sets the cluster format level the CLI reads. +func useCountingStore(t *testing.T, mem *memChunkStore, level uint32) *opCountingStore { + t.Helper() + useMemChunkStore(t, mem) + counting := &opCountingStore{memChunkStore: mem} + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return counting, func() error { return nil }, nil + } + readClusterFormatLevel = func(context.Context, string) (uint32, error) { return level, nil } + return counting +} + +// toVersion1 makes v's HEAD a version-1 HEAD whose snapshots are stamped, as +// a v1.1 holder's first write leaves it. +func toVersion1(t *testing.T, st *chunkstore.LayoutStore) layout.Head { + t.Helper() + ctx := context.Background() + h, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + for name, s := range h.Snapshots { + s.Gen = h.Gen + 1 + h.Snapshots[name] = s + } + h.Version = layout.HeadVersion1 + if err := st.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil { + t.Fatal(err) + } + h, _, err = st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + return h +} + +// At cluster format level 0 a delete by name of a version-0 HEAD's snapshot +// is v1.0's name-only delete: it succeeds, the HEAD stays version 0, and not +// one write is attempted under the snapshot-operation tree. +func TestSnapshotDeleteByNameAtLevel0OnAV0HeadIsTheV10Delete(t *testing.T) { + ctx := context.Background() + mem := newMemChunkStore() + v := cliVolume(t, mem, "v1", "daily") + counting := useCountingStore(t, mem, 0) + code, out, logs := runChunk(cliArgs("snapshot-delete", volArgs("volume", v), []string{"--name", "daily"})...) + if code != 0 || !strings.Contains(out, `"state":"absent"`) { + t.Fatalf("v1.0 delete by name: code=%d out=%s logs=%s", code, out, logs) + } + cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI) + st, _ := cat.Store(v) + h, _, err := st.ReadHead(ctx) + if err != nil || h.Version != 0 || len(h.Snapshots) != 0 { + t.Fatalf("after the v1.0 delete: %+v %v; want a version-0 HEAD without daily", h, err) + } + if n := counting.writes.Load(); n != 0 { + t.Fatalf("the v1.0 delete attempted %d writes under the operation tree, want 0", n) + } +} + +// The route follows the HEAD's version at any format level. On a version-1 +// HEAD a delete by name is an operation delete under an id the CLI makes +// once for this invocation and prints, whose terminal receipt names the +// incarnation it captured; the HEAD stays version 1. On a version-0 HEAD at +// level 1 (a volume that has not adopted v1.1 yet) it is v1.0's name-only +// delete, with no write under the operation tree, as at level 0. +func TestSnapshotDeleteByNameRoutesOnTheHeadVersion(t *testing.T) { + ctx := context.Background() + for _, level := range []uint32{0, 1} { + t.Run(map[uint32]string{0: "v1 head at level 0", 1: "v1 head at level 1"}[level], func(t *testing.T) { + mem := newMemChunkStore() + v := cliVolume(t, mem, "v1", "daily") + cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI) + st, _ := cat.Store(v) + captured := toVersion1(t, st).Snapshots["daily"].Gen + useCountingStore(t, mem, level) + code, out, logs := runChunk(cliArgs("snapshot-delete", volArgs("volume", v), []string{"--name", "daily"})...) + m := regexp.MustCompile(`request id (cli-[0-9a-f]+)`).FindStringSubmatch(logs) + if code != 0 || m == nil { + t.Fatalf("operation delete by name: code=%d out=%s logs=%s; want success under a printed cli- id", code, out, logs) + } + op, found, err := st.ReadSnapshotOperation(ctx, m[1], "delete") + if err != nil || !found || op.State != "succeeded" || op.Name != "daily" || op.TargetGeneration == nil || *op.TargetGeneration != captured { + t.Fatalf("the receipt of the printed id %s: %+v found=%v %v; want succeeded for daily@%d", m[1], op, found, err, captured) + } + h, _, err := st.ReadHead(ctx) + if err != nil || h.Version != layout.HeadVersion1 || len(h.Snapshots) != 0 { + t.Fatalf("after the operation delete: %+v %v; want a version-1 HEAD without daily", h, err) + } + }) + } + t.Run("v0 head at level 1", func(t *testing.T) { + mem := newMemChunkStore() + v := cliVolume(t, mem, "v1", "daily") + counting := useCountingStore(t, mem, 1) + code, out, logs := runChunk(cliArgs("snapshot-delete", volArgs("volume", v), []string{"--name", "daily"})...) + if code != 0 || !strings.Contains(out, `"state":"absent"`) { + t.Fatalf("level 1, version-0 HEAD: code=%d out=%s logs=%s; want v1.0's delete by name", code, out, logs) + } + cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI) + st, _ := cat.Store(v) + h, _, err := st.ReadHead(ctx) + if err != nil || h.Version != 0 || len(h.Snapshots) != 0 { + t.Fatalf("after the delete: %+v %v; want a version-0 HEAD without daily", h, err) + } + if n := counting.writes.Load(); n != 0 { + t.Fatalf("the v1.0 delete at level 1 attempted %d writes under the operation tree, want 0", n) + } + }) +} + +// On a version-0 HEAD only the default delete by name falls back to v1.0's +// delete. With --request-id or --gen (exactly-once, or one incarnation) it +// is refused typed, at level 0 and at level 1, with the HEAD unchanged and +// no write under the operation tree. +func TestSnapshotDeleteExplicitIdentityOnAV0HeadIsRefused(t *testing.T) { + ctx := context.Background() + for _, tc := range []struct { + name string + args []string + level uint32 + }{ + {"request-id at level 0", []string{"--request-id", "exact-once"}, 0}, + {"request-id at level 1", []string{"--request-id", "exact-once"}, 1}, + {"gen at level 0", []string{"--gen", "3"}, 0}, + {"gen at level 1", []string{"--gen", "3"}, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + mem := newMemChunkStore() + v := cliVolume(t, mem, "v1", "daily") + cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI) + st, _ := cat.Store(v) + before, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + counting := useCountingStore(t, mem, tc.level) + code, out, _ := runChunk(cliArgs("snapshot-delete", volArgs("volume", v), append([]string{"--name", "daily"}, tc.args...))...) + failure := chunkErrorOut(t, out) + if code == 0 || failure.Code != "snapshot_generation_unavailable" || !strings.Contains(failure.Message, "until this volume adopts v1.1") { + t.Fatalf("%s on a version-0 HEAD: code=%d out=%s; want refused, typed", tc.name, code, out) + } + after, _, err := st.ReadHead(ctx) + if err != nil || after.Gen != before.Gen || after.Version != 0 || len(after.Snapshots) != 1 { + t.Fatalf("the refused delete changed the HEAD: before %+v after %+v %v", before, after, err) + } + if n := counting.writes.Load(); n != 0 { + t.Fatalf("the refused delete attempted %d writes under the operation tree, want 0", n) + } + }) + } +} + +// An explicit --gen 0 names no incarnation: on a version-0 and on a +// version-1 HEAD it is refused before any read or write, the HEAD unchanged +// and no write under the operation tree (it is not the unpinned delete). +func TestSnapshotDeleteExplicitGenZeroIsRefusedBeforeAdmission(t *testing.T) { + ctx := context.Background() + for _, v1 := range []bool{false, true} { + t.Run(map[bool]string{false: "v0 head", true: "v1 head"}[v1], func(t *testing.T) { + mem := newMemChunkStore() + v := cliVolume(t, mem, "v1", "daily") + cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI) + st, _ := cat.Store(v) + if v1 { + toVersion1(t, st) + } + before, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + counting := useCountingStore(t, mem, 1) + code, out, logs := runChunk(cliArgs("snapshot-delete", volArgs("volume", v), []string{"--name", "daily", "--gen", "0"})...) + if code == 0 || !strings.Contains(out+logs, "--gen must name a publishing generation") { + t.Fatalf("--gen 0: code=%d out=%s logs=%s; want refused before admission", code, out, logs) + } + after, _, err := st.ReadHead(ctx) + if err != nil || after.Gen != before.Gen || len(after.Snapshots) != 1 { + t.Fatalf("--gen 0 changed the HEAD: before %+v after %+v %v", before, after, err) + } + if n := counting.writes.Load(); n != 0 { + t.Fatalf("--gen 0 attempted %d writes under the operation tree, want 0", n) + } + }) + } +} + +// An old client's name-only delete (the v1.0 call) of a version-1 HEAD's +// snapshot refuses typed and writes nothing. +func TestSnapshotDeleteOldClientNameOnlyRefusesAV1Head(t *testing.T) { + ctx := context.Background() + mem := newMemChunkStore() + v := cliVolume(t, mem, "v1", "daily") + cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI) + st, _ := cat.Store(v) + before := toVersion1(t, st) + if _, err := cat.DeleteSnapshot(ctx, v, "daily"); !errors.Is(err, layout.ErrSnapshotDeleteNeedsOperation) { + t.Fatalf("an old client's name-only delete of a version-1 HEAD: %v; want snapshot_delete_requires_operation", err) + } + after, _, err := st.ReadHead(ctx) + if err != nil || after.Gen != before.Gen { + t.Fatalf("the refused delete wrote the HEAD: before gen %d after %+v %v", before.Gen, after, err) + } +} diff --git a/seaweed-block/cmd/sw-block/snapshot_operation.go b/seaweed-block/cmd/sw-block/snapshot_operation.go new file mode 100644 index 0000000000..60fcfb232e --- /dev/null +++ b/seaweed-block/cmd/sw-block/snapshot_operation.go @@ -0,0 +1,123 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "os/signal" + "strings" + "time" +) + +type snapshotCLIAnswer struct { + ID string `json:"operation_id"` + State string `json:"state"` + Result json.RawMessage `json:"result,omitempty"` + Message string `json:"message,omitempty"` + Code string `json:"code,omitempty"` +} + +type snapshotCLIAdmission struct { + Answer snapshotCLIAnswer + Raw []byte + Location string + Accepted bool +} + +// The admission retry uses the existing request loop and the same body. Once +// admitted, observation only GETs the returned handle; interrupt ends the +// observer, never the server operation. Old synchronous servers still relay +// their final 200 answer through the existing loop. +func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]any, noWait bool, stdout, stderr io.Writer) int { + var a snapshotCLIAdmission + code := chunkPostLoop("snapshot", addr, "/chunk/snapshot", timeout, body, stdout, stderr, &a) + if code != 0 || !a.Accepted { + return code + } + if noWait { + if err := writeAll(stdout, a.Raw); err != nil { + return chunkExitFailed + } + return 0 + } + base := addr + if !strings.Contains(base, "://") { + base = "http://" + base + } + origin, err := url.Parse(base) + if err != nil { + return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeBadRequestCLI, err.Error(), false) + } + loc, err := url.Parse(a.Location) + if err != nil { + return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "invalid operation handle URI", false) + } + handle := origin.ResolveReference(loc) + if handle.Scheme != origin.Scheme || handle.Host != origin.Host || handle.User != nil { + return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation handle changed origin", false) + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + for { + callCtx, cancel := context.WithTimeout(ctx, min(timeout, 2*time.Second)) + req, err := http.NewRequestWithContext(callCtx, http.MethodGet, handle.String(), nil) + if err != nil { + cancel() + return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false) + } + resp, err := chunkHTTPClient.Do(req) + var current snapshotCLIAnswer + if err == nil { + err = json.NewDecoder(io.LimitReader(resp.Body, chunkResponseLimit+1)).Decode(¤t) + _ = resp.Body.Close() + if resp.StatusCode != 200 { + err = fmt.Errorf("operation status HTTP %d", resp.StatusCode) + } + } + cancel() + if ctx.Err() != nil { + fmt.Fprintf(stderr, "snapshot observation interrupted; resume with --request-id %s\n", a.Answer.ID) + return chunkExitFailed + } + if err != nil { + return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeUnavailableCLI, err.Error(), true) + } + if current.ID != a.Answer.ID { + return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation status changed identity", false) + } + switch current.State { + case "succeeded": + if len(current.Result) == 0 || !json.Valid(current.Result) { + return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "operation has no result", false) + } + if err := writeAll(stdout, current.Result); err != nil { + return chunkExitFailed + } + return 0 + case "refused": + message := current.Message + if message == "" { + message = "snapshot operation refused" + } + return chunkFail("snapshot", stdout, stderr, chunkExitFailed, current.Code, message, false) + case "stalled": + return chunkFail("snapshot", stdout, stderr, chunkExitFailed, "no_progress", "snapshot stalled; repeat with --request-id "+a.Answer.ID, true) + case "accepted", "running": + default: + return chunkFail("snapshot", stdout, stderr, chunkExitFailed, codeInternalCLI, "unknown operation state", false) + } + timer := time.NewTimer(100 * time.Millisecond) + select { + case <-ctx.Done(): + if !timer.Stop() { + <-timer.C + } + return chunkExitFailed + case <-timer.C: + } + } +} diff --git a/seaweed-block/cmd/sw-block/snapshot_operation_interrupt_unix_test.go b/seaweed-block/cmd/sw-block/snapshot_operation_interrupt_unix_test.go new file mode 100644 index 0000000000..e94f96427c --- /dev/null +++ b/seaweed-block/cmd/sw-block/snapshot_operation_interrupt_unix_test.go @@ -0,0 +1,142 @@ +//go:build !windows + +package main + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "sync" + "testing" + "time" +) + +// The child runs the actual command, not a second request-loop implementation. +func TestSnapshotOperationCLIObserverProcess(t *testing.T) { + if os.Getenv("SW_BLOCK_SNAPSHOT_OBSERVER_CHILD") != "1" { + return + } + args := []string{"ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", os.Getenv("SW_BLOCK_SNAPSHOT_OBSERVER_URL"), "--name", "s1", "--timeout", "5s"} + os.Exit(run(args, os.Stdout, os.Stderr)) +} + +func TestSnapshotOperationCLIInterruptThenResumeUsesPrintedID(t *testing.T) { + var mu sync.Mutex + var ids []string + var pollIDs []string + observing := make(chan struct{}, 1) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.Method { + case http.MethodPost: + var req struct { + ID string `json:"requestID"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Error(err) + w.WriteHeader(400) + return + } + mu.Lock() + ids = append(ids, req.ID) + mu.Unlock() + w.Header().Set("Location", "/operations/"+req.ID) + w.Header().Set("Retry-After", "0") + w.WriteHeader(http.StatusAccepted) + _ = json.NewEncoder(w).Encode(map[string]any{"operation_id": req.ID, "state": "running"}) + case http.MethodGet: + id := strings.TrimPrefix(r.URL.Path, "/operations/") + mu.Lock() + pollIDs = append(pollIDs, id) + resumed := len(ids) > 1 + mu.Unlock() + if !resumed { + select { + case observing <- struct{}{}: + default: + } + // An interrupted observer must drop this connection, not cancel or + // re-admit the server operation with a fresh identity. + <-r.Context().Done() + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"operation_id": id, "state": "succeeded", "result": json.RawMessage(published)}) + default: + t.Errorf("observer must not cancel: %s", r.Method) + http.NotFound(w, r) + } + })) + defer srv.Close() + dir := t.TempDir() + out, err := os.Create(filepath.Join(dir, "observer.stdout")) + if err != nil { + t.Fatal(err) + } + defer out.Close() + errs, err := os.Create(filepath.Join(dir, "observer.stderr")) + if err != nil { + t.Fatal(err) + } + defer errs.Close() + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestSnapshotOperationCLIObserverProcess$", "-test.timeout=7s") + cmd.Env = append(os.Environ(), "SW_BLOCK_SNAPSHOT_OBSERVER_CHILD=1", "SW_BLOCK_SNAPSHOT_OBSERVER_URL="+srv.URL) + cmd.Stdout, cmd.Stderr = out, errs + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { done <- cmd.Wait() }() + joined := false + defer func() { + if !joined { + _ = cmd.Process.Kill() + <-done + } + }() + select { + case <-observing: + case err := <-done: + joined = true + b, _ := os.ReadFile(errs.Name()) + t.Fatalf("CLI exited before observing the durable operation: err=%v stderr=%s", err, b) + case <-ctx.Done(): + t.Fatal("CLI did not start bounded observation") + } + if err := cmd.Process.Signal(os.Interrupt); err != nil { + t.Fatal(err) + } + select { + case <-done: + joined = true + case <-ctx.Done(): + t.Fatal("interrupt did not stop the observer") + } + b, err := os.ReadFile(errs.Name()) + if err != nil { + t.Fatal(err) + } + printed := regexp.MustCompile(`request id ([0-9a-f]{32}) `).FindAllStringSubmatch(string(b), -1) + if len(printed) != 1 { + t.Fatalf("one resumable printed ID required: %s", b) + } + id := printed[0][1] + code, stdout, stderr := runChunkWithin(t, 4*time.Second, "snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", id, "--timeout", "2s") + mu.Lock() + defer mu.Unlock() + if code != 0 || len(ids) != 2 || ids[0] != id || ids[1] != id || !strings.Contains(stdout, `"headGen":4`) { + t.Fatalf("resume must keep original ID %s: IDs=%v exit=%d stdout=%q stderr=%q", id, ids, code, stdout, stderr) + } + for _, got := range pollIDs { + if got != id { + t.Errorf("poll changed ID: got=%q want=%q", got, id) + } + } +} diff --git a/seaweed-block/cmd/sw-block/snapshot_operation_red_test.go b/seaweed-block/cmd/sw-block/snapshot_operation_red_test.go new file mode 100644 index 0000000000..66aaaadea4 --- /dev/null +++ b/seaweed-block/cmd/sw-block/snapshot_operation_red_test.go @@ -0,0 +1,98 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "sync" + "testing" + "time" +) + +// The server is an HTTP boundary fixture only. It does not execute snapshot +// transitions or remember an original snapshot on behalf of the product. +func TestSnapshotOperationCLIUsesPrintedIDForAsyncObservation(t *testing.T) { + shortLoop(t, 200*time.Millisecond, 10*time.Millisecond, 10*time.Millisecond) + for _, noWait := range []bool{false, true} { + t.Run(fmt.Sprintf("no_wait=%v", noWait), func(t *testing.T) { + var mu sync.Mutex + var ids []string + var polls int + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodPost && r.URL.Path == "/chunk/snapshot": + var body struct { + RequestID string `json:"requestID"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + w.WriteHeader(400) + return + } + ids = append(ids, body.RequestID) + if len(ids) == 1 { + // Lose the answer after the boundary has read the entire + // request. The retry must retain the printed identity. + conn, _, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Error(err) + return + } + _ = conn.Close() + return + } + // An operation handle is a URI; the CLI follows the returned Location, + // rather than manufacturing an endpoint or submitting another create. + w.Header().Set("Location", "/operations/"+body.RequestID) + w.Header().Set("Retry-After", "0") + w.WriteHeader(http.StatusAccepted) + _ = json.NewEncoder(w).Encode(map[string]any{"operation_id": body.RequestID, "state": "running"}) + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/operations/"): + polls++ + id := strings.TrimPrefix(r.URL.Path, "/operations/") + if len(ids) != 2 || id != ids[0] || ids[1] != ids[0] { + t.Errorf("poll identity %q, admitted IDs %v", id, ids) + } + _ = json.NewEncoder(w).Encode(map[string]any{"operation_id": id, "state": "succeeded", "result": json.RawMessage(published)}) + case r.Method == http.MethodGet && r.URL.Path == "/status/durable": + http.NotFound(w, r) + default: + t.Errorf("unexpected observation %s %s", r.Method, r.URL.String()) + http.NotFound(w, r) + } + })) + defer srv.Close() + args := []string{"snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--timeout", "2s"} + if noWait { + args = append(args, "--no-wait") + } + code, out, errs := runChunkWithin(t, 4*time.Second, args...) + mu.Lock() + defer mu.Unlock() + printed := regexp.MustCompile(`request id ([0-9a-f]{32}) `).FindAllStringSubmatch(errs, -1) + if code != 0 || len(printed) != 1 || len(ids) != 2 || ids[0] != printed[0][1] || ids[1] != ids[0] { + t.Fatalf("one printed/admitted ID required: exit=%d IDs=%v printed=%v stdout=%q stderr=%q", code, ids, printed, out, errs) + } + if noWait { + var handle struct { + ID string `json:"operation_id"` + State string `json:"state"` + } + if err := json.Unmarshal([]byte(out), &handle); err != nil || handle.ID != ids[0] || handle.State != "running" || polls != 0 { + t.Fatalf("no-wait must return the same handle without polling: handle=%+v polls=%d err=%v stdout=%q", handle, polls, err, out) + } + } else { + // Accepting a 202 answer as completed is not observation of success. + if polls != 1 || !strings.Contains(out, `"headGen":4`) { + t.Fatalf("default must poll the same operation through success: IDs=%v polls=%d stdout=%q", ids, polls, out) + } + } + }) + } +} diff --git a/seaweed-block/cmd/sw-block/start_any_test.go b/seaweed-block/cmd/sw-block/start_any_test.go new file mode 100644 index 0000000000..a6d3255409 --- /dev/null +++ b/seaweed-block/cmd/sw-block/start_any_test.go @@ -0,0 +1,7 @@ +package main + +import "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + +// anyStart is a local root that can start from any HEAD: these tests do +// not model the local store. +func anyStart(layout.Head) error { return nil } diff --git a/seaweed-block/cmd/sw-block/volume_backup.go b/seaweed-block/cmd/sw-block/volume_backup.go new file mode 100644 index 0000000000..862609e83e --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_backup.go @@ -0,0 +1,586 @@ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/ops" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// volume backup and volume restore: whole-job commands composed of existing +// calls (the holder's snapshot; the master's restore create, workspace +// binding and placement; volume start's steps; ops chunk volume-delete for +// the way back). The commands keep no state: every request id is derived +// from the command's own arguments, every step checks before it acts, so a +// command interrupted anywhere (the host losing power included) is finished +// by running it again unchanged, or undone by restore --abort. + +// derivedID is a stable request id: the same inputs, the same request. +func derivedID(prefix string, parts ...string) string { + sum := sha256.Sum256([]byte(strings.Join(parts, "\x00"))) + return prefix + "-" + hex.EncodeToString(sum[:16]) +} + +type backupOpts struct { + Volume, Name string + Timeout time.Duration +} + +func parseVolumeBackup(args []string, stderr io.Writer) (backupOpts, error) { + fs := flag.NewFlagSet("sw-block volume backup", flag.ContinueOnError) + fs.SetOutput(stderr) + var o backupOpts + fs.StringVar(&o.Name, "name", "", "snapshot name (required: the same --name resumes this backup)") + fs.DurationVar(&o.Timeout, "timeout", 5*time.Minute, "bound on the snapshot") + if err := fs.Parse(volumeArgsFirst(args)); err != nil { + return o, err + } + if fs.NArg() != 1 || !volumeNameRE.MatchString(fs.Arg(0)) { + fmt.Fprintln(stderr, volumeHelp()) + return o, errors.New("one volume") + } + o.Volume = fs.Arg(0) + if o.Name == "" { + // No generated default: a name chosen by the command is lost with + // its terminal, and the same command could not find that snapshot + // again. The operator's name is what a re-run resumes. + fmt.Fprintln(stderr, "sw-block volume backup: --name is required (the same command with the same --name resumes the backup)") + return o, errors.New("--name is required") + } + return o, nil +} + +// snapshotAnswer is the part of the holder's snapshot answer backup checks. +// Every fact backup prints must be present in the answer (zero is a valid +// value when present). +type snapshotAnswer struct { + VolumeID string `json:"volumeID"` + Name string `json:"name"` + HeadGen *uint64 `json:"headGen"` + CutLSN *uint64 `json:"cutLSN"` + CreatedNs *int64 `json:"createdNs"` + Labels map[string]string `json:"labels"` +} + +// backupLabel marks a snapshot taken by volume backup with its request: +// the holder keeps a snapshot's labels and answers an existing name with +// the snapshot it already has, so the label is how backup tells its own +// snapshot (a resumed run) from another one of the same name. +const backupLabel = "sw-block-backup" + +func backupTag(requestID string) string { return strings.TrimPrefix(requestID, "backup-") } + +// volumeBackup takes a named snapshot of a running walstore-chunk volume. +func volumeBackup(ctx context.Context, env verbEnv, o backupOpts, stdout, stderr io.Writer) int { + refuse := func(step, msg string) int { + fmt.Fprintf(stderr, "sw-block volume backup: %s: %s\n", step, msg) + return ops.VolumeStatusExitInvalid + } + e, err := readEnvFile(filepath.Join(env.EtcDir, o.Volume+".env")) + if err != nil { + return refuse("settings", fmt.Sprintf("%v (was %s started with sudo sw-block volume start?)", err, o.Volume)) + } + if e["SWB_DURABLE_IMPL"] != "walstore-chunk" { + return refuse("settings", o.Volume+" is walstore: it has no object store, so no snapshot (start it with --chunk-filer)") + } + again := fmt.Sprintf("sudo sw-block volume backup %s --name %s", o.Volume, shQuote(o.Name)) + id := derivedID("backup", o.Volume, o.Name) + if err := env.step(stdout, "snapshot", fmt.Sprintf("snapshot %s as %s (request %s)", o.Volume, shQuote(o.Name), id)); err != nil { + fmt.Fprintf(stderr, "sw-block volume backup: snapshot: %v; a cut that timed out keeps what it uploaded; to finish, run the same command (it resumes the same request and reuses completed uploads): %s\n", err, again) + return 1 + } + a, refusal, err := volumeSnapshot(ctx, env, e["SWB_STATUS_ADDR"], o.Volume, o.Name, id, o.Timeout) + if refusal != nil { + text := refusal.Code + ": " + refusal.Message + if refusal.Code == "snapshot_name_taken" { + return refuse("snapshot", fmt.Sprintf("%s; choose a new snapshot name: sudo sw-block volume backup %s --name ", text, o.Volume)) + } + return refuse("snapshot", fmt.Sprintf("%s; a cut that timed out keeps what it uploaded; after correcting the refusal, run the same command (it resumes the same request and reuses completed uploads): %s", text, again)) + } + if err != nil { + fmt.Fprintf(stderr, "sw-block volume backup: snapshot: %v; a cut that timed out keeps what it uploaded; to finish, run the same command (it resumes the same request and reuses completed uploads): %s\n", err, again) + return 1 + } + fmt.Fprintf(stdout, "sw-block volume backup: snapshot %s of %s: head generation %d, cut LSN %d, at %s\n", + shQuote(a.Name), o.Volume, *a.HeadGen, *a.CutLSN, time.Unix(0, *a.CreatedNs).UTC().Format(time.RFC3339)) + fmt.Fprintf(stdout, "Restore it into a new volume: sudo sw-block volume restore %s --snapshot %s --as [flags]\n", o.Volume, shQuote(a.Name)) + return 0 +} + +type snapshotRefusal struct{ Code, Message string } + +// volumeSnapshot is the holder's POST /chunk/snapshot with a fixed request +// id. Only a complete answer naming this volume and name is the snapshot; a +// refusal returns its code and message; anything else is an unknown outcome +// that the same request resolves (a snapshot is one conditional HEAD write: +// it exists or it does not, and a replay finds it). +func volumeSnapshot(ctx context.Context, env verbEnv, status, volume, name, requestID string, timeout time.Duration) (snapshotAnswer, *snapshotRefusal, error) { + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + body, _ := json.Marshal(map[string]any{"volumeID": volume, "name": name, "requestID": requestID, "consistency": "crash", "labels": map[string]string{backupLabel: backupTag(requestID)}}) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://"+status+"/chunk/snapshot", bytes.NewReader(body)) + if err != nil { + return snapshotAnswer{}, nil, err + } + req.Header.Set("Content-Type", "application/json") + client := *env.HTTP + client.Timeout = timeout + 5*time.Second + unknown := func(why string) (snapshotAnswer, *snapshotRefusal, error) { + return snapshotAnswer{}, nil, fmt.Errorf("the snapshot's outcome is unknown (%s)", why) + } + resp, err := client.Do(req) + if err != nil { + return unknown(err.Error()) + } + defer resp.Body.Close() + b, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) + if err != nil { + return unknown("answer unreadable: " + err.Error()) + } + if resp.StatusCode != http.StatusOK { + var eb struct{ Code, Message string } + if json.Unmarshal(b, &eb) != nil || eb.Code == "" || eb.Code == "outcome_unknown" { + return unknown(fmt.Sprintf("http %d %s %s", resp.StatusCode, eb.Code, strings.TrimSpace(eb.Message))) + } + return snapshotAnswer{}, &snapshotRefusal{Code: eb.Code, Message: eb.Message}, nil + } + var a snapshotAnswer + if err := json.Unmarshal(b, &a); err != nil || a.VolumeID != volume || a.Name != name { + return unknown("the answer is not this snapshot") + } + if a.HeadGen == nil || a.CutLSN == nil || a.CreatedNs == nil { + return unknown("the answer lacks the snapshot's head generation, cut LSN or time") + } + if got := a.Labels[backupLabel]; got != backupTag(requestID) { + return snapshotAnswer{}, &snapshotRefusal{Code: "snapshot_name_taken", Message: fmt.Sprintf("%s already has a snapshot %s that this command did not take (its %s label is %q); choose another --name", volume, shQuote(name), backupLabel, got)}, nil + } + return a, nil, nil +} + +type restoreOpts struct { + Source, Snapshot string + New volumeSpec // the new volume: its name and its own endpoints (from the flags) + Start startOpts + Timeout time.Duration + Abort bool +} + +func parseVolumeRestore(args []string, stderr io.Writer) (restoreOpts, error) { + fs := flag.NewFlagSet("sw-block volume restore", flag.ContinueOnError) + fs.SetOutput(stderr) + var o restoreOpts + v := &o.New + fs.StringVar(&o.Snapshot, "snapshot", "", "the source's snapshot to restore (required)") + fs.StringVar(&v.VolumeID, "as", "", "the new volume's name (required; never an existing one)") + fs.BoolVar(&o.Abort, "abort", false, "undo this restore: stop and delete the new volume, release the source snapshot, remove its settings") + fs.StringVar(&v.ReplicaID, "replica-id", "", "the new volume's replica id on this host (required)") + fs.StringVar(&v.DataAddr, "data-addr", "", "the new volume's replication data address (required)") + fs.StringVar(&v.CtrlAddr, "ctrl-addr", "", "the new volume's replication control address (required)") + fs.StringVar(&v.StatusAddr, "status-addr", "", "the new volume's status address, loopback (required)") + fs.StringVar(&v.NVMeListen, "nvme-listen", "", "the new volume's NVMe/TCP listen address (required)") + fs.StringVar(&v.NQN, "nqn", "", "the new volume's NVMe subsystem NQN (default nqn.2026-05.io.seaweedfs:)") + fs.StringVar(&v.DurableRoot, "durable-root", "", "the new volume's local data directory (default /var/lib/sw-block-volume/)") + fs.StringVar(&v.ISCSIListen, "iscsi-listen", "", "iSCSI listen address (optional)") + fs.StringVar(&v.IQN, "iqn", "", "iSCSI target IQN (with --iscsi-listen)") + fs.DurationVar(&o.Start.Wait, "wait", 2*time.Minute, "how long to wait until the new volume serves") + fs.DurationVar(&o.Timeout, "timeout", 6*time.Minute, "bound on the restore create and on the abort's delete") + if err := fs.Parse(volumeArgsFirst(args)); err != nil { + return o, err + } + bad := func(msg string) (restoreOpts, error) { + fmt.Fprintf(stderr, "sw-block volume restore: %s\n", msg) + return o, errors.New(msg) + } + if fs.NArg() != 1 || !volumeNameRE.MatchString(fs.Arg(0)) { + fmt.Fprintln(stderr, volumeHelp()) + return o, errors.New("one source volume") + } + o.Source = fs.Arg(0) + if !volumeNameRE.MatchString(v.VolumeID) || v.VolumeID == o.Source { + return bad(fmt.Sprintf("--as %q: a new volume name, not the source", v.VolumeID)) + } + if o.Snapshot == "" { + return bad("--snapshot is required") + } + if o.Abort { + return o, nil // the way back needs only the source, the snapshot and the new name + } + for _, r := range []struct{ name, val string }{{"--replica-id", v.ReplicaID}, {"--data-addr", v.DataAddr}, + {"--ctrl-addr", v.CtrlAddr}, {"--status-addr", v.StatusAddr}, {"--nvme-listen", v.NVMeListen}} { + if r.val == "" { + return bad(r.name + " is required") + } + } + if (v.ISCSIListen == "") != (v.IQN == "") { + return bad("--iscsi-listen and --iqn go together") + } + if v.DurableRoot == "" { + v.DurableRoot = "/var/lib/sw-block-volume/" + v.VolumeID + } + if v.NQN == "" { + v.NQN = "nqn.2026-05.io.seaweedfs:" + v.VolumeID + } + return o, nil +} + +// restoreCommands are the two ways on after a failure, as exact commands. +func restoreCommands(o restoreOpts, args []string) (again, abort string) { + abort = fmt.Sprintf("sudo sw-block volume restore %s --snapshot %s --as %s --abort", o.Source, shQuote(o.Snapshot), o.New.VolumeID) + q := make([]string, len(args)) + for i, a := range args { + q[i] = shQuote(a) + } + return "sudo sw-block volume restore " + strings.Join(q, " "), abort +} + +// volumeRestore restores a snapshot of a running volume into a new volume +// and starts it on this host: the master's restore create (a journaled +// operation: a replay of the same request completes it), the new volume's +// binding and placement, then volume start's steps. The source is never +// touched; the new name must be new. +func volumeRestore(ctx context.Context, env verbEnv, o restoreOpts, args []string, stdout, stderr io.Writer) int { + again, abort := restoreCommands(o, args) + ways := fmt.Sprintf("to finish, run the same command: %s; to undo it: %s", again, abort) + refuse := func(step, msg string) int { + fmt.Fprintf(stderr, "sw-block volume restore: %s: %s\n", step, msg) + return ops.VolumeStatusExitInvalid + } + unknown := func(step string, err error) int { + fmt.Fprintf(stderr, "sw-block volume restore: %s: %v; %s\n", step, err, ways) + return 1 + } + src, err := readEnvFile(filepath.Join(env.EtcDir, o.Source+".env")) + if err != nil { + return refuse("settings", fmt.Sprintf("%v (was %s started with sudo sw-block volume start?)", err, o.Source)) + } + if src["SWB_DURABLE_IMPL"] != "walstore-chunk" { + return refuse("settings", o.Source+" is walstore: it has no snapshots to restore") + } + master := src["SWB_MASTER_ADDR"] + v := o.New + v.Master, v.ServerID = master, src["SWB_SERVER_ID"] // the same host and master as the source + v.Chunk, v.BlockSize, v.ChunkFiler, v.ChunkPath = true, 4096, src["SWB_CHUNK_FILER"], src["SWB_CHUNK_PATH"] + + id := derivedID("restore", v.VolumeID, o.Source, o.Snapshot) // ops chunk restore's own default derivation + if err := env.step(stdout, "restore", fmt.Sprintf("restore %s's snapshot %s as %s at %s (request %s)", o.Source, shQuote(o.Snapshot), v.VolumeID, master, id)); err != nil { + return unknown("restore", err) + } + rctx, cancel := context.WithTimeout(ctx, o.Timeout) + resp, err := restoreCreateRPC(rctx, master, &control.CreateVolumeRequest{VolumeId: v.VolumeID, SourceVolume: o.Source, SourceSnapshot: o.Snapshot, CreateRequestId: id}) + cancel() + if err != nil { + if code := restoreRefusal(err); code != "" { + return refuse("restore", code+": "+err.Error()) + } + return unknown("restore", fmt.Errorf("the outcome is unknown (%v)", err)) + } + if resp.GetVolumeId() != v.VolumeID || !resp.GetStoreReady() { + return unknown("restore", errors.New("the master did not confirm the new volume store-ready")) + } + if _, err := layout.ParseVolumeID(resp.GetLayoutId()); err != nil || resp.GetSizeBytes() == 0 || resp.GetSizeBytes()%4096 != 0 { + return unknown("restore", errors.New("the master's answer has no valid layout id or size")) + } + v.Blocks = resp.GetSizeBytes() / 4096 + + if err := env.step(stdout, "place", fmt.Sprintf("bind and place %s on server %s (replica %s)", v.VolumeID, v.ServerID, v.ReplicaID)); err != nil { + return unknown("place", err) + } + binding := &control.WorkspaceBinding{VolumeId: v.VolumeID, ServerId: v.ServerID, DataAddr: v.DataAddr, CtrlAddr: v.CtrlAddr} + // Once the volume's authority line is published (the holder started), + // the master refuses any placement as already assigned, an identical one + // included. So check first: a line for this replica with this binding is + // this restore's placement, done; a line for anything else refuses. + placed, why, err := restorePlaced(ctx, master, binding, v.ReplicaID) + switch { + case err != nil: + return unknown("place", fmt.Errorf("read %s's placement at the master: %w", v.VolumeID, err)) + case why != "": + fmt.Fprintf(stderr, "sw-block volume restore: place: refused: %s; to undo it: %s\n", why, abort) + return ops.VolumeStatusExitInvalid + case placed: + fmt.Fprintln(stdout, " already placed (an earlier run of this command)") + default: + if step, err := workspaceBindPlace(ctx, master, binding, v.ReplicaID); err != nil { + if status.Code(err) == codes.FailedPrecondition { + // The line may have been published between the read and the + // placement: this exact placement counts as done; anything + // else keeps the refusal. + again, why2, qerr := restorePlaced(ctx, master, binding, v.ReplicaID) + switch { + case qerr != nil: + // The line may well be published: unknown, not "not placed". + return unknown("place", fmt.Errorf("the placement was refused (%v) and the re-read failed (%v): its outcome is unknown", err, qerr)) + case again: + fmt.Fprintln(stdout, " placed (published while placing)") + case why2 != "": + fmt.Fprintf(stderr, "sw-block volume restore: place: refused: %s; to undo it: %s\n", why2, abort) + return ops.VolumeStatusExitInvalid + } + if again { + break + } + } + switch status.Code(err) { + case codes.FailedPrecondition, codes.InvalidArgument, codes.AlreadyExists, codes.PermissionDenied: + fmt.Fprintf(stderr, "sw-block volume restore: %s: refused: %v; the new volume exists but is not placed; to undo it: %s\n", step, err, abort) + return ops.VolumeStatusExitInvalid + } + return unknown(step, err) + } + } + fmt.Fprintf(stdout, "sw-block volume restore: %s holds %s's snapshot %s; starting it\n", v.VolumeID, o.Source, shQuote(o.Snapshot)) + if code := volumeStart(ctx, env, v, o.Start, stdout, stderr); code != 0 { + fmt.Fprintf(stderr, "sw-block volume restore: %s\n", ways) + return code + } + return 0 +} + +// volumeRestoreAbort is the one way back: it stops and disables the new +// volume's unit, removes its settings, then deletes it (an abort is a +// delete: the name is tombstoned, never created again) and releases the +// source snapshot's dependent. Every step checks first, so an abort +// interrupted anywhere is finished by running it again. +func volumeRestoreAbort(ctx context.Context, env verbEnv, o restoreOpts, stdout, stderr io.Writer) int { + t := o.New.VolumeID + unit := volumeUnit(t) + again := fmt.Sprintf("sudo sw-block volume restore %s --snapshot %s --as %s --abort", o.Source, shQuote(o.Snapshot), t) + fail := func(step string, err error) int { + fmt.Fprintf(stderr, "sw-block volume restore --abort: %s: %v; run it again: %s\n", step, err, again) + return 1 + } + src, err := readEnvFile(filepath.Join(env.EtcDir, o.Source+".env")) + if err != nil { + return fail("settings", fmt.Errorf("the source's settings: %w (the abort needs its master and chunk filer)", err)) + } + master, filer := src["SWB_MASTER_ADDR"], []string{"--chunk-filer", src["SWB_CHUNK_FILER"], "--chunk-path", src["SWB_CHUNK_PATH"], "--timeout", o.Timeout.String()} + // Before anything changes: T must be this restore's target, by the + // master's durable record of it (source, snapshot and request id). Any + // other answer stops the abort with nothing done. + if err := env.step(stdout, "verify", fmt.Sprintf("check at %s that %s is the target of this restore", master, t)); err != nil { + return fail("verify", err) + } + rctx, cancel := context.WithTimeout(ctx, o.Timeout) + rec, rerr := restoreTargetRecord(rctx, master, t) + cancel() + switch { + case status.Code(rerr) == codes.NotFound: + // The master has no record of T: the restore was refused before it + // wrote anything (the master undid it). Nothing to undo. + fmt.Fprintf(stdout, "sw-block volume restore --abort: the master has no record of %s: nothing to undo\n", t) + return 0 + case rerr != nil: + return fail("verify", fmt.Errorf("read %s's record at the master: %w (nothing was changed)", t, rerr)) + case rec.GetSourceVolume() == "" && rec.GetSourceSnapshot() == "" && rec.GetCreateRequestId() == "": + // Unknown, never a match: a blockmaster before v1.0.1 does not + // report the tuple, and a plain volume has none. + fmt.Fprintf(stderr, "sw-block volume restore --abort: verify: refused: the master's record of %s carries no restore tuple, so it cannot be confirmed as the target of this restore (a blockmaster before v1.0.1 does not report it; or %s is not a restore target); nothing was changed\n", t, t) + return ops.VolumeStatusExitInvalid + case rec.GetVolumeId() != t || rec.GetSourceVolume() != o.Source || rec.GetSourceSnapshot() != o.Snapshot || rec.GetCreateRequestId() != derivedID("restore", t, o.Source, o.Snapshot): + fmt.Fprintf(stderr, "sw-block volume restore --abort: verify: refused: %s is not the target of this restore (the master records source %q, snapshot %q, request %q); nothing was changed\n", + t, rec.GetSourceVolume(), rec.GetSourceSnapshot(), rec.GetCreateRequestId()) + return ops.VolumeStatusExitInvalid + } + // And this host's T must be that target: its settings name this volume, + // this master and the record's layout id. Settings that name anything + // else are another installation; a running unit without settings cannot + // be confirmed. Either refuses with nothing changed. No settings and a + // stopped unit is an abort already past its settings step. + envPath := filepath.Join(env.EtcDir, t+".env") + if local, lerr := readEnvFile(envPath); lerr == nil { + // The unit passes SWB_VOLUME_EXTRA_ARGS after its own flags, so a + // flag there overrides the nominal settings: only the exact pair + // volume start writes (--layout-id ) is accepted; anything more + // (another layout id after it, a --master or --volume-id override) + // fails closed. + if local["SWB_VOLUME_ID"] != t || local["SWB_MASTER_ADDR"] != master || strings.Join(strings.Fields(local["SWB_VOLUME_EXTRA_ARGS"]), " ") != "--layout-id "+rec.GetLayoutId() { + fmt.Fprintf(stderr, "sw-block volume restore --abort: verify: refused: %s on this host is another installation (settings name volume %q, master %q, %q; the target is layout %s at %s); nothing was changed\n", + envPath, local["SWB_VOLUME_ID"], local["SWB_MASTER_ADDR"], local["SWB_VOLUME_EXTRA_ARGS"], rec.GetLayoutId(), master) + return ops.VolumeStatusExitInvalid + } + } else if !errors.Is(lerr, os.ErrNotExist) { + return fail("verify", fmt.Errorf("read %s: %w (nothing was changed)", envPath, lerr)) + } else if st, serr := unitState(ctx, env, unit); serr != nil { + return fail("verify", fmt.Errorf("%s's state: %w (nothing was changed)", unit, serr)) + } else if !unitStopped(st) { + fmt.Fprintf(stderr, "sw-block volume restore --abort: verify: refused: %s is %s but has no settings, so it cannot be confirmed as this restore's target; nothing was changed\n", unit, st) + return ops.VolumeStatusExitInvalid + } + if err := env.step(stdout, "unit", "stop and disable "+unit); err != nil { + return fail("unit", err) + } + if st, serr := unitState(ctx, env, unit); serr != nil { + return fail("unit", serr) + } else if !unitStopped(st) { + if out, err := env.Systemctl(ctx, "disable", "--now", unit); err != nil { + return fail("unit", fmt.Errorf("%v: %s", err, out)) + } + } else if out, err := env.Systemctl(ctx, "disable", unit); err != nil && !strings.Contains(out, "not loaded") { + return fail("unit", fmt.Errorf("%v: %s", err, out)) + } + if err := env.step(stdout, "settings", "remove "+filepath.Join(env.EtcDir, t+".env")); err != nil { + return fail("settings", err) + } + if err := os.Remove(filepath.Join(env.EtcDir, t+".env")); err != nil && !errors.Is(err, os.ErrNotExist) { + return fail("settings", err) + } + if err := env.step(stdout, "delete", fmt.Sprintf("delete %s (then release %s's snapshot %s)", t, o.Source, shQuote(o.Snapshot))); err != nil { + return fail("delete", err) + } + // T with its first HEAD: volume-delete (the master marks it deleting, + // then the dependent is released). T without HEAD (the restore never + // finished): release, which tombstones T first, then releases. Either + // way the dependent goes only after T can no longer serve, and the name + // is never created again. + // + // volume_not_found names both "the master does not know T" and "T has + // no HEAD". The master answered for T at the verify step (its NotFound + // ended the abort there), so a volume_not_found from the delete is the layout's: + // no HEAD. Should the master forget T in between, the release's own + // resolve fails and the abort says to run it again. + code, ecode, msg := runChunkStep(runOpsVolumeDelete, append([]string{"--volume", t, "--master", master, "--request-id", derivedID("abort", t, o.Source, o.Snapshot)}, filer...)) + released := false + if code != 0 && ecode == "volume_not_found" { + code, ecode, msg = runChunkStep(runOpsRelease, append([]string{"--source", o.Source, "--target", t, "--master", master}, filer...)) + released = true + } + if code != 0 { + return fail("delete", fmt.Errorf("exit %d: %s %s", code, ecode, msg)) + } + fmt.Fprintf(stdout, "sw-block volume restore --abort: %s is deleted (its name is not reused); %s's snapshot %s is released\n", t, o.Source, shQuote(o.Snapshot)) + if released { + // The release path changes only the layout: the master keeps the + // restore's not-ready record, so the name stays taken there too. + fmt.Fprintf(stdout, "sw-block volume restore --abort: %s never got its first HEAD: it is tombstoned; the master keeps its not-ready restore record (never placed or served; the name stays taken)\n", t) + } + return 0 +} + +// runChunkStep runs one ops chunk command in-process and returns its exit +// code, its JSON error code and its log line. +func runChunkStep(cmd func(args []string, stdout, stderr io.Writer) int, args []string) (int, string, string) { + var out, errb bytes.Buffer + code := cmd(args, &out, &errb) + var e chunkErrBody + if code != 0 { + _ = json.Unmarshal(bytes.TrimSpace(out.Bytes()), &e) + } + return code, e.Code, strings.TrimSpace(errb.String()) +} + +// runOpsVolumeDelete and runOpsRelease are ops chunk volume-delete and ops +// chunk release, run in-process (variables so tests can stand in for them). +var ( + runOpsVolumeDelete = chunkVolumeDelete + runOpsRelease = chunkRelease +) + +// restoreRefusal maps a refused restore create to its JSON code (the codes +// ops chunk restore reports); "" for an outcome a re-run may change. +func restoreRefusal(err error) string { + if lifecycleclient.Reason(err) == lifecycleclient.ReasonRestoreSourceNotOwn { + return "restore_source_not_own" + } + switch status.Code(err) { + case codes.NotFound: + return "snapshot_not_found" + case codes.AlreadyExists: + return "target_exists" + case codes.InvalidArgument: + return codeBadRequestCLI + case codes.FailedPrecondition: + return "not_admitted" + } + return "" +} + +// restorePlaced reads the volume's published authority line at the master +// (QueryVolumeStatus: the publisher's line itself, which exists before any +// lease is granted on it) and its bindings (QueryWorkspace): placed when +// the line is this replica's and a live binding names this server and +// these addresses; why is set when a line exists for anything else; +// neither when no line is published yet (an identical placement is then +// accepted again). +func restorePlaced(ctx context.Context, master string, b *control.WorkspaceBinding, replica string) (placed bool, why string, err error) { + line, err := volumeStatusQuery(ctx, master, b.VolumeId) + if err != nil { + return false, "", err + } + if line.GetReplicaId() == "" || line.GetEpoch() == 0 { + return false, "", nil + } + if line.GetReplicaId() != replica { + return false, fmt.Sprintf("%s's authority line is replica %q, not %q", b.VolumeId, line.GetReplicaId(), replica), nil + } + st, err := workspaceQuery(ctx, master, b.VolumeId) + if err != nil { + return false, "", err + } + for _, have := range st.GetBindings() { + if have.GetServerId() == b.ServerId && have.GetDataAddr() == b.DataAddr && have.GetCtrlAddr() == b.CtrlAddr && !have.GetRetired() { + return true, "", nil + } + } + return false, fmt.Sprintf("%s's authority line has no live binding for server %s at %s/%s", b.VolumeId, b.ServerId, b.DataAddr, b.CtrlAddr), nil +} + +// volumeStatusQuery is the master's QueryVolumeStatus: the publisher's +// current authority line for the volume. +var volumeStatusQuery = func(ctx context.Context, master, volume string) (*control.StatusResponse, error) { + conn, err := link.DialMasterFromEnv(master) + if err != nil { + return nil, err + } + defer conn.Close() + return control.NewEvidenceServiceClient(conn).QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: volume}) +} + +// workspaceQuery is the master's QueryWorkspace. +var workspaceQuery = func(ctx context.Context, master, volume string) (*control.WorkspaceStatus, error) { + conn, err := link.DialMasterFromEnv(master) + if err != nil { + return nil, err + } + defer conn.Close() + return control.NewWorkspaceServiceClient(conn).QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: volume}) +} + +// restoreTargetRecord is the master's GetVolume for a restore target: its +// durable record, with the restore tuple it was created for. +var restoreTargetRecord = func(ctx context.Context, master, name string) (*control.CreateVolumeResponse, error) { + conn, err := link.DialMasterFromEnv(master) + if err != nil { + return nil, err + } + defer conn.Close() + return control.NewLifecycleServiceClient(conn).GetVolume(ctx, &control.GetLifecycleVolumeRequest{VolumeId: name}) +} + +// workspaceBindPlace dials the master and records the new volume's binding +// and placement (bindAndPlace, the calls ops volume create makes). +var workspaceBindPlace = func(ctx context.Context, master string, b *control.WorkspaceBinding, replica string) (string, error) { + conn, err := link.DialMasterFromEnv(master) + if err != nil { + return "connect", err + } + defer conn.Close() + return bindAndPlace(ctx, control.NewWorkspaceServiceClient(conn), b, replica) +} diff --git a/seaweed-block/cmd/sw-block/volume_backup_test.go b/seaweed-block/cmd/sw-block/volume_backup_test.go new file mode 100644 index 0000000000..bebf56f740 --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_backup_test.go @@ -0,0 +1,1018 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// --- fakes: the holder's snapshot route and the master's restore --- + +// snapHolder is the holder's POST /chunk/snapshot: one snapshot per name, +// a replay of the same request id answers the same snapshot. +type snapHolder struct { + mu sync.Mutex + snaps map[string]string // name -> its backup label ("" for a snapshot without one) + posts int + mode string // "", "lost" (taken, answer lost), "refuse", "unknown", "missing-" + srv *httptest.Server +} + +func newSnapHolder(t *testing.T) *snapHolder { + h := &snapHolder{snaps: map[string]string{}} + h.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/chunk/snapshot" || r.Method != http.MethodPost { + http.NotFound(w, r) + return + } + var q struct { + VolumeID, Name, RequestID string + Labels map[string]string + } + _ = json.NewDecoder(r.Body).Decode(&q) + h.mu.Lock() + defer h.mu.Unlock() + h.posts++ + switch h.mode { + case "refuse": + w.WriteHeader(http.StatusServiceUnavailable) + _ = json.NewEncoder(w).Encode(map[string]string{"code": "not_primary", "message": "not the primary"}) + return + case "unknown": + w.WriteHeader(http.StatusServiceUnavailable) + _ = json.NewEncoder(w).Encode(map[string]string{"code": "outcome_unknown", "message": "the HEAD write's result is not known"}) + return + } + // As the holder does: the request id is not kept, and an existing + // name answers the snapshot already there, with its own labels. + if _, ok := h.snaps[q.Name]; !ok { + h.snaps[q.Name] = q.Labels[backupLabel] + } + answer := map[string]any{"volumeID": q.VolumeID, "name": q.Name, "headGen": 5, "headEpoch": 1, "cutLSN": 42, + "createdNs": time.Date(2026, 11, 29, 10, 0, 0, 0, time.UTC).UnixNano(), "labels": map[string]string{backupLabel: h.snaps[q.Name]}} + if h.snaps[q.Name] == "" { + answer["labels"] = map[string]string{} + } + for _, f := range []string{"headGen", "cutLSN", "createdNs"} { + if h.mode == "missing-"+f { + delete(answer, f) + } + } + if h.mode == "lost" { + h.mode = "" + if hj, ok := w.(http.Hijacker); ok { + c, _, _ := hj.Hijack() + _ = c.Close() + } + return + } + _ = json.NewEncoder(w).Encode(answer) + })) + t.Cleanup(h.srv.Close) + return h +} + +// The test reads and sets the fake's state through these, under its lock: +// the handler runs on the server's goroutines. +func (h *snapHolder) setMode(m string) { h.mu.Lock(); h.mode = m; h.mu.Unlock() } + +func (h *snapHolder) count() int { h.mu.Lock(); defer h.mu.Unlock(); return len(h.snaps) } + +func (h *snapHolder) label(name string) string { + h.mu.Lock() + defer h.mu.Unlock() + return h.snaps[name] +} + +func (h *snapHolder) postCount() int { + h.mu.Lock() + defer h.mu.Unlock() + return h.posts +} + +func (h *snapHolder) put(name, label string) { h.mu.Lock(); h.snaps[name] = label; h.mu.Unlock() } + +// restoreMaster is a running master's restore create (journaled: the same +// request id completes it, another id is refused), GetVolume, and the +// workspace binding and placement, behind real loopback gRPC. +// +// The target's store is the real layout catalog (the in-memory filer the +// ops chunk tests use): a store-ready create runs the catalog's own +// Restore, which adds the source snapshot's dependent; the abort runs the +// production ops chunk volume-delete and release against it, so the +// dependent's removal and the tombstone are the catalog's, not a flag. +// Placement follows the real master: an identical placement is accepted +// until the volume's authority line is published (the unit started), then +// refused as already assigned; QueryWorkspace shows the line and bindings. +type restoreMaster struct { + control.UnimplementedLifecycleServiceServer + control.UnimplementedWorkspaceServiceServer + control.UnimplementedEvidenceServiceServer + mu sync.Mutex + vols map[string]*restoreRec + ids map[string]layout.VolumeID // layout ids the master minted + src chunkstore.VolumeRef // vol-a in the catalog, with snapshot s1 + cat *chunkstore.BCatalog + creates int + binds int + places int + reserves int + bound map[string]*control.WorkspaceBinding + placed map[string]string // volume -> replica + published map[string]bool // the authority line exists (the holder started) + failNext string // "create-lost", "create-half", "create-notready", "place-lost", "bind-refuse", "publish-race[-other|-reread-fails]" + statusErr bool // the next QueryVolumeStatus fails (Unavailable) +} + +type restoreRec struct { + source, snap, req string + ready, deleted bool +} + +func (m *restoreMaster) CreateVolume(ctx context.Context, q *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) { + m.mu.Lock() + defer m.mu.Unlock() + m.creates++ + if q.GetSourceVolume() == "vol-t" { // a restore target's snapshot names another volume's chunks + return nil, lifecycleclient.WithReason(status.New(codes.FailedPrecondition, "restore target: the snapshot names another volume's chunks"), lifecycleclient.ReasonRestoreSourceNotOwn).Err() + } + if q.GetSourceVolume() != "vol-a" { + return nil, status.Error(codes.FailedPrecondition, "source is not this cluster's") + } + if q.GetSourceSnapshot() != "s1" { + return nil, status.Error(codes.NotFound, "no such snapshot") + } + r, ok := m.vols[q.VolumeId] + switch { + case ok && r.req != q.CreateRequestId: + return nil, status.Error(codes.AlreadyExists, "create volume: vol-r is bound to another restore request") + case ok && r.deleted: // as the master answers a deleting target + return nil, status.Error(codes.FailedPrecondition, "restore target: "+layout.ErrVolumeDeleting.Error()) + case !ok: + r = &restoreRec{source: q.SourceVolume, snap: q.SourceSnapshot, req: q.CreateRequestId} + m.vols[q.VolumeId] = r + id, err := layout.NewVolumeID() + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + m.ids[q.VolumeId] = id + } + fail := m.failNext + if fail == "create-half" { // journaled not-ready; the store is never made + m.failNext = "" + return nil, status.Error(codes.Unavailable, "master lost") + } + if fail == "create-badlayout" { // a store-ready answer without a valid layout id + m.failNext = "" + a := m.answer(q.VolumeId, r) + a.StoreReady, a.LayoutId = true, "not-a-layout-id" + return a, nil + } + if fail == "create-notready" { // answered, but the record is not ready yet + m.failNext = "" + return m.answer(q.VolumeId, r), nil + } + if !r.ready { + // The store and the dependent: the catalog's own restore. A tombstoned + // or existing target is the catalog's refusal. + if _, err := m.cat.Restore(ctx, m.src, "s1", chunkstore.VolumeRef{Name: q.VolumeId, ID: m.ids[q.VolumeId]}); err != nil { + if errors.Is(err, layout.ErrExists) || errors.Is(err, layout.ErrVolumeDeleting) { + return nil, status.Error(codes.FailedPrecondition, "restore target: "+err.Error()) // the master's mapping + } + return nil, status.Error(codes.Internal, err.Error()) + } + r.ready = true + } + if fail == "create-lost" { + m.failNext = "" + return nil, status.Error(codes.Unavailable, "reply lost") + } + return m.answer(q.VolumeId, r), nil +} + +func (m *restoreMaster) answer(name string, r *restoreRec) *control.CreateVolumeResponse { + id, ok := m.ids[name] + lid := "aabbccddeeff00112233445566778899" + if ok { + lid = id.String() + } + return &control.CreateVolumeResponse{VolumeId: name, SizeBytes: 1 << 30, ReplicationFactor: 1, LayoutId: lid, BlockSize: 4096, StoreReady: r.ready, + SourceVolume: r.source, SourceSnapshot: r.snap, CreateRequestId: r.req} +} + +func (m *restoreMaster) GetVolume(_ context.Context, q *control.GetLifecycleVolumeRequest) (*control.CreateVolumeResponse, error) { + m.mu.Lock() + defer m.mu.Unlock() + if q.VolumeId == "vol-a" { + return &control.CreateVolumeResponse{VolumeId: "vol-a", SizeBytes: 1 << 30, LayoutId: m.src.ID.String(), StoreReady: true}, nil + } + r, ok := m.vols[q.VolumeId] + if !ok { + return nil, status.Error(codes.NotFound, "no such volume") + } + return m.answer(q.VolumeId, r), nil +} + +// ReserveVolumeDeletion and CheckVolumeNoLiveLease are the delete's master +// authority (ops chunk volume-delete): the reservation marks the record +// deleting for good. +func (m *restoreMaster) ReserveVolumeDeletion(_ context.Context, q *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) { + m.mu.Lock() + defer m.mu.Unlock() + m.reserves++ + r, ok := m.vols[q.GetVolumeId()] + if !ok { + return nil, status.Error(codes.NotFound, "volume not found") + } + r.deleted = true + return &control.MarkVolumeDeletingResponse{}, nil +} + +func (m *restoreMaster) CheckVolumeNoLiveLease(_ context.Context, q *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.published[q.GetVolumeId()] { + return nil, status.Error(codes.FailedPrecondition, "a live authority line") + } + return &control.MarkVolumeDeletingResponse{}, nil +} + +func (m *restoreMaster) RegisterWorkspaceBinding(_ context.Context, q *control.WorkspaceBinding) (*control.WorkspaceBinding, error) { + m.mu.Lock() + defer m.mu.Unlock() + if r, ok := m.vols[q.VolumeId]; !ok || !r.ready || r.deleted { + return nil, status.Error(codes.FailedPrecondition, "binding before a store-ready create") + } + if m.failNext == "bind-refuse" { + m.failNext = "" + return nil, status.Error(codes.FailedPrecondition, "server not registered") + } + m.binds++ + m.bound[q.VolumeId] = q + return q, nil +} + +func (m *restoreMaster) PlaceWorkspace(_ context.Context, q *control.WorkspacePlacement) (*control.WorkspaceEmpty, error) { + m.mu.Lock() + defer m.mu.Unlock() + m.places++ + if strings.HasPrefix(m.failNext, "publish-race") { // the line is published just before this placement lands + rep := q.ReplicaId + if m.failNext == "publish-race-other" { + rep = "r1" + } + m.statusErr = m.failNext == "publish-race-reread-fails" + m.failNext = "" + m.placed[q.VolumeId], m.published[q.VolumeId] = rep, true + } + if m.published[q.VolumeId] { // RecordWorkspacePlacement once a line exists + return nil, status.Error(codes.FailedPrecondition, "workspace placement: volume already assigned; use move") + } + if rep, ok := m.placed[q.VolumeId]; ok && rep != q.ReplicaId { + return nil, status.Error(codes.FailedPrecondition, "placement differs from the recorded one") + } + m.placed[q.VolumeId] = q.ReplicaId + if m.failNext == "place-lost" { + m.failNext = "" + return nil, status.Error(codes.Unavailable, "reply lost") + } + return &control.WorkspaceEmpty{}, nil +} + +func (m *restoreMaster) QueryWorkspace(_ context.Context, q *control.WorkspaceVolume) (*control.WorkspaceStatus, error) { + m.mu.Lock() + defer m.mu.Unlock() + // Bindings only: no holder ever renews here, so no lease is granted, + // the interval a published line spends before its first lease. + out := &control.WorkspaceStatus{} + if b, ok := m.bound[q.GetVolumeId()]; ok { + out.Bindings = append(out.Bindings, b) + } + return out, nil +} + +// QueryVolumeStatus is the publisher's line: present once published, +// whether or not a lease was granted on it. +func (m *restoreMaster) QueryVolumeStatus(_ context.Context, q *control.StatusRequest) (*control.StatusResponse, error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.statusErr { + m.statusErr = false + return nil, status.Error(codes.Unavailable, "master unavailable") + } + out := &control.StatusResponse{VolumeId: q.GetVolumeId()} + if m.published[q.GetVolumeId()] { + out.ReplicaId, out.Epoch, out.Assigned = m.placed[q.GetVolumeId()], 1, true + } + return out, nil +} + +func serveRestoreMaster(t *testing.T) (*restoreMaster, string) { + t.Helper() + for _, key := range []string{"SW_BLOCK_TLS_CERT", "SW_BLOCK_TLS_KEY", "SW_BLOCK_TLS_CA"} { + t.Setenv(key, "") + } + store := newMemChunkStore() + cat, err := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + prev := dialChunkFiler + assumeSingleFilerFixture(t) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil } + t.Cleanup(func() { dialChunkFiler = prev }) + m := &restoreMaster{vols: map[string]*restoreRec{}, ids: map[string]layout.VolumeID{}, cat: cat, src: cliVolume(t, store, "vol-a", "s1"), + bound: map[string]*control.WorkspaceBinding{}, placed: map[string]string{}, published: map[string]bool{}} + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + control.RegisterLifecycleServiceServer(server, m) + control.RegisterWorkspaceServiceServer(server, m) + control.RegisterEvidenceServiceServer(server, m) + go func() { _ = server.Serve(lis) }() + t.Cleanup(server.Stop) + return m, lis.Addr().String() +} + +// recordChunkSteps runs the production ops chunk volume-delete and release +// (against the catalog serveRestoreMaster dials), recording each call and +// its exit with the unit's state at that moment. +func recordChunkSteps(t *testing.T, h *fakeHost, order *[]string) { + oldD, oldR := runOpsVolumeDelete, runOpsRelease + t.Cleanup(func() { runOpsVolumeDelete, runOpsRelease = oldD, oldR }) + flagOf := func(args []string, name string) string { + for i := 0; i+1 < len(args); i++ { + if args[i] == name { + return args[i+1] + } + } + return "" + } + unit := func() string { h.mu.Lock(); defer h.mu.Unlock(); return h.unit } + runOpsVolumeDelete = func(args []string, stdout, stderr io.Writer) int { + u := unit() + code := chunkVolumeDelete(args, stdout, stderr) + *order = append(*order, fmt.Sprintf("delete %s req=%s unit=%s exit=%d", flagOf(args, "--volume"), flagOf(args, "--request-id"), u, code)) + return code + } + runOpsRelease = func(args []string, stdout, stderr io.Writer) int { + u := unit() + code := chunkRelease(args, stdout, stderr) + *order = append(*order, fmt.Sprintf("release %s %s unit=%s exit=%d", flagOf(args, "--source"), flagOf(args, "--target"), u, code)) + return code + } +} + +// dependentsOf is the catalog's list of restore targets of vol-a's s1. +func dependentsOf(t *testing.T, m *restoreMaster) []string { + t.Helper() + h, ok, err := m.cat.ReadHead(context.Background(), m.src) + if err != nil || !ok { + t.Fatalf("source HEAD: %v %v", ok, err) + } + var out []string + for _, d := range h.Snapshots["s1"].Dependents { + out = append(out, d.Target) + } + return out +} + +// sourceEnv writes vol-a's settings as volume start would. +func sourceEnv(t *testing.T, env verbEnv, master, status string, chunk bool) { + v := testSpecs()["walstore"] + if chunk { + v = testSpecs()["walstore-chunk"] + } + v.Master, v.StatusAddr = master, status + if err := os.WriteFile(filepath.Join(env.EtcDir, "vol-a.env"), []byte(renderEnv("# test\n", v.env())), 0o640); err != nil { + t.Fatal(err) + } +} + +func runBackup(env verbEnv, args ...string) (int, string, string) { + var out, errb bytes.Buffer + o, err := parseVolumeBackup(args, &errb) + if err != nil { + return 2, out.String(), errb.String() + } + code := volumeBackup(context.Background(), env, o, &out, &errb) + return code, out.String(), errb.String() +} + +func runRestore(env verbEnv, args ...string) (int, string, string) { + var out, errb bytes.Buffer + o, err := parseVolumeRestore(args, &errb) + if err != nil { + return 2, out.String(), errb.String() + } + var code int + if o.Abort { + code = volumeRestoreAbort(context.Background(), env, o, &out, &errb) + } else { + code = volumeRestore(context.Background(), env, o, args, &out, &errb) + } + return code, out.String(), errb.String() +} + +// restoreArgs is the restore command for vol-r, served on the fake host. +func restoreArgs(h *fakeHost) []string { + return []string{"vol-a", "--snapshot", "s1", "--as", "vol-r", "--replica-id", "r9", "--data-addr", "10.0.0.7:9301", + "--ctrl-addr", "10.0.0.7:9302", "--status-addr", h.addr(), "--nvme-listen", "10.0.0.7:4430", "--wait", "1s", "--timeout", "5s"} +} + +const abortCmd = "sudo sw-block volume restore vol-a --snapshot s1 --as vol-r --abort" + +func restoreSetup(t *testing.T) (*fakeHost, verbEnv, *restoreMaster, *[]string) { + h := newFakeHost(t) + h.name = "vol-r" + env := h.env(t) + base := env.Systemctl + m, master := serveRestoreMaster(t) + // The holder starting publishes the volume's authority line; its stop + // ends it (the test stands the lease's expiry in for the real wait). + line := func(on bool) { + m.mu.Lock() + m.published["vol-r"] = on + m.mu.Unlock() + } + env.Systemctl = func(ctx context.Context, a ...string) (string, error) { + if a[0] == "disable" && len(a) > 1 && a[1] == "--now" { + _, _ = base(ctx, "stop", a[2]) + line(false) + } + out, err := base(ctx, a...) + if a[0] == "enable" && err == nil { + line(true) + } + if a[0] == "stop" { + line(false) + } + return out, err + } + sourceEnv(t, env, master, h.addr(), true) + order := &[]string{} + recordChunkSteps(t, h, order) + return h, env, m, order +} + +// --- volume backup --- + +// backup takes one named snapshot with a request id derived from the +// volume and the name; the same command again replays it, never a second. +func TestVolumeBackupTakesOneSnapshotAndRerunReplays(t *testing.T) { + h := newFakeHost(t) + env := h.env(t) + sh := newSnapHolder(t) + sourceEnv(t, env, "127.0.0.1:1", strings.TrimPrefix(sh.srv.URL, "http://"), true) + // No generated default: without --name the command refuses before + // any request (a name it chose would be lost with its terminal). + if code, _, errs := runBackup(env, "vol-a"); code != 2 || !strings.Contains(errs, "--name is required") || sh.postCount() != 0 { + t.Fatalf("no --name: %d %s (posts %d)", code, errs, sh.postCount()) + } + code, out, errs := runBackup(env, "vol-a", "--name", "backup-20261128T230000Z") + if code != 0 || !strings.Contains(out, "snapshot backup-20261128T230000Z of vol-a") || !strings.Contains(out, "sudo sw-block volume restore vol-a --snapshot backup-20261128T230000Z --as ") { + t.Fatalf("backup: %d\n%s\n%s", code, out, errs) + } + if got := sh.label("backup-20261128T230000Z"); got != backupTag(derivedID("backup", "vol-a", "backup-20261128T230000Z")) { + t.Fatalf("request id %q is not derived from the volume and the name", got) + } + code, out, _ = runBackup(env, "vol-a", "--name", "backup-20261128T230000Z") + if code != 0 || !strings.Contains(out, "snapshot backup-20261128T230000Z of vol-a") || sh.count() != 1 { + t.Fatalf("rerun: %d %s (snapshots %d)", code, out, sh.count()) + } +} + +// Interrupted before the snapshot, or with the snapshot taken and its +// answer lost or unknown: the failure names the same command; running it +// completes with exactly one snapshot. +func TestVolumeBackupInterruptedResumesWithTheSameCommand(t *testing.T) { + for _, c := range []string{"step", "lost", "unknown", "refuse"} { + t.Run(c, func(t *testing.T) { + h := newFakeHost(t) + env := h.env(t) + sh := newSnapHolder(t) + sourceEnv(t, env, "127.0.0.1:1", strings.TrimPrefix(sh.srv.URL, "http://"), true) + if c == "step" { + env.Step = func(name string) error { + if name == "snapshot" { + return errors.New("interrupted") + } + return nil + } + } else { + sh.setMode(c) + } + code, _, errs := runBackup(env, "vol-a", "--name", "nightly") + wantCode := 1 + if c == "refuse" { + wantCode = 2 + } + if code != wantCode || !strings.Contains(errs, "run the same command") || !strings.Contains(errs, "sudo sw-block volume backup vol-a --name nightly") || !strings.Contains(errs, "keeps what it uploaded") { + t.Fatalf("interrupted backup: %d %s", code, errs) + } + env.Step = nil + sh.setMode("") + if code, _, errs := runBackup(env, "vol-a", "--name", "nightly"); code != 0 || sh.count() != 1 { + t.Fatalf("rerun: %d %s (snapshots %d)", code, errs, sh.count()) + } + }) + } +} + +// An answer missing a fact backup reports (head generation, cut LSN, time) +// is an unknown outcome, never printed as zero; the same command then +// completes with the one snapshot. +func TestVolumeBackupIncompleteAnswerIsUnknown(t *testing.T) { + for _, f := range []string{"headGen", "cutLSN", "createdNs"} { + t.Run(f, func(t *testing.T) { + h := newFakeHost(t) + env := h.env(t) + sh := newSnapHolder(t) + sourceEnv(t, env, "127.0.0.1:1", strings.TrimPrefix(sh.srv.URL, "http://"), true) + sh.setMode("missing-" + f) + code, out, errs := runBackup(env, "vol-a", "--name", "n1") + if code != 1 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(out, "head generation") { + t.Fatalf("missing %s: %d %s %s", f, code, out, errs) + } + sh.setMode("") + if code, out, errs := runBackup(env, "vol-a", "--name", "n1"); code != 0 || !strings.Contains(out, "cut LSN 42") || sh.count() != 1 { + t.Fatalf("rerun: %d %s %s", code, out, errs) + } + }) + } +} + +func TestVolumeBackupRefusals(t *testing.T) { + h := newFakeHost(t) + env := h.env(t) + sh := newSnapHolder(t) + if code, _, errs := runBackup(env, "vol-a", "--name", "n1"); code != 2 || !strings.Contains(errs, "was vol-a started") { + t.Fatalf("unknown volume: %d %s", code, errs) + } + sourceEnv(t, env, "127.0.0.1:1", strings.TrimPrefix(sh.srv.URL, "http://"), false) + if code, _, errs := runBackup(env, "vol-a", "--name", "n1"); code != 2 || !strings.Contains(errs, "is walstore") || sh.postCount() != 0 { + t.Fatalf("walstore: %d %s", code, errs) + } + sourceEnv(t, env, "127.0.0.1:1", strings.TrimPrefix(sh.srv.URL, "http://"), true) + sh.setMode("refuse") + if code, _, errs := runBackup(env, "vol-a", "--name", "n1"); code != 2 || !strings.Contains(errs, "not_primary") { + t.Fatalf("refused: %d %s", code, errs) + } + sh.setMode("") + // The holder answers an existing name with the snapshot already there: + // one another backup took (another label) or one taken without a label + // (ops chunk snapshot, the schedule) is refused, never reported as ours. + sh.put("taken", "someone-else") + sh.put("plain", "") + for _, name := range []string{"plain"} { + if code, _, errs := runBackup(env, "vol-a", "--name", name); code != 2 || !strings.Contains(errs, "snapshot_name_taken") || !strings.Contains(errs, "choose a new snapshot name") || strings.Contains(errs, "run the same command") { + t.Fatalf("name %s without our label: %d %s", name, code, errs) + } + } + if code, _, errs := runBackup(env, "vol-a", "--name", "taken"); code != 2 || !strings.Contains(errs, "snapshot_name_taken") { + t.Fatalf("name of another request: %d %s", code, errs) + } +} + +// --- volume restore --- + +// restore creates the target from the snapshot with the derived request +// id, binds and places it on this host, starts it with the source's master +// and chunk filer and the restored size, and an identical re-run finds it +// all done (no second target, the same request). +func TestVolumeRestoreCreatesPlacesAndStarts(t *testing.T) { + h, env, m, _ := restoreSetup(t) + code, out, errs := runRestore(env, restoreArgs(h)...) + if code != 0 || !strings.Contains(out, "vol-r holds vol-a's snapshot s1") || !strings.Contains(out, "nvme connect") { + t.Fatalf("restore: %d\n%s\n%s", code, out, errs) + } + r := m.vols["vol-r"] + if r == nil || r.req != derivedID("restore", "vol-r", "vol-a", "s1") || m.binds != 1 || m.places != 1 { + t.Fatalf("master after restore: %+v binds %d places %d", r, m.binds, m.places) + } + e, err := readEnvFile(filepath.Join(env.EtcDir, "vol-r.env")) + if err != nil { + t.Fatal(err) + } + src, _ := readEnvFile(filepath.Join(env.EtcDir, "vol-a.env")) + for k, want := range map[string]string{"SWB_VOLUME_ID": "vol-r", "SWB_DURABLE_IMPL": "walstore-chunk", "SWB_DURABLE_BLOCKS": "262144", + "SWB_MASTER_ADDR": src["SWB_MASTER_ADDR"], "SWB_CHUNK_FILER": src["SWB_CHUNK_FILER"], "SWB_CHUNK_PATH": src["SWB_CHUNK_PATH"], + "SWB_SERVER_ID": src["SWB_SERVER_ID"], "SWB_REPLICA_ID": "r9", "SWB_VOLUME_EXTRA_ARGS": "--layout-id " + m.ids["vol-r"].String()} { + if e[k] != want { + t.Errorf("%s = %q, want %q", k, e[k], want) + } + } + if code, _, errs := runRestore(env, restoreArgs(h)...); code != 0 || len(m.vols) != 1 { + t.Fatalf("identical re-run: %d %s (targets %d)", code, errs, len(m.vols)) + } +} + +// The crash table, both ways: interrupted at every step (and with the +// create or placement applied but its answer lost, and with the create +// journaled but never made), the failure names both exact commands; the +// same command then converges to one started target, and --abort instead +// leaves nothing behind: unit stopped and disabled, settings gone, the +// target deleted (or tombstoned when it never got HEAD) only after its +// unit stopped, and the dependent released. +func TestVolumeRestoreCrashTableBothWays(t *testing.T) { + type row struct{ name, step, fail string } + rows := []row{{"before-create", "restore", ""}, {"create-lost", "", "create-lost"}, {"create-half", "", "create-half"}, {"create-notready", "", "create-notready"}, + {"before-place", "place", ""}, {"place-lost", "", "place-lost"}, {"before-resolve", "resolve", ""}, + {"before-settings", "settings", ""}, {"before-unit", "unit", ""}, {"before-serve", "serve", ""}} + for _, r := range rows { + for _, way := range []string{"rerun", "abort"} { + t.Run(r.name+"/"+way, func(t *testing.T) { + h, env, m, order := restoreSetup(t) + env.Step = func(name string) error { + if name == r.step { + return errors.New("interrupted") + } + return nil + } + m.failNext = r.fail + code, _, errs := runRestore(env, restoreArgs(h)...) + if code != 1 || !strings.Contains(errs, "to finish, run the same command: sudo sw-block volume restore vol-a --snapshot s1 --as vol-r") || + !strings.Contains(errs, "to undo it: "+abortCmd) { + t.Fatalf("interrupted restore: %d\n%s", code, errs) + } + if strings.HasPrefix(r.fail, "create-") && (m.binds != 0 || h.called("enable") != 0) { + t.Fatalf("placed or started before the master confirmed the target ready (binds %d)", m.binds) + } + env.Step = nil + if way == "rerun" { + if code, _, errs := runRestore(env, restoreArgs(h)...); code != 0 { + t.Fatalf("re-run: %d %s", code, errs) + } + if len(m.vols) != 1 || !m.vols["vol-r"].ready || h.called("enable") == 0 { + t.Fatalf("after re-run: targets %d %+v", len(m.vols), m.vols["vol-r"]) + } + return + } + var firstAbortOut string + for i := 0; i < 2; i++ { // the abort, then the abort again (found done) + code, out, errs := runRestore(env, "vol-a", "--snapshot", "s1", "--as", "vol-r", "--abort", "--timeout", "5s") + if code != 0 { + t.Fatalf("abort %d: %d %s %s", i, code, out, errs) + } + if i == 0 { + firstAbortOut = out + } + } + if _, err := os.Stat(filepath.Join(env.EtcDir, "vol-r.env")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("settings left: %v", err) + } + if h.unit == "active" { + t.Fatal("unit still active after abort") + } + rec := m.vols["vol-r"] + if rec == nil { + if r.name != "before-create" { + t.Fatal("the target vanished from the master") + } + return + } + // The catalog's facts: the source snapshot no longer lists the + // target as a dependent. + if deps := dependentsOf(t, m); len(deps) != 0 { + t.Fatalf("the source snapshot still lists dependents %v after the abort (%v)", deps, *order) + } + for _, o := range *order { + if strings.Contains(o, "unit=active") { + t.Fatalf("delete or release while the unit could serve: %v", *order) + } + } + released := false + for _, o := range *order { + released = released || (strings.HasPrefix(o, "release ") && strings.HasSuffix(o, "exit=0")) + } + if rec.ready == released || (rec.ready && !rec.deleted) { + t.Fatalf("a target with HEAD goes through volume-delete (the master reserves it), one without through release: ready=%v deleted=%v %v", rec.ready, rec.deleted, *order) + } + if !rec.ready && !strings.Contains(firstAbortOut, "the master keeps its not-ready restore record") { + t.Fatalf("the release path must say what the master keeps: %s", firstAbortOut) + } + if rec.ready && strings.Contains(firstAbortOut, "not-ready restore record") { + t.Fatalf("a deleted target is not a kept not-ready record: %s", firstAbortOut) + } + // After an abort the name is never created again: the master + // refuses the deleting target, and the catalog's tombstone + // refuses a target that never had HEAD (FailedPrecondition). + if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "not_admitted") || !strings.Contains(errs, "restore target:") { + t.Fatalf("restore after abort: %d %s", code, errs) + } + }) + } + } +} + +// The abort's delete carries a request id derived from its arguments, so a +// re-run is the same delete. +func TestVolumeRestoreAbortUsesADerivedDeleteID(t *testing.T) { + h, env, _, order := restoreSetup(t) + if code, _, errs := runRestore(env, restoreArgs(h)...); code != 0 { + t.Fatal(errs) + } + for i := 0; i < 2; i++ { + _, _, _ = runRestore(env, "vol-a", "--snapshot", "s1", "--as", "vol-r", "--abort") + } + want := "req=" + derivedID("abort", "vol-r", "vol-a", "s1") + if len(*order) != 2 || !strings.Contains((*order)[0], want) || !strings.Contains((*order)[1], want) { + t.Fatalf("deletes: %v", *order) + } +} + +func TestVolumeRestoreRefusals(t *testing.T) { + h, env, m, _ := restoreSetup(t) + for _, c := range []struct { + name string + args []string + want string + }{ + {"missing snapshot", append(restoreArgs(h), "--snapshot", "nope"), "snapshot_not_found"}, + {"same name", []string{"vol-a", "--snapshot", "s1", "--as", "vol-a"}, "a new volume name"}, + {"no snapshot flag", []string{"vol-a", "--as", "vol-r"}, "--snapshot is required"}, + {"unknown source", append([]string{"vol-z"}, restoreArgs(h)[1:]...), "was vol-z started"}, + } { + if code, _, errs := runRestore(env, c.args...); code != 2 || !strings.Contains(errs, c.want) { + t.Errorf("%s: %d %s", c.name, code, errs) + } + } + // A source that is itself a restore target: the master's typed reason. + sourceT := filepath.Join(env.EtcDir, "vol-t.env") + if raw, err := os.ReadFile(filepath.Join(env.EtcDir, "vol-a.env")); err != nil || os.WriteFile(sourceT, raw, 0o640) != nil { + t.Fatal(err) + } + if code, _, errs := runRestore(env, append([]string{"vol-t"}, restoreArgs(h)[1:]...)...); code != 2 || !strings.Contains(errs, "restore_source_not_own") { + t.Errorf("restore target as source: %d %s", code, errs) + } + m.vols["vol-r"] = &restoreRec{source: "vol-a", snap: "s1", req: "another", ready: true} + if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "target_exists") { + t.Errorf("target of another request: %d %s", code, errs) + } + delete(m.vols, "vol-r") + sourceEnv(t, env, "127.0.0.1:1", h.addr(), false) + if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "is walstore") { + t.Errorf("walstore source: %d %s", code, errs) + } + if m.creates != 3 { + t.Errorf("creates %d: refusals before the master must not reach it", m.creates) + } +} + +// A placement the master refuses leaves the target unplaced; the failure +// names the abort command. +func TestVolumeRestoreRefusedPlacementNamesTheAbort(t *testing.T) { + h, env, m, _ := restoreSetup(t) + m.failNext = "bind-refuse" + if code, _, errs := runRestore(env, restoreArgs(h)...); code != 2 || !strings.Contains(errs, "to undo it: "+abortCmd) { + t.Fatalf("refused placement: %d %s", code, errs) + } + if h.called("enable") != 0 { + t.Fatal("started after a refused placement") + } +} + +// --abort acts only on this restore's own target: a volume the master +// records for another source, snapshot or request, or a plain volume, is +// refused before anything changes (no systemctl, settings kept, no delete +// or release). +func TestVolumeRestoreAbortRefusesAForeignTarget(t *testing.T) { + derived := derivedID("restore", "vol-r", "vol-a", "s1") + for _, c := range []struct { + name string + rec restoreRec + want string + }{ + // A plain volume, or any target read from a blockmaster before + // v1.0.1 (no tuple reported): unknown, never a match. + {"no tuple (plain volume or v1.0.0 master)", restoreRec{ready: true}, "carries no restore tuple"}, + {"other source", restoreRec{source: "vol-b", snap: "s1", req: derived, ready: true}, "is not the target of this restore"}, + {"other snapshot", restoreRec{source: "vol-a", snap: "s2", req: derived, ready: true}, "is not the target of this restore"}, + {"other request", restoreRec{source: "vol-a", snap: "s1", req: "restore-someone-else", ready: true}, "is not the target of this restore"}, + } { + t.Run(c.name, func(t *testing.T) { + h, env, m, order := restoreSetup(t) + rec := c.rec + m.vols["vol-r"] = &rec + settings := filepath.Join(env.EtcDir, "vol-r.env") + if err := os.WriteFile(settings, []byte("# another volume's settings\n"), 0o640); err != nil { + t.Fatal(err) + } + h.mu.Lock() + h.unit = "active" + h.mu.Unlock() + code, _, errs := runRestore(env, "vol-a", "--snapshot", "s1", "--as", "vol-r", "--abort") + if code != 2 || !strings.Contains(errs, c.want) || !strings.Contains(errs, "nothing was changed") { + t.Fatalf("foreign target: %d %s", code, errs) + } + if n := len(h.calls); n != 0 { + t.Fatalf("systemctl called %d times: %v", n, h.calls) + } + if _, err := os.Stat(settings); err != nil { + t.Fatalf("settings removed: %v", err) + } + if len(*order) != 0 || m.vols["vol-r"].deleted || m.reserves != 0 { + t.Fatalf("deleted or released a foreign target: %v %+v", *order, rec) + } + }) + } +} + +// An abort interrupted before any of its steps is finished by running it +// again: the dependent goes, the settings go, and an interrupt before the +// verify changes nothing. +func TestVolumeRestoreAbortInterruptedAtEveryStepCompletes(t *testing.T) { + for _, step := range []string{"verify", "unit", "settings", "delete"} { + t.Run(step, func(t *testing.T) { + h, env, m, order := restoreSetup(t) + if code, _, errs := runRestore(env, restoreArgs(h)...); code != 0 { + t.Fatal(errs) + } + env.Step = func(name string) error { + if name == step { + return errors.New("interrupted") + } + return nil + } + code, _, errs := runRestore(env, "vol-a", "--snapshot", "s1", "--as", "vol-r", "--abort") + if code != 1 || !strings.Contains(errs, "run it again: "+abortCmd) { + t.Fatalf("interrupted abort: %d %s", code, errs) + } + if step == "verify" && (h.called("disable") != 0 || len(*order) != 0) { + t.Fatalf("an abort interrupted before its verify changed something: %v %v", h.calls, *order) + } + env.Step = nil + if code, out, errs := runRestore(env, "vol-a", "--snapshot", "s1", "--as", "vol-r", "--abort"); code != 0 { + t.Fatalf("abort re-run: %d %s %s", code, out, errs) + } + if deps := dependentsOf(t, m); len(deps) != 0 || !m.vols["vol-r"].deleted { + t.Fatalf("after the re-run: dependents %v, record %+v", deps, m.vols["vol-r"]) + } + if _, err := os.Stat(filepath.Join(env.EtcDir, "vol-r.env")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("settings left: %v", err) + } + }) + } +} + +// A restore whose target's authority line belongs to another replica, or +// lacks this server's binding, refuses at the placement and starts +// nothing; the refusal names the abort. +func TestVolumeRestorePlacementOfAnotherLineRefuses(t *testing.T) { + for _, c := range []struct { + name string + replica string + binding *control.WorkspaceBinding + want string + }{ + {"another replica", "r1", &control.WorkspaceBinding{VolumeId: "vol-r", ServerId: "s7", DataAddr: "10.0.0.7:9301", CtrlAddr: "10.0.0.7:9302"}, `authority line is replica "r1"`}, + {"another binding", "r9", &control.WorkspaceBinding{VolumeId: "vol-r", ServerId: "s8", DataAddr: "10.0.0.8:9301", CtrlAddr: "10.0.0.8:9302"}, "no live binding for server s7"}, + } { + t.Run(c.name, func(t *testing.T) { + h, env, m, _ := restoreSetup(t) + m.mu.Lock() + m.placed["vol-r"], m.bound["vol-r"], m.published["vol-r"] = c.replica, c.binding, true + m.mu.Unlock() + code, _, errs := runRestore(env, restoreArgs(h)...) + if code != 2 || !strings.Contains(errs, c.want) || !strings.Contains(errs, "to undo it: "+abortCmd) { + t.Fatalf("%s: %d %s", c.name, code, errs) + } + if h.called("enable") != 0 || m.places != 0 { + t.Fatalf("placed or started over another line: places %d", m.places) + } + }) + } +} + +// The line published between the placement read and the placement: the +// master refuses the placement as already assigned; this exact placement +// counts as done and the restore starts, another replica's refuses. +func TestVolumeRestorePublicationDuringThePlacement(t *testing.T) { + h, env, m, _ := restoreSetup(t) + m.failNext = "publish-race" + code, out, errs := runRestore(env, restoreArgs(h)...) + if code != 0 || !strings.Contains(out, "published while placing") || h.called("enable") == 0 { + t.Fatalf("own publication during the placement: %d %s %s", code, out, errs) + } + h2, env2, m2, _ := restoreSetup(t) + m2.failNext = "publish-race-other" + code, _, errs = runRestore(env2, restoreArgs(h2)...) + if code != 2 || !strings.Contains(errs, `authority line is replica "r1"`) || h2.called("enable") != 0 { + t.Fatalf("another replica's publication during the placement: %d %s", code, errs) + } + // The re-read after the refusal fails: the outcome is unknown (the line + // may be published), never "not placed"; the same command then converges. + h3, env3, m3, _ := restoreSetup(t) + m3.failNext = "publish-race-reread-fails" + code, _, errs = runRestore(env3, restoreArgs(h3)...) + if code != 1 || !strings.Contains(errs, "outcome is unknown") || strings.Contains(errs, "not placed") || !strings.Contains(errs, "to finish, run the same command") { + t.Fatalf("failed re-read: %d %s", code, errs) + } + if code, _, errs := runRestore(env3, restoreArgs(h3)...); code != 0 { + t.Fatalf("re-run after the failed re-read: %d %s", code, errs) + } +} + +// --abort leaves another installation of the same name on this host alone: +// settings naming another master or layout, or a running unit with no +// settings, refuse before any change (no systemctl, settings kept, no +// delete or release), even though the master's record is this restore's. +func TestVolumeRestoreAbortRefusesAnotherLocalInstallation(t *testing.T) { + for _, c := range []struct { + name string + settings func(master, layoutID string) string // "" = no settings file + unit string + want string + }{ + {"another master", func(_, id string) string { + return "SWB_VOLUME_ID=vol-r\nSWB_MASTER_ADDR=10.9.9.9:9180\nSWB_VOLUME_EXTRA_ARGS=\"--layout-id " + id + "\"\n" + }, "active", "is another installation"}, + {"another layout", func(master, _ string) string { + return "SWB_VOLUME_ID=vol-r\nSWB_MASTER_ADDR=" + master + "\nSWB_VOLUME_EXTRA_ARGS=\"--layout-id ffffffffffffffffffffffffffffffff\"\n" + }, "active", "is another installation"}, + // The unit passes the extra arguments after its own flags: a second + // layout id, or a --master there, overrides the nominal settings. + {"layout id followed by another", func(master, id string) string { + return "SWB_VOLUME_ID=vol-r\nSWB_MASTER_ADDR=" + master + "\nSWB_VOLUME_EXTRA_ARGS=\"--layout-id " + id + " --layout-id ffffffffffffffffffffffffffffffff\"\n" + }, "active", "is another installation"}, + {"master override in the extra arguments", func(master, id string) string { + return "SWB_VOLUME_ID=vol-r\nSWB_MASTER_ADDR=" + master + "\nSWB_VOLUME_EXTRA_ARGS=\"--layout-id " + id + " --master 10.9.9.9:9180\"\n" + }, "active", "is another installation"}, + {"running unit, no settings", nil, "active", "has no settings, so it cannot be confirmed"}, + } { + t.Run(c.name, func(t *testing.T) { + h, env, m, order := restoreSetup(t) + if code, _, errs := runRestore(env, restoreArgs(h)...); code != 0 { + t.Fatal(errs) + } + src, _ := readEnvFile(filepath.Join(env.EtcDir, "vol-a.env")) + settings := filepath.Join(env.EtcDir, "vol-r.env") + if c.settings == nil { + _ = os.Remove(settings) + } else if err := os.WriteFile(settings, []byte(c.settings(src["SWB_MASTER_ADDR"], m.ids["vol-r"].String())), 0o640); err != nil { + t.Fatal(err) + } + h.mu.Lock() + h.unit, h.calls = c.unit, nil + h.mu.Unlock() + code, _, errs := runRestore(env, "vol-a", "--snapshot", "s1", "--as", "vol-r", "--abort") + if code != 2 || !strings.Contains(errs, c.want) || !strings.Contains(errs, "nothing was changed") { + t.Fatalf("%s: %d %s", c.name, code, errs) + } + if h.called("disable") != 0 || h.called("stop") != 0 || len(*order) != 0 || m.reserves != 0 { + t.Fatalf("changed another installation: systemctl %v, chunk steps %v", h.calls, *order) + } + if c.settings != nil { + if _, err := os.Stat(settings); err != nil { + t.Fatalf("removed another installation's settings: %v", err) + } + } + }) + } +} + +// A restore answer without a valid layout id is an unknown outcome: +// nothing is placed or started, and the message names both commands. +func TestVolumeRestoreRefusesAMalformedLayoutAnswer(t *testing.T) { + h, env, m, _ := restoreSetup(t) + m.failNext = "create-badlayout" + code, _, errs := runRestore(env, restoreArgs(h)...) + if code != 1 || !strings.Contains(errs, "no valid layout id") || !strings.Contains(errs, "to undo it: "+abortCmd) { + t.Fatalf("malformed layout answer: %d %s", code, errs) + } + if m.binds != 0 || h.called("enable") != 0 { + t.Fatalf("placed or started on a malformed layout id (binds %d)", m.binds) + } +} + +// An abort for a target the master never recorded (the restore was refused +// before it wrote anything) has nothing to delete. +func TestVolumeRestoreAbortOfANeverCreatedTarget(t *testing.T) { + _, env, _, order := restoreSetup(t) + code, out, errs := runRestore(env, "vol-a", "--snapshot", "s1", "--as", "vol-r", "--abort") + if code != 0 || !strings.Contains(out, "nothing to undo") || len(*order) != 0 { + t.Fatalf("abort of nothing: %d %s %s %v", code, out, errs, *order) + } +} diff --git a/seaweed-block/cmd/sw-block/volume_create.go b/seaweed-block/cmd/sw-block/volume_create.go new file mode 100644 index 0000000000..8817e287c6 --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_create.go @@ -0,0 +1,115 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "io" + "regexp" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// S1 composes existing receiver admissions. It does not issue a lease or +// decide whether the target is serving, and never rolls back a partial result. +func runOpsVolumeCreate(args []string, stdout, stderr io.Writer) int { + const usage = "usage: sw-block ops volume create --master ADDR --size-bytes N --server-id HOST --replica-id REPLICA --data-addr HOST:PORT --ctrl-addr HOST:PORT [--protocol iscsi|nvme] [--transport tcp|rdma] [--timeout 10s] NAME" + fs := flag.NewFlagSet("sw-block ops volume create", flag.ContinueOnError) + fs.SetOutput(stderr) + fs.Usage = func() { fmt.Fprintln(stderr, usage) } + master := fs.String("master", "", "master gRPC address") + size := fs.Uint64("size-bytes", 0, "volume size in bytes (multiple of 4096)") + protocol := fs.String("protocol", "nvme", "nvme (default) or iscsi") + transport := fs.String("transport", "", "NVMe transport: tcp (default) or rdma") + server := fs.String("server-id", "", "already registered host") + replica := fs.String("replica-id", "", "replica identity") + data := fs.String("data-addr", "", "per-volume data endpoint") + ctrl := fs.String("ctrl-addr", "", "per-volume control endpoint") + timeout := fs.Duration("timeout", 10*time.Second, "deadline for the entire operation") + if err := fs.Parse(args); err != nil { + return 2 + } + if *protocol == "nvme" && *transport == "" { + *transport = "tcp" + } + validID := regexp.MustCompile(`^[A-Za-z0-9._-]+$`) + binding := &control.WorkspaceBinding{VolumeId: fs.Arg(0), ServerId: *server, DataAddr: *data, CtrlAddr: *ctrl} + geometry := layout.Geometry{SizeBytes: *size, BlockSize: 4096, ChunkBytes: 4 << 20} + if fs.NArg() != 1 || *master == "" || *timeout <= 0 || !validID.MatchString(fs.Arg(0)) || !validID.MatchString(*server) || !validID.MatchString(*replica) || geometry.Check() != nil || + !(*protocol == "iscsi" && *transport == "" || *protocol == "nvme" && (*transport == "tcp" || *transport == "rdma")) { + fs.Usage() + return 2 + } + if err := lifecycle.ValidateWorkspaceEndpoints(lifecycle.WorkspaceBinding{VolumeID: binding.VolumeId, ServerID: *server, DataAddr: *data, CtrlAddr: *ctrl}); err != nil { + fmt.Fprintf(stderr, "sw-block ops volume create: %v\n", err) + return 2 + } + conn, err := link.DialMasterFromEnv(*master) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops volume create: connection configuration: %v\n", err) + return 2 + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + fail := func(step string, err error) int { + code, outcome := 78, "refused" + switch status.Code(err) { + case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled, codes.Unknown, codes.Internal, codes.DataLoss: + code, outcome = 75, "unknown" + } + fmt.Fprintf(stderr, "sw-block ops volume create: %s %s: %v; earlier steps may remain recorded; retry the identical name, geometry and placement\n", step, outcome, err) + return code + } + q := &control.CreateVolumeRequest{VolumeId: binding.VolumeId, SizeBytes: *size, ReplicationFactor: 1, Protocol: *protocol, FrontendTransport: *transport, BlockSize: geometry.BlockSize, ChunkBytes: geometry.ChunkBytes} + v, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, q) + if err != nil { + return fail("create", err) + } + if _, err := layout.ParseVolumeID(v.GetLayoutId()); err != nil || v.GetVolumeId() != q.VolumeId || v.GetSizeBytes() != q.SizeBytes || v.GetReplicationFactor() != 1 || v.GetProtocol() != q.Protocol || v.GetFrontendTransport() != q.FrontendTransport || v.GetBlockSize() != q.BlockSize || v.GetChunkBytes() != q.ChunkBytes { + return fail("create reply", status.Error(codes.FailedPrecondition, "identity or geometry does not match; no binding or placement attempted")) + } + if !v.GetStoreReady() { + fmt.Fprintln(stderr, "sw-block ops volume create: created, store not ready; no binding or placement attempted; retry the identical name, geometry and placement") + return 75 + } + if step, err := bindAndPlace(ctx, control.NewWorkspaceServiceClient(conn), binding, *replica); err != nil { + return fail(step, err) + } + if err := json.NewEncoder(stdout).Encode(struct { + Status string `json:"status"` + Volume string `json:"volume"` + LayoutID string `json:"layout_id"` + ServerID string `json:"server_id"` + ReplicaID string `json:"replica_id"` + }{"placement_recorded", q.VolumeId, v.LayoutId, *server, *replica}); err != nil { + fmt.Fprintf(stderr, "sw-block ops volume create: placement recorded, output failed: %v\n", err) + return 75 + } + return 0 +} + +// bindAndPlace records a created volume's workspace binding and its +// placement on the binding's server, the two workspace calls ops volume +// create and volume restore both run. A binding answer that differs from +// the request stops before the placement. step names the failed call. +func bindAndPlace(ctx context.Context, ws control.WorkspaceServiceClient, binding *control.WorkspaceBinding, replica string) (step string, err error) { + b, err := ws.RegisterWorkspaceBinding(ctx, binding) + if err != nil { + return "binding", err + } + if b.GetVolumeId() != binding.VolumeId || b.GetServerId() != binding.ServerId || b.GetDataAddr() != binding.DataAddr || b.GetCtrlAddr() != binding.CtrlAddr || b.GetRetired() { + return "binding reply", status.Error(codes.FailedPrecondition, "binding does not match; no placement attempted") + } + if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: binding.VolumeId, ServerId: binding.ServerId, ReplicaId: replica}); err != nil { + return "placement", err + } + return "", nil +} diff --git a/seaweed-block/cmd/sw-block/volume_create_test.go b/seaweed-block/cmd/sw-block/volume_create_test.go new file mode 100644 index 0000000000..13f8599eaa --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_create_test.go @@ -0,0 +1,371 @@ +package main + +import ( + "bytes" + "context" + "fmt" + "net" + "reflect" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/host/master" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// The S1 command's public seam: a running master's existing lifecycle and +// workspace RPCs. This receiver checks the operator's intent, not private CLI +// functions. No test-only command implementation stands in for the command. +type createAndPlaceReceiver struct { + control.UnimplementedLifecycleServiceServer + control.UnimplementedWorkspaceServiceServer + mu sync.Mutex + calls []string + failStep string + failErr error + createReply func(*control.CreateVolumeResponse) + bindReply func(*control.WorkspaceBinding) + consumeBudget bool + createDeadline time.Time + deadlineMismatch atomic.Bool +} + +func (s *createAndPlaceReceiver) CreateVolume(ctx context.Context, q *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + if q.GetVolumeId() != "new-volume" || q.GetSizeBytes() != 268435456 || q.GetReplicationFactor() != 1 || q.GetProtocol() != "nvme" || q.GetFrontendTransport() != "tcp" || q.GetSourceVolume() != "" || q.GetSourceSnapshot() != "" || q.GetCreateRequestId() != "" { + return nil, status.Error(codes.InvalidArgument, "wrong ordinary RF1 create intent") + } + s.calls = append(s.calls, "create") + if s.failStep == "create" { + return nil, s.failErr + } + v := &control.CreateVolumeResponse{VolumeId: q.VolumeId, SizeBytes: q.SizeBytes, ReplicationFactor: 1, Protocol: "nvme", FrontendTransport: "tcp", LayoutId: "1234567890abcdef1234567890abcdef", BlockSize: 4096, ChunkBytes: 4194304, StoreReady: true} + if s.createReply != nil { + s.createReply(v) + } + if s.consumeBudget { + deadline, ok := ctx.Deadline() + if !ok { + return nil, status.Error(codes.FailedPrecondition, "missing create deadline") + } + s.createDeadline = deadline + timer := time.NewTimer(time.Until(deadline) - 100*time.Millisecond) + defer timer.Stop() + select { + case <-timer.C: + case <-ctx.Done(): + return nil, status.FromContextError(ctx.Err()).Err() + } + } + return v, nil +} + +func (s *createAndPlaceReceiver) RegisterWorkspaceBinding(ctx context.Context, q *control.WorkspaceBinding) (*control.WorkspaceBinding, error) { + s.mu.Lock() + defer s.mu.Unlock() + if !reflect.DeepEqual(s.calls, []string{"create"}) || q.GetVolumeId() != "new-volume" || q.GetServerId() != "registered-host" || q.GetDataAddr() != "192.0.2.10:9201" || q.GetCtrlAddr() != "192.0.2.10:9202" || q.GetRetired() { + return nil, status.Error(codes.FailedPrecondition, "binding must follow store-ready create with exact endpoints") + } + s.calls = append(s.calls, "bind") + if s.failStep == "bind" { + return nil, s.failErr + } + if s.bindReply != nil { + s.bindReply(q) + } + if s.consumeBudget { + deadline, ok := ctx.Deadline() + if !ok || deadline.Sub(s.createDeadline).Abs() > 25*time.Millisecond { + s.deadlineMismatch.Store(true) + return nil, status.Error(codes.FailedPrecondition, "whole-operation deadline reset") + } + <-ctx.Done() + return nil, status.FromContextError(ctx.Err()).Err() + } + return q, nil +} + +func (s *createAndPlaceReceiver) PlaceWorkspace(_ context.Context, q *control.WorkspacePlacement) (*control.WorkspaceEmpty, error) { + s.mu.Lock() + defer s.mu.Unlock() + if !reflect.DeepEqual(s.calls, []string{"create", "bind"}) || q.GetVolumeId() != "new-volume" || q.GetServerId() != "registered-host" || q.GetReplicaId() != "r1" { + return nil, status.Error(codes.FailedPrecondition, "placement must follow the exact prepared binding") + } + s.calls = append(s.calls, "place") + if s.failStep == "place" { + return nil, s.failErr + } + return &control.WorkspaceEmpty{}, nil +} + +func serveCreateAndPlace(t *testing.T, s *createAndPlaceReceiver) string { + t.Helper() + for _, key := range []string{"SW_BLOCK_TLS_CERT", "SW_BLOCK_TLS_KEY", "SW_BLOCK_TLS_CA"} { + t.Setenv(key, "") + } + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + control.RegisterLifecycleServiceServer(server, s) + control.RegisterWorkspaceServiceServer(server, s) + go func() { _ = server.Serve(lis) }() + t.Cleanup(server.Stop) + return lis.Addr().String() +} + +func createAndPlaceArgs(master string) []string { + return []string{"ops", "volume", "create", "--master", master, "--size-bytes", "268435456", "--protocol", "nvme", "--transport", "tcp", "--server-id", "registered-host", "--replica-id", "r1", "--data-addr", "192.0.2.10:9201", "--ctrl-addr", "192.0.2.10:9202", "--timeout", "5s", "new-volume"} +} + +func TestOpsVolumeCreateAndPlaceWithoutMasterRestart(t *testing.T) { + s := &createAndPlaceReceiver{} + addr := serveCreateAndPlace(t, s) + var out, errout bytes.Buffer + code := run(createAndPlaceArgs(addr), &out, &errout) + if code != 0 { + t.Fatalf("online create-and-place: exit=%d stdout=%q stderr=%q", code, &out, &errout) + } + if !strings.Contains(out.String(), `"status":"placement_recorded"`) || strings.Contains(out.String(), `"serving"`) { + t.Fatalf("success must describe placement only: %s", &out) + } + s.mu.Lock() + defer s.mu.Unlock() + if !reflect.DeepEqual(s.calls, []string{"create", "bind", "place"}) { + t.Fatalf("master RPCs=%v; want one create, binding, placement on the running master", s.calls) + } +} + +func TestOpsVolumeCreateDefaultsToSupportedNVMeTCP(t *testing.T) { + s := &createAndPlaceReceiver{} + all := createAndPlaceArgs(serveCreateAndPlace(t, s)) + var args []string + for i := 0; i < len(all); i++ { + if all[i] == "--protocol" || all[i] == "--transport" { + i++ + continue + } + args = append(args, all[i]) + } + var out, errout bytes.Buffer + if code := run(args, &out, &errout); code != 0 { + t.Fatalf("default must create supported nvme/tcp: exit=%d out=%q err=%q", code, &out, &errout) + } +} + +func TestOpsVolumeCreateUsesOneDeadlineAcrossSteps(t *testing.T) { + s := &createAndPlaceReceiver{consumeBudget: true} + args := createAndPlaceArgs(serveCreateAndPlace(t, s)) + for i := range args { + if args[i] == "--timeout" { + args[i+1] = "1s" + } + } + var out, errout bytes.Buffer + if code := run(args, &out, &errout); code != 75 || out.Len() != 0 || s.deadlineMismatch.Load() { + t.Fatalf("whole-operation budget: code=%d out=%q err=%q reset=%v", code, &out, &errout, s.deadlineMismatch.Load()) + } + s.mu.Lock() + defer s.mu.Unlock() + if !reflect.DeepEqual(s.calls, []string{"create", "bind"}) { + t.Fatalf("expired command reached another step: %v", s.calls) + } +} + +func TestOpsVolumeCreateStopsAfterRefusedOrUnknownStep(t *testing.T) { + for i, step := range []string{"create", "bind", "place"} { + for _, tc := range []struct { + code codes.Code + exit int + outcome string + }{ + {codes.FailedPrecondition, 78, "refused"}, {codes.Unavailable, 75, "unknown"}, {codes.DeadlineExceeded, 75, "unknown"}, + } { + t.Run(step+"/"+tc.code.String(), func(t *testing.T) { + s := &createAndPlaceReceiver{failStep: step, failErr: status.Error(tc.code, "injected")} + addr := serveCreateAndPlace(t, s) + var out, errout bytes.Buffer + code := run(createAndPlaceArgs(addr), &out, &errout) + if code != tc.exit || out.Len() != 0 || !strings.Contains(errout.String(), tc.outcome) { + t.Fatalf("code=%d out=%q err=%q", code, &out, &errout) + } + s.mu.Lock() + defer s.mu.Unlock() + if !reflect.DeepEqual(s.calls, []string{"create", "bind", "place"}[:i+1]) { + t.Fatalf("continued after %s: %v", step, s.calls) + } + }) + } + } +} + +func TestOpsVolumeCreateRefusesUnreadyOrMismatchedAnswers(t *testing.T) { + for _, tc := range []struct { + name string + create func(*control.CreateVolumeResponse) + bind func(*control.WorkspaceBinding) + exit int + calls []string + }{ + {"not-ready", func(v *control.CreateVolumeResponse) { v.StoreReady = false }, nil, 75, []string{"create"}}, + {"foreign-volume", func(v *control.CreateVolumeResponse) { v.VolumeId = "other" }, nil, 78, []string{"create"}}, + {"invalid-layout", func(v *control.CreateVolumeResponse) { v.LayoutId = "bad" }, nil, 78, []string{"create"}}, + {"geometry", func(v *control.CreateVolumeResponse) { v.SizeBytes = 4096 }, nil, 78, []string{"create"}}, + {"replicated", func(v *control.CreateVolumeResponse) { v.ReplicationFactor = 3 }, nil, 78, []string{"create"}}, + {"foreign-binding", nil, func(v *control.WorkspaceBinding) { v.ServerId = "other" }, 78, []string{"create", "bind"}}, + {"retired-binding", nil, func(v *control.WorkspaceBinding) { v.Retired = true }, 78, []string{"create", "bind"}}, + } { + t.Run(tc.name, func(t *testing.T) { + s := &createAndPlaceReceiver{createReply: tc.create, bindReply: tc.bind} + addr := serveCreateAndPlace(t, s) + var out, errout bytes.Buffer + code := run(createAndPlaceArgs(addr), &out, &errout) + if code != tc.exit || out.Len() != 0 { + t.Fatalf("code=%d out=%q err=%q", code, &out, &errout) + } + s.mu.Lock() + defer s.mu.Unlock() + if !reflect.DeepEqual(s.calls, tc.calls) { + t.Fatalf("continued after bad answer: %v", s.calls) + } + }) + } +} + +func TestOpsVolumeCreateValidatesBeforeAnyRPC(t *testing.T) { + for _, tc := range []struct{ flag, value string }{ + {"--size-bytes", "0"}, {"--size-bytes", "4097"}, {"--protocol", "other"}, {"--transport", "other"}, + {"--server-id", ""}, {"--replica-id", ""}, {"--data-addr", "bad"}, {"--ctrl-addr", "192.0.2.10:9201"}, {"--timeout", "0s"}, + } { + t.Run(tc.flag+tc.value, func(t *testing.T) { + s := &createAndPlaceReceiver{} + args := createAndPlaceArgs(serveCreateAndPlace(t, s)) + for i := range args { + if args[i] == tc.flag { + args[i+1] = tc.value + break + } + } + var out, errout bytes.Buffer + if code := run(args, &out, &errout); code != 2 || out.Len() != 0 { + t.Fatalf("code=%d out=%q err=%q", code, &out, &errout) + } + s.mu.Lock() + defer s.mu.Unlock() + if len(s.calls) != 0 { + t.Fatalf("invalid arguments wrote remote state: %v", s.calls) + } + }) + } +} + +func TestOpsVolumeCreateAndPlaceRetriesAgainstRunningMaster(t *testing.T) { + for _, lostReply := range []string{control.LifecycleService_CreateVolume_FullMethodName, control.WorkspaceService_RegisterWorkspaceBinding_FullMethodName, control.WorkspaceService_PlaceWorkspace_FullMethodName} { + t.Run(lostReply, func(t *testing.T) { testCreateAndPlaceLostReply(t, lostReply) }) + } +} + +func testCreateAndPlaceLostReply(t *testing.T, lostReply string) { + t.Helper() + for _, key := range []string{"SW_BLOCK_TLS_CERT", "SW_BLOCK_TLS_KEY", "SW_BLOCK_TLS_CA"} { + t.Setenv(key, "") + } + var dropped atomic.Bool + var bindingCalls, placementCalls atomic.Int32 + // Lose the answer AFTER the real receiver commits. The client must stop, + // then an identical invocation must settle by the receiver's idempotence. + loseAnswer := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + if info.FullMethod == control.WorkspaceService_RegisterWorkspaceBinding_FullMethodName { + bindingCalls.Add(1) + } + if info.FullMethod == control.WorkspaceService_PlaceWorkspace_FullMethodName { + placementCalls.Add(1) + } + reply, err := handler(ctx, req) + if err == nil && info.FullMethod == lostReply && dropped.CompareAndSwap(false, true) { + return nil, status.Error(codes.Unavailable, "answer lost after commit") + } + return reply, err + } + h, stop := startDeleteMaster(t, master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + LifecycleProductLoop: true, + ServerOptions: []grpc.ServerOption{grpc.ChainUnaryInterceptor(loseAnswer)}, + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{}, fmt.Errorf("create-and-place must not inspect a holder HEAD") + }, + }) + defer stop() + if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "registered-host", DataAddr: "192.0.2.10:9201", CtrlAddr: "192.0.2.10:9202"}); err != nil { + t.Fatal(err) + } + args := createAndPlaceArgs(h.Addr()) + var interrupted, diagnostics bytes.Buffer + if code := run(args, &interrupted, &diagnostics); code != 75 || interrupted.Len() != 0 || !dropped.Load() { + t.Fatalf("lost answer: code=%d out=%q err=%q", code, &interrupted, &diagnostics) + } + if lostReply == control.LifecycleService_CreateVolume_FullMethodName && bindingCalls.Load() != 0 || lostReply != control.WorkspaceService_PlaceWorkspace_FullMethodName && placementCalls.Load() != 0 { + t.Fatal("continued after unknown outcome") + } + before, err := lifecycleClient(t, h.Addr()).GetVolume(context.Background(), &control.GetLifecycleVolumeRequest{VolumeId: "new-volume"}) + if err != nil || !before.GetStoreReady() { + t.Fatalf("create was not committed before lost answer: %v %v", before, err) + } + var first string + for i := 0; i < 2; i++ { + var out, errout bytes.Buffer + if code := run(args, &out, &errout); code != 0 { + t.Fatalf("attempt %d: exit=%d out=%q err=%q", i, code, &out, &errout) + } + if i == 0 { + first = out.String() + } else if out.String() != first { + t.Fatalf("retry changed result: %s -> %s", first, &out) + } + } + v, err := lifecycleClient(t, h.Addr()).GetVolume(context.Background(), &control.GetLifecycleVolumeRequest{VolumeId: "new-volume"}) + if err != nil || !v.GetStoreReady() || v.GetSizeBytes() != 268435456 || v.GetReplicationFactor() != 1 || v.GetLayoutId() != before.GetLayoutId() { + t.Fatalf("master volume=%v err=%v", v, err) + } + // Changing the desired placement cannot overwrite the recorded placement. + for i := range args { + if args[i] == "--replica-id" { + args[i+1] = "r2" + } + } + var out, errout bytes.Buffer + if code := run(args, &out, &errout); code != 78 || out.Len() != 0 { + t.Fatalf("conflicting placement: code=%d out=%q err=%q", code, &out, &errout) + } + p, ok := h.Lifecycle().Placements.GetPlacementSnapshot("new-volume") + if !ok || len(p.Slots) != 1 || p.Slots[0].ServerID != "registered-host" || p.Slots[0].ReplicaID != "r1" || p.Slots[0].DataAddr != "192.0.2.10:9201" || p.Slots[0].CtrlAddr != "192.0.2.10:9202" { + t.Fatalf("refused conflict changed original placement: %+v", p) + } + args[len(args)-1] = "too-large" + for i := range args { + if args[i] == "--size-bytes" { + args[i+1] = "1099511631872" // 1 TiB + 4 KiB + } + } + beforeBindings := bindingCalls.Load() + out.Reset() + errout.Reset() + if code := run(args, &out, &errout); code != 78 || !strings.Contains(errout.String(), "exceeds the maximum of 1099511627776 bytes") || out.Len() != 0 { + t.Fatalf("size refusal: code=%d out=%q err=%q", code, &out, &errout) + } + if bindingCalls.Load() != beforeBindings { + t.Fatal("oversized create reached binding") + } + if _, err := lifecycleClient(t, h.Addr()).GetVolume(context.Background(), &control.GetLifecycleVolumeRequest{VolumeId: "too-large"}); status.Code(err) != codes.NotFound { + t.Fatalf("oversized create left a record: %v", err) + } +} diff --git a/seaweed-block/cmd/sw-block/volume_resolve.go b/seaweed-block/cmd/sw-block/volume_resolve.go new file mode 100644 index 0000000000..5f167824f5 --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_resolve.go @@ -0,0 +1,54 @@ +package main + +import ( + "context" + "flag" + "fmt" + "io" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// runOpsVolume exposes the same master name binding used by ops chunk. +func runOpsVolume(args []string, stdout, stderr io.Writer) int { + if len(args) > 0 && args[0] == "create" { + return runOpsVolumeCreate(args[1:], stdout, stderr) + } + const usage = "usage: sw-block ops volume resolve --master [--timeout 10s] " + if len(args) == 0 || args[0] != "resolve" { + fmt.Fprintln(stderr, usage) + return ops.VolumeStatusExitInvalid + } + fs := flag.NewFlagSet("sw-block ops volume resolve", flag.ContinueOnError) + fs.SetOutput(stderr) + fs.Usage = func() { fmt.Fprintln(stderr, usage) } + master := fs.String("master", "", "master gRPC address") + timeout := fs.Duration("timeout", 10*time.Second, "master query timeout") + if err := fs.Parse(args[1:]); err != nil { + return ops.VolumeStatusExitInvalid + } + if *master == "" || *timeout <= 0 || fs.NArg() != 1 || fs.Arg(0) == "" { + fmt.Fprintln(stderr, usage) + return ops.VolumeStatusExitInvalid + } + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + id, err := resolveVolumeID(ctx, *master, fs.Arg(0)) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops volume resolve: %v\n", err) + // Match blockvolume: an unavailable or unknown master answer is retryable; + // a definite refusal or invalid local configuration needs correction. + if s, ok := status.FromError(err); ok { + switch s.Code() { + case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled, codes.Unknown, codes.Internal: + return 75 + } + } + return 78 + } + fmt.Fprintln(stdout, id.String()) + return ops.VolumeStatusExitOK +} diff --git a/seaweed-block/cmd/sw-block/volume_resolve_test.go b/seaweed-block/cmd/sw-block/volume_resolve_test.go new file mode 100644 index 0000000000..b09730564e --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_resolve_test.go @@ -0,0 +1,96 @@ +package main + +import ( + "bytes" + "context" + "net" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type volumeResolveServer struct { + control.UnimplementedLifecycleServiceServer + mu sync.Mutex + reply *control.CreateVolumeResponse + err error + names []string +} + +func (s *volumeResolveServer) GetVolume(_ context.Context, q *control.GetLifecycleVolumeRequest) (*control.CreateVolumeResponse, error) { + s.mu.Lock() + s.names = append(s.names, q.GetVolumeId()) + s.mu.Unlock() + return s.reply, s.err +} +func serveVolumeResolver(t *testing.T, s *volumeResolveServer) string { + t.Helper() + for _, key := range []string{"SW_BLOCK_TLS_CERT", "SW_BLOCK_TLS_KEY", "SW_BLOCK_TLS_CA"} { + t.Setenv(key, "") + } + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + control.RegisterLifecycleServiceServer(server, s) + go func() { _ = server.Serve(lis) }() + t.Cleanup(server.Stop) + return lis.Addr().String() +} +func TestOpsVolumeResolvePrintsOnlyMasterLayoutID(t *testing.T) { + const id = "1234567890abcdef1234567890abcdef" + s := &volumeResolveServer{reply: &control.CreateVolumeResponse{VolumeId: "v1", LayoutId: id}} + addr := serveVolumeResolver(t, s) + var out, errout bytes.Buffer + code := run([]string{"ops", "volume", "resolve", "--master", addr, "v1"}, &out, &errout) + if code != 0 || out.String() != id+"\n" || errout.Len() != 0 { + t.Fatalf("code=%d stdout=%q stderr=%q", code, &out, &errout) + } + s.mu.Lock() + defer s.mu.Unlock() + if len(s.names) != 1 || s.names[0] != "v1" { + t.Fatalf("resolved names=%v", s.names) + } +} + +func TestOpsVolumeResolveRefusesMissingOrForeignIdentity(t *testing.T) { + for _, tc := range []struct { + name, volume, id string + err error + exit int + }{ + {"missing", "", "", status.Error(codes.NotFound, "no such volume"), 78}, + {"unavailable", "", "", status.Error(codes.Unavailable, "master unavailable"), 75}, + {"deadline", "", "", status.Error(codes.DeadlineExceeded, "query timed out"), 75}, + {"invalid-id", "v1", "bad", nil, 78}, + {"wrong-name", "v2", "1234567890abcdef1234567890abcdef", nil, 78}, + } { + t.Run(tc.name, func(t *testing.T) { + s := &volumeResolveServer{reply: &control.CreateVolumeResponse{VolumeId: tc.volume, LayoutId: tc.id}, err: tc.err} + addr := serveVolumeResolver(t, s) + var out, errout bytes.Buffer + code := run([]string{"ops", "volume", "resolve", "--master", addr, "v1"}, &out, &errout) + if code != tc.exit || out.Len() != 0 || errout.Len() == 0 { + t.Fatalf("code=%d stdout=%q stderr=%q", code, &out, &errout) + } + }) + } +} +func TestOpsVolumeResolveRequiresOneNameAndBoundedQuery(t *testing.T) { + for _, args := range [][]string{ + {}, {"other"}, {"resolve", "v1"}, {"resolve", "--master", "unused"}, + {"resolve", "--master", "unused", "v1", "v2"}, + {"resolve", "--master", "unused", "--timeout", "0s", "v1"}, + } { + var out, errout bytes.Buffer + code := run(append([]string{"ops", "volume"}, args...), &out, &errout) + if code != 2 || out.Len() != 0 || errout.Len() == 0 { + t.Fatalf("args=%v code=%d stdout=%q stderr=%q", args, code, &out, &errout) + } + } +} diff --git a/seaweed-block/cmd/sw-block/volume_spec.go b/seaweed-block/cmd/sw-block/volume_spec.go new file mode 100644 index 0000000000..567fbf5bf6 --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_spec.go @@ -0,0 +1,110 @@ +package main + +import ( + "fmt" + "sort" + "strconv" + "strings" +) + +// volumeSpec is one blockvolume's settings, the one source of both forms +// they take: the flags sw-block mini passes to its blockvolume child +// (args), and the settings file volume start writes for the +// sw-blockvolume@ unit (env), whose ExecStart passes each key to +// the same flag. A test renders env through the shipped unit and compares +// it with args, so the two cannot drift. +type volumeSpec struct { + Master, ServerID, VolumeID, ReplicaID string + DataAddr, CtrlAddr, StatusAddr string + DurableRoot string + Blocks uint64 + BlockSize int // 0: blockvolume's default (walstore) + Chunk bool + ChunkFiler, ChunkPath, LayoutID string // with Chunk + NVMeListen, NQN string + ISCSIListen, IQN string // optional (volume start) +} + +// args are the blockvolume flags, in the order mini has always passed them. +func (v volumeSpec) args() []string { + a := []string{"--master", v.Master, "--server-id", v.ServerID, "--volume-id", v.VolumeID, "--replica-id", v.ReplicaID, + "--data-addr", v.DataAddr, "--ctrl-addr", v.CtrlAddr, "--status-addr", v.StatusAddr, "--durable-root", v.DurableRoot} + blocks := strconv.FormatUint(v.Blocks, 10) + if !v.Chunk { + a = append(a, "--durable-impl", "walstore", "--durable-blocks", blocks) + } else { + a = append(a, "--durable-impl", "walstore-chunk", "--durable-blocks", blocks, "--durable-blocksize", strconv.Itoa(v.BlockSize), + "--chunk-filer", v.ChunkFiler, "--chunk-path", v.ChunkPath, "--chunk-control-endpoint", "--workspace-lease", "--layout-id", v.LayoutID) + } + a = append(a, "--nvme-listen", v.NVMeListen, "--nvme-subsysnqn", v.NQN) + if v.ISCSIListen != "" { + a = append(a, "--iscsi-listen", v.ISCSIListen, "--iscsi-iqn", v.IQN) + } + return a +} + +// blockvolumeEnvDefaults are deploy/config/blockvolume.env's values (a test +// keeps them equal): what the unit passes for a key the spec does not set. +var blockvolumeEnvDefaults = map[string]string{ + "SWB_MASTER_ADDR": "127.0.0.1:9180", "SWB_SERVER_ID": "s1", "SWB_VOLUME_ID": "v1", "SWB_REPLICA_ID": "r1", + "SWB_DATA_ADDR": "127.0.0.1:9201", "SWB_CTRL_ADDR": "127.0.0.1:9202", "SWB_STATUS_ADDR": "127.0.0.1:9203", + "SWB_HEARTBEAT_INTERVAL": "2s", "SWB_RECOVER_TIMEOUT": "30s", + "SWB_DURABLE_ROOT": "/var/lib/sw-block-volume/volumes", "SWB_DURABLE_IMPL": "walstore", + "SWB_DURABLE_BLOCKS": "65536", "SWB_DURABLE_BLOCKSIZE": "4096", + "SWB_NVME_LISTEN": "127.0.0.1:4420", "SWB_NVME_SUBSYSNQN": "nqn.2026-05.io.seaweedfs:v1", "SWB_NVME_NS": "1", + "SWB_NVME_MAX_H2C_DATA_LENGTH": "0", "SWB_UBLK_DEVICE": "-1", "SWB_UBLK_QUEUES": "0", "SWB_UBLK_QUEUE_DEPTH": "0", + "SWB_ISCSI_LISTEN": "", "SWB_ISCSI_IQN": "", "SWB_ISCSI_PORTAL_ADDR": "", "SWB_ISCSI_LUN": "0", "SWB_ISCSI_DATAOUT_TIMEOUT": "0", + "SWB_REPLICATION_ACK": "best-effort", "SWB_WAL_RETENTION_LSNS": "0", "SWB_RECOVERY_MODE": "legacy", + "SWB_DEGRADED_PROBE_INTERVAL": "0", "SWB_DEGRADED_PROBE_COOLDOWN_BASE": "5s", "SWB_DEGRADED_PROBE_COOLDOWN_CAP": "60s", + "SWB_CHUNK_FILER": "", "SWB_CHUNK_PATH": "/swblock/chunks", "SWB_CHUNK_COLLECTION": "", "SWB_CHUNK_REPLICATION": "", + "SWB_CHUNK_CAPTURE_INTERVAL": "0", "SWB_CHUNK_SNAPSHOT_SCHEDULE": "daily:7", "SWB_CHUNK_UPLOAD_CONCURRENCY": "8", + "SWB_CHUNK_CONTROL_ENDPOINT": "false", "SWB_WORKSPACE_LEASE": "false", "SWB_VOLUME_EXTRA_ARGS": "", +} + +// env is the unit's settings file for v: every key of the shipped +// defaults, with the spec's values over them. The layout id has no key of +// its own: it goes in SWB_VOLUME_EXTRA_ARGS. +func (v volumeSpec) env() map[string]string { + e := make(map[string]string, len(blockvolumeEnvDefaults)) + for k, val := range blockvolumeEnvDefaults { + e[k] = val + } + set := map[string]string{ + "SWB_MASTER_ADDR": v.Master, "SWB_SERVER_ID": v.ServerID, "SWB_VOLUME_ID": v.VolumeID, "SWB_REPLICA_ID": v.ReplicaID, + "SWB_DATA_ADDR": v.DataAddr, "SWB_CTRL_ADDR": v.CtrlAddr, "SWB_STATUS_ADDR": v.StatusAddr, + "SWB_DURABLE_ROOT": v.DurableRoot, "SWB_DURABLE_IMPL": "walstore", "SWB_DURABLE_BLOCKS": strconv.FormatUint(v.Blocks, 10), + "SWB_NVME_LISTEN": v.NVMeListen, "SWB_NVME_SUBSYSNQN": v.NQN, + "SWB_ISCSI_LISTEN": v.ISCSIListen, "SWB_ISCSI_IQN": v.IQN, + } + if v.Chunk { + set["SWB_DURABLE_IMPL"] = "walstore-chunk" + set["SWB_DURABLE_BLOCKSIZE"] = strconv.Itoa(v.BlockSize) + set["SWB_CHUNK_FILER"], set["SWB_CHUNK_PATH"] = v.ChunkFiler, v.ChunkPath + set["SWB_CHUNK_CONTROL_ENDPOINT"], set["SWB_WORKSPACE_LEASE"] = "true", "true" + set["SWB_VOLUME_EXTRA_ARGS"] = "--layout-id " + v.LayoutID + } + for k, val := range set { + e[k] = val + } + return e +} + +// renderEnv is a settings file: KEY=VALUE lines in key order, each value +// quoted for systemd's EnvironmentFile when it is not plain. +func renderEnv(header string, e map[string]string) string { + keys := make([]string, 0, len(e)) + for k := range e { + keys = append(keys, k) + } + sort.Strings(keys) + var b strings.Builder + b.WriteString(header) + for _, k := range keys { + val := e[k] + if strings.ContainsAny(val, " \t\"'\\$#") { + val = strconv.Quote(val) + } + fmt.Fprintf(&b, "%s=%s\n", k, val) + } + return b.String() +} diff --git a/seaweed-block/cmd/sw-block/volume_unheld.go b/seaweed-block/cmd/sw-block/volume_unheld.go new file mode 100644 index 0000000000..81d2c12d0e --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_unheld.go @@ -0,0 +1,54 @@ +package main + +import ( + "errors" + "flag" + "fmt" + "io" + + "github.com/seaweedfs/seaweed-block/core/ops" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const volumeUnheldUsage = `usage: sw-block ops volume-unheld --path + +Exit 0 only when no process on THIS host holds the v3 volume file's lock +(the lock every v3 owner holds while its store is open; the kernel releases +it when the owner process exits). Exit 1: held. Exit 2: unknown (missing +file, not a v3 volume, lock error) or bad usage. + +This proof is per host and for local filesystems only. It says nothing about +another host, and nothing on a network or shared mount. It does not prove the +owner process is dead: host cleanup must require BOTH this command's exit 0 +AND the host tooling's own check that the recorded owner process is gone. + +The probe holds the lock only for an instant and reserves nothing: it does not +keep a new owner out after it returns, and an owner opening the volume at that +instant is refused. Run it only when the owner is believed gone. +` + +// runOpsVolumeUnheld is `sw-block ops volume-unheld`. +func runOpsVolumeUnheld(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block ops volume-unheld", flag.ContinueOnError) + fs.SetOutput(stderr) + fs.Usage = func() { fmt.Fprint(stderr, volumeUnheldUsage) } + path := fs.String("path", "", "the volume file") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if *path == "" || fs.NArg() != 0 { + fmt.Fprint(stderr, volumeUnheldUsage) + return ops.VolumeStatusExitInvalid + } + switch err := storage.ProbeVolumeUnheld(*path); { + case err == nil: + fmt.Fprintf(stdout, "unheld: no process on this host holds %s (local proof only; also check the owner process is gone)\n", *path) + return ops.VolumeStatusExitOK + case errors.Is(err, storage.ErrVolumeHeld): + fmt.Fprintf(stdout, "held: a live process on this host holds %s\n", *path) + return ops.VolumeStatusExitUnhealthy + default: + fmt.Fprintf(stderr, "unknown: %v\n", err) + return ops.VolumeStatusExitInvalid + } +} diff --git a/seaweed-block/cmd/sw-block/volume_unheld_test.go b/seaweed-block/cmd/sw-block/volume_unheld_test.go new file mode 100644 index 0000000000..868f276778 --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_unheld_test.go @@ -0,0 +1,63 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// `sw-block ops volume-unheld` exits 0 only for an unheld v3 volume: 1 while +// a store holds it, 2 for unknown (missing, not v3) and bad usage. The +// usage states the per-host, local-only limit and the second check. +func TestOpsVolumeUnheldExitCodes(t *testing.T) { + path := filepath.Join(t.TempDir(), "v.bin") + s, err := storage.CreateWALStore(path, 64, 4096) + if err != nil { + t.Fatal(err) + } + closed := false + t.Cleanup(func() { + if !closed { + _ = s.Close() + } + }) + junk := filepath.Join(t.TempDir(), "junk.bin") + if err := os.WriteFile(junk, make([]byte, 64<<10), 0o644); err != nil { + t.Fatal(err) + } + runIt := func(args ...string) (int, string, string) { + var out, errOut bytes.Buffer + code := run(append([]string{"ops", "volume-unheld"}, args...), &out, &errOut) + return code, out.String(), errOut.String() + } + if code, out, _ := runIt("--path", path); code != 1 || !strings.HasPrefix(out, "held:") { + t.Fatalf("open store: exit %d %q; want 1 held", code, out) + } + closed = true + if err := s.Close(); err != nil { + t.Fatal(err) + } + if code, out, _ := runIt("--path", path); code != 0 || !strings.HasPrefix(out, "unheld:") { + t.Fatalf("closed store: exit %d %q; want 0 unheld", code, out) + } + for name, args := range map[string][]string{ + "missing": {"--path", filepath.Join(t.TempDir(), "missing.bin")}, + "not v3": {"--path", junk}, + "no path": nil, + "extra arg": {"--path", path, "x"}, + } { + if code, out, _ := runIt(args...); code != 2 || strings.HasPrefix(out, "unheld") { + t.Fatalf("%s: exit %d %q; want 2", name, code, out) + } + } + _, _, usage := runIt() + for _, want := range []string{"per host", "local filesystems only", "network or shared mount", "BOTH", "reserves nothing", "is refused"} { + if !strings.Contains(usage, want) { + t.Fatalf("usage lacks %q:\n%s", want, usage) + } + } +} diff --git a/seaweed-block/cmd/sw-block/volume_verbs.go b/seaweed-block/cmd/sw-block/volume_verbs.go new file mode 100644 index 0000000000..cebffb632c --- /dev/null +++ b/seaweed-block/cmd/sw-block/volume_verbs.go @@ -0,0 +1,582 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "os/signal" + "path/filepath" + "regexp" + "strconv" + "strings" + "syscall" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// The whole-job volume commands: each runs on the volume's host, prints +// every step before it runs it, and stops at the first step that answers +// otherwise than expected, saying how to go on. A volume is an instance of +// the sw-blockvolume@ unit; its settings file is the only state they keep. + +// The sentence volume stop ends with (and the help and the page say): what +// it promises, and only that. +const stopRecoveryPoint = "recovery point in the object store: the cut at %s; writes after it are on this host only" + +const volumeUsage = `usage: sudo sw-block volume start [flags] + sudo sw-block volume stop [--force] [--no-cut] [--timeout 2m] + sudo sw-block volume backup --name S + sudo sw-block volume restore --snapshot S --as [start flags for ] + sudo sw-block volume restore --snapshot S --as --abort + +start: an existing volume (in the cluster spec) as the systemd unit +sw-blockvolume@: writes /etc/sw-block/volumes/.env, resolves +the volume's layout id (with --chunk-filer), starts the unit, waits until it +serves, and prints the connect command. A new volume, until volume start +can create one: add it to blockmaster's cluster spec and restart blockmaster +(the standalone page's "Required setup"), then volume start. + +stop: refuses while a guest is connected (unless --force), takes a cut, +refuses when the cut failed or its outcome is unknown (unless --no-cut), +stops the unit, and ends with: "` + stopRecoveryPoint + `". + +backup: a named snapshot of a running walstore-chunk volume (--name is +required; the same command with the same --name resumes it, never a second). + +restore: the snapshot into a new volume on this host (same master and chunk +filer as the source), then volume start for it. Interrupted anywhere, the +same command finishes it; --abort undoes it (stops and deletes the new +volume, releases the snapshot, removes its settings).` + +// volumeHelp is the usage, with the stop sentence's time shown as