Compare commits

..
558 changed files with 14617 additions and 31704 deletions

No files matched your search

+1 -2
View File
@@ -24,7 +24,6 @@ ignore-regex = \b[a-z]+[A-Z]\w*\b|\b[A-Z][a-z]+[A-Z]\w*\b
# aer: NVMe Asynchronous Event Request (spec term, seaweed-block NVMe/TCP target)
# aas: iSCSI ALUA Access State; dout: iSCSI Data-Out PDU (seaweed-block iSCSI target)
# nd, readds, wonce, abd, delet, re-declare: identifiers and test fixture literals in seaweed-block
# lits: Go AST literal slices in seaweed-block tests (internal/timebound/scan_test.go)
ignore-words-list = visibles,fo,te,ser,bject,unparseable,keep-alives,tread,anc,ue,auther,thirdparty,unknwon,atleast,sme,nin,aer,aas,dout,nd,readds,wonce,abd,delet,re-declare,lits
ignore-words-list = visibles,fo,te,ser,bject,unparseable,keep-alives,tread,anc,ue,auther,thirdparty,unknwon,atleast,sme,nin,aer,aas,dout,nd,readds,wonce,abd,delet,re-declare
# poligon: Yandex Disk API sandbox URL path (https://yandex.ru/dev/disk/poligon/)
uri-ignore-words-list = poligon
+1029 -1042
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 53 KiB

-1
View File
@@ -1,3 +1,2 @@
*.sh text eol=lf
core/chunkkernel/chunk-kernel-2.tsv text eol=lf
.github/model-code-trace.tsv text eol=lf
-11
View File
@@ -8,17 +8,6 @@ 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.
Source line numbers are not part of this file-wide mapping. Moving a function
or test within its file does not change its model obligations or rewrite the
table. The time-bound registry separately keys individual bounds by file,
function, bound kind and occurrence; CI scans current source locations for
diagnostics rather than committing those locations.
Git uses its built-in union merge for this table so concurrent row additions
are retained. After a merge, sort and deduplicate the non-comment rows; the
checker refuses unsorted or duplicate rows. Review removals explicitly: a
union merge does not decide whether an old mapping should be removed.
The reviewed map uses the neutral public module names: `SnapshotRemoval`,
`RestoreTarget`, `HolderInterface`, `EngineAdapter`, `StopAndRestart`,
`MoveAdmission`, `Promotion`, `ProbeRound`, `FencingRound`, `VolumeCreate`,
+83 -194
View File
@@ -1,24 +1,8 @@
# Exact repository-relative path<TAB>Module.Action; repeat a path for alternatives.
cmd/blockvolume/snapshot_operation_shutdown.go SnapOps.Stall
cmd/sw-block/chunk.go CutTime.Poll
cmd/sw-block/cut_progress_poll.go CutTime.CliGiveUp
cmd/sw-block/cut_progress_poll.go CutTime.CliServerUnknown
cmd/sw-block/cut_progress_poll.go CutTime.CliSilent
cmd/sw-block/cut_progress_poll.go CutTime.HolderRestart
cmd/sw-block/cut_progress_poll.go CutTime.Poll
cmd/sw-block/snapshot_operation.go SnapOps.Send
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
cmd/sw-block/volume_start_release.go StopAndRestart.IssueClean
cmd/sw-block/volume_start_release.go StopAndRestart.ReadClean
cmd/sw-block/volume_start_release.go StopAndRestart.SameEpochReopen
cmd/sw-block/volume_verbs.go CutTime.CliGiveUp
cmd/sw-block/volume_verbs.go CutTime.Poll
cmd/sw-block/workspace_show.go MoveAdmission.ReadForMove
core/authority/authority.go DeleteRetire.Retire
core/authority/authority_store_file.go DeleteRetire.Retire
core/authority/workspace.go HolderInterface.ForcedMove
core/authority/workspace.go HolderInterface.PlannedMove
core/authority/workspace.go MoveAdmission.Ack
@@ -36,30 +20,7 @@ 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/authority/workspace_retirement.go DeleteRetire.Retire
core/engine/apply.go ReplicationPeer.Reconcile
core/frontend/chunkstore/catalog_b.go CleanBatch.Publish
core/frontend/chunkstore/catalog_b.go CleanBatch.Request
core/frontend/chunkstore/catalog_snapshot_operation.go CleanBatch.Publish
core/frontend/chunkstore/clean_admission.go CleanBatch.Begin
core/frontend/chunkstore/clean_admission.go CleanBatch.Close
core/frontend/chunkstore/clean_admission.go CleanBatch.Request
core/frontend/chunkstore/clean_b.go CleanBatch.BeginIn
core/frontend/chunkstore/clean_b.go CleanBatch.Close
core/frontend/chunkstore/clean_b.go CleanBatch.Effects
core/frontend/chunkstore/clean_b.go CleanBatch.PrepIn
core/frontend/chunkstore/clean_b.go CleanBatch.PrepOut
core/frontend/chunkstore/clean_b.go CutTime.Complete
core/frontend/chunkstore/clean_b.go PageChain.Sweep
core/frontend/chunkstore/clean_b.go SnapshotRemoval.BeginClean
core/frontend/chunkstore/clean_b.go SnapshotRemoval.EndClean
core/frontend/chunkstore/clean_b.go StaleClean.HeadRead
core/frontend/chunkstore/clean_intent_b.go CleanBatch.Publish
core/frontend/chunkstore/clean_intent_b.go CleanBatch.Request
core/frontend/chunkstore/clean_intent_b.go PageChain.CRead
core/frontend/chunkstore/clean_intent_b.go QueueCap.Consume
core/frontend/chunkstore/cut_verification_window.go CutTime.Complete
core/frontend/chunkstore/cut_verification_window.go CutWindow.CallTimeout
core/frontend/chunkstore/layout/claim.go EngineAdapter.Takeover
core/frontend/chunkstore/layout/claim.go MoveAdmission.ClaimB
core/frontend/chunkstore/layout/claim.go SnapshotRemoval.Claim
@@ -68,16 +29,8 @@ 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/clean_batch.go CleanBatch.PrepIn
core/frontend/chunkstore/layout/clean_batch.go CleanBatch.PrepOut
core/frontend/chunkstore/layout/clean_batch.go SnapshotRemoval.EndClean
core/frontend/chunkstore/layout/clean_batch.go SnapshotRemoval.Validate
core/frontend/chunkstore/layout/commit.go CutTime.Complete
core/frontend/chunkstore/layout/commit.go EngineAdapter.Apply
core/frontend/chunkstore/layout/commit.go QueueCap.TakeBack
core/frontend/chunkstore/layout/commit.go SnapshotRemoval.Commit
core/frontend/chunkstore/layout/commit.go StaleClean.CommitCheck
core/frontend/chunkstore/layout/commit.go StaleClean.HeadCommit
core/frontend/chunkstore/layout/commit.go VolumeCreate.Commit
core/frontend/chunkstore/layout/create.go RestoreTarget.CreateHead
core/frontend/chunkstore/layout/create.go RestoreTarget.CreateVol
@@ -86,49 +39,14 @@ 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/delete_intent.go CutTime.Complete
core/frontend/chunkstore/layout/delete_intent.go PageChain.CAdvance
core/frontend/chunkstore/layout/delete_intent.go PageChain.CApply
core/frontend/chunkstore/layout/delete_intent.go PageChain.CRead
core/frontend/chunkstore/layout/delete_intent.go PageChain.CResolve
core/frontend/chunkstore/layout/delete_intent.go PageChain.Resend
core/frontend/chunkstore/layout/delete_intent.go PageChain.Send
core/frontend/chunkstore/layout/delete_intent.go PageChain.WritePage
core/frontend/chunkstore/layout/delete_intent.go QueueCap.Consume
core/frontend/chunkstore/layout/delete_intent.go QueueCap.Produce
core/frontend/chunkstore/layout/delete_intent.go VolDelSweep.Land
core/frontend/chunkstore/layout/delete_intent.go VolDelSweep.Stage
core/frontend/chunkstore/layout/format_level.go FormatGate.PublishOp
core/frontend/chunkstore/layout/format_level.go FormatGate.Upgrade1
core/frontend/chunkstore/layout/head.go CleanBatch.Publish
core/frontend/chunkstore/layout/head.go CleanBatch.Request
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/list_chain.go CutTime.Complete
core/frontend/chunkstore/layout/list_chain.go PageChain.CAdvance
core/frontend/chunkstore/layout/list_chain.go PageChain.CRead
core/frontend/chunkstore/layout/list_chain.go PageChain.CResolve
core/frontend/chunkstore/layout/list_chain.go PageChain.Resend
core/frontend/chunkstore/layout/list_chain.go PageChain.Send
core/frontend/chunkstore/layout/list_chain.go PageChain.WritePage
core/frontend/chunkstore/layout/list_chain.go QueueCap.Produce
core/frontend/chunkstore/layout/list_chain.go VolDelSweep.Land
core/frontend/chunkstore/layout/list_chain.go VolDelSweep.Stage
core/frontend/chunkstore/layout/maintenance_progress.go CutTime.Complete
core/frontend/chunkstore/layout/objects.go SnapshotRemoval.Upload
core/frontend/chunkstore/layout/read.go CutTime.Complete
core/frontend/chunkstore/layout/remove.go CleanBatch.Effects
core/frontend/chunkstore/layout/remove.go CutTime.Complete
core/frontend/chunkstore/layout/remove.go PageChain.Sweep
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/remove.go StaleClean.DeleteIt
core/frontend/chunkstore/layout/remove.go StaleClean.HeadRead
core/frontend/chunkstore/layout/remove.go StaleClean.MarkIt
core/frontend/chunkstore/layout/remove.go StaleClean.Stat
core/frontend/chunkstore/layout/snapshots.go EngineAdapter.OpWrite
core/frontend/chunkstore/layout/snapshots.go MoveAdmission.OpWrite
core/frontend/chunkstore/layout/snapshots.go RestoreTarget.AddDep
@@ -138,115 +56,42 @@ 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 CleanBatch.Begin
core/frontend/chunkstore/layout_remote.go CleanBatch.Publish
core/frontend/chunkstore/layout_remote.go CutTime.Complete
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 FormatGate.CutPublish
core/frontend/chunkstore/layout_remote.go FormatGate.Upgrade1
core/frontend/chunkstore/layout_remote.go PageChain.CRead
core/frontend/chunkstore/layout_remote.go StopAndRestart.SendCommit
core/frontend/chunkstore/layout_remote.go StopAndRestart.SettleAbort
core/frontend/chunkstore/layout_store.go CleanBatch.Publish
core/frontend/chunkstore/layout_store.go CleanBatch.Request
core/frontend/chunkstore/layout_store.go SnapshotRemoval.ApplyDelete
core/frontend/chunkstore/layout_store.go SnapshotRemoval.ApplyMark
core/frontend/chunkstore/layout_store.go StaleClean.Adopt
core/frontend/chunkstore/maintenance_request.go CutTime.CallTimeout
core/frontend/chunkstore/retain_b.go CleanBatch.Publish
core/frontend/chunkstore/retain_b.go CleanBatch.Request
core/frontend/chunkstore/retain_b.go CutTime.Complete
core/frontend/chunkstore/snapshot_delete_operation.go FormatGate.AdmitOp
core/frontend/chunkstore/snapshot_delete_operation.go SnapDelete.Send
core/frontend/chunkstore/snapshot_delete_target.go FormatGate.AdmitOp
core/frontend/chunkstore/snapshot_operation.go SnapOps.Retire
core/frontend/chunkstore/snapshot_operation.go SnapOps.Send
core/frontend/chunkstore/snapshot_operation.go SnapOps.TornAdmit
core/frontend/chunkstore/snapshot_operation_guard.go SnapOps.Delete
core/frontend/chunkstore/snapshot_operation_guard.go SnapOps.Publish
core/frontend/chunkstore/snapshot_operation_index.go SnapOps.GC
core/frontend/chunkstore/snapshot_operation_index.go SnapOps.Poll
core/frontend/chunkstore/snapshot_operation_index.go SnapOps.TermFlag
core/frontend/chunkstore/swfs.go VolumeCreate.Land
core/frontend/durable/maintenance_progress.go CutTime.Complete
core/frontend/durable/maintenance_progress.go CutTime.Fail
core/frontend/durable/maintenance_progress.go CutTime.Tick
core/frontend/durable/provider_chunk.go CutTime.Admit
core/frontend/durable/provider_chunk.go CutWindow.Fail
core/frontend/durable/provider_chunk.go EngineAdapter.SettleResume
core/frontend/durable/provider_chunk.go EngineAdapter.StartStop
core/frontend/durable/provider_chunk.go FormatGate.CutPublish
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/provider_preempt.go CutTime.Preempt
core/frontend/durable/provider_preempt.go CutTime.Settle
core/frontend/durable/storage_adapter.go EngineAdapter.GuestWrite
core/frontend/durable/storage_adapter.go HolderInterface.Write
core/frontend/durable/storage_adapter.go WALHold.Resubmit
core/frontend/iscsi/scsi.go WALHold.Stall
core/frontend/nvme/io.go WALHold.Stall
core/host/master/format_gate.go FormatGate.Finalize
core/host/master/format_gate.go FormatGate.Grant
core/host/master/format_gate.go FormatGate.Place
core/host/master/format_gate.go FormatGate.Report
core/host/master/format_gate.go FormatGate.Retire
core/host/master/journal_isolation.go DeleteRetire.HostRetire
core/host/master/layout_ready.go VolumeCreate.Place
core/host/master/observation_snapshot.go DeleteRetire.HostRetire
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/services.go FormatGate.Report
core/host/master/spec_retirement.go DeleteRetire.ReadOK
core/host/master/store_attestation.go ReplicationPeer.Attest
core/host/master/workspace_binding.go FormatGate.Grant
core/host/master/workspace_binding.go MoveAdmission.Ack
core/host/master/workspace_service.go FormatGate.Place
core/host/master/workspace_service.go FormatGate.Renew
core/host/master/workspace_service.go MoveAdmission.ReadForMove
core/host/master/workspace_service.go StopAndRestart.ReadClean
core/host/volume/chunk_control.go CutTime.InProgress
core/host/volume/chunk_control.go CutWindow.Fail
core/host/volume/chunk_control.go FormatGate.Upgrade1
core/host/volume/chunk_control.go SnapOps.Start
core/host/volume/host.go FormatGate.Downgrade
core/host/volume/host.go FormatGate.Renew
core/host/volume/host.go FormatGate.Upgrade
core/host/volume/manual_cut.go CutTime.Admit
core/host/volume/manual_cut.go CutTime.InProgress
core/host/volume/manual_cut.go CutTime.Poll
core/host/volume/manual_cut.go CutTime.Retire
core/host/volume/plain_detach_handle.go CutTime.OtherEnd
core/host/volume/plain_detach_handle.go CutTime.OtherStep
core/host/volume/plain_detach_handle.go CutTime.Preempt
core/host/volume/plain_detach_handle.go CutTime.Settle
core/host/volume/plain_detach_handle.go CutTime.SettleStall
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/recovery_watchdog.go RecoveryProgress.Authority
core/host/volume/recovery_watchdog.go RecoveryProgress.Fence
core/host/volume/recovery_watchdog.go RecoveryProgress.Replay
core/host/volume/recovery_watchdog.go RecoveryProgress.Stall
core/host/volume/recovery_watchdog.go RecoveryProgress.ToFence
core/host/volume/snapshot_operation.go SnapOps.Start
core/host/volume/workspace_lease.go FormatGate.Renew
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/host/volume/workspace_runtime.go FormatGate.Renew
core/host/volume/workspace_startup.go FormatGate.Renew
core/lifecycle/store.go VolumeCreate.MarkReady
core/lifecycle/store.go VolumeCreate.Record
core/replication/peer.go Promotion.Ship1
@@ -262,58 +107,102 @@ 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_coverage.go SlotFence.Publish
core/storage/chunk_coverage_map.go MoveWide2.Write
core/storage/chunk_head_belt.go HolderInterface.Fence
core/storage/chunk_layer.go CutTime.Settle
core/storage/chunk_layer.go CutWindow.Publish
core/storage/chunk_layer.go CutWindow.Retry
core/storage/chunk_layer.go EngineAdapter.EngineReRead
core/storage/chunk_layer.go EngineAdapter.NoOpCut
core/storage/chunk_layer.go FormatGate.Upgrade1
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_manual_cut.go CutTime.Busy
core/storage/chunk_manual_cut.go CutTime.PublishLost
core/storage/chunk_manual_cut.go CutTime.Settle
core/storage/chunk_manual_cut.go CutTime.SettleInherited
core/storage/chunk_manual_cut.go CutTime.SettleStall
core/storage/chunk_manual_cut.go HolderInterface.Fence
core/storage/chunk_preempt.go CutTime.OtherStep
core/storage/chunk_preempt.go CutTime.Preempt
core/storage/chunk_public.go FormatGate.Upgrade1
core/storage/chunk_seam.go FormatGate.Upgrade1
core/storage/chunk_state_upgrade.go SlotFence.Publish
core/storage/chunk_state_upgrade.go SlotFence.Sync
core/storage/chunk_upload.go CutWindow.CallTimeout
core/storage/chunk_upload.go CutWindow.Start
core/storage/cut_progress_window.go CutTime.Complete
core/storage/cut_progress_window.go CutWindow.CallTimeout
core/storage/cut_progress_window.go CutWindow.Complete
core/storage/cut_progress_window.go CutWindow.Fail
core/storage/cut_progress_window.go CutWindow.Tick
core/storage/flusher.go WALHold.Reclaim
core/storage/recovery_progress.go RecoveryProgress.Replay
core/storage/wal_admission.go WALHold.Arrive
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_fifo.go WALHold.Admit
core/storage/wal_admission_fifo.go WALHold.Arrive
core/storage/wal_admission_fifo.go WALHold.ReEnter
core/storage/wal_hold_window.go WALHold.CapAnswer
core/storage/wal_hold_window.go WALHold.Stall
core/storage/wal_write_hold.go WALHold.CapAnswer
core/storage/wal_write_hold.go WALHold.Stall
core/storage/walstore.go WALHold.Admit
core/storage/walstore_v3.go RecoveryProgress.Fence
core/storage/walstore_v3.go SlotFence2.OpenNew
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
1 # Exact repository-relative path<TAB>Module.Action; repeat a path for alternatives.
cmd/blockvolume/snapshot_operation_shutdown.go
cmd/sw-block/chunk.go
cmd/sw-block/cut_progress_poll.go
cmd/sw-block/cut_progress_poll.go
cmd/sw-block/cut_progress_poll.go
cmd/sw-block/cut_progress_poll.go
cmd/sw-block/cut_progress_poll.go
cmd/sw-block/snapshot_operation.go
2 cmd/sw-block/volume_backup.go
3 cmd/sw-block/volume_backup.go
4 cmd/sw-block/volume_backup.go
5 cmd/sw-block/volume_backup.go
cmd/sw-block/volume_start_release.go
cmd/sw-block/volume_start_release.go
cmd/sw-block/volume_start_release.go
cmd/sw-block/volume_verbs.go
cmd/sw-block/volume_verbs.go
cmd/sw-block/workspace_show.go
core/authority/authority.go
core/authority/authority_store_file.go
6 core/authority/workspace.go
7 core/authority/workspace.go
8 core/authority/workspace.go
20 core/authority/workspace_delete_reservation.go
21 core/authority/workspace_lease_view.go
22 core/authority/workspace_lease_view.go
core/authority/workspace_retirement.go
23 core/engine/apply.go
core/frontend/chunkstore/catalog_b.go
core/frontend/chunkstore/catalog_b.go
core/frontend/chunkstore/catalog_snapshot_operation.go
core/frontend/chunkstore/clean_admission.go
core/frontend/chunkstore/clean_admission.go
core/frontend/chunkstore/clean_admission.go
core/frontend/chunkstore/clean_b.go
core/frontend/chunkstore/clean_b.go
core/frontend/chunkstore/clean_b.go
core/frontend/chunkstore/clean_b.go
core/frontend/chunkstore/clean_b.go
core/frontend/chunkstore/clean_b.go
core/frontend/chunkstore/clean_b.go
core/frontend/chunkstore/clean_b.go
core/frontend/chunkstore/clean_b.go
core/frontend/chunkstore/clean_b.go
core/frontend/chunkstore/clean_intent_b.go
core/frontend/chunkstore/clean_intent_b.go
core/frontend/chunkstore/clean_intent_b.go
core/frontend/chunkstore/clean_intent_b.go
core/frontend/chunkstore/cut_verification_window.go
core/frontend/chunkstore/cut_verification_window.go
24 core/frontend/chunkstore/layout/claim.go
25 core/frontend/chunkstore/layout/claim.go
26 core/frontend/chunkstore/layout/claim.go
29 core/frontend/chunkstore/layout/clean.go
30 core/frontend/chunkstore/layout/clean.go
31 core/frontend/chunkstore/layout/clean.go
core/frontend/chunkstore/layout/clean_batch.go
core/frontend/chunkstore/layout/clean_batch.go
core/frontend/chunkstore/layout/clean_batch.go
core/frontend/chunkstore/layout/clean_batch.go
core/frontend/chunkstore/layout/commit.go
32 core/frontend/chunkstore/layout/commit.go
core/frontend/chunkstore/layout/commit.go
33 core/frontend/chunkstore/layout/commit.go
core/frontend/chunkstore/layout/commit.go
core/frontend/chunkstore/layout/commit.go
34 core/frontend/chunkstore/layout/commit.go
35 core/frontend/chunkstore/layout/create.go
36 core/frontend/chunkstore/layout/create.go
39 core/frontend/chunkstore/layout/delete.go
40 core/frontend/chunkstore/layout/delete.go
41 core/frontend/chunkstore/layout/delete.go
core/frontend/chunkstore/layout/delete_intent.go
core/frontend/chunkstore/layout/delete_intent.go
core/frontend/chunkstore/layout/delete_intent.go
core/frontend/chunkstore/layout/delete_intent.go
core/frontend/chunkstore/layout/delete_intent.go
core/frontend/chunkstore/layout/delete_intent.go
core/frontend/chunkstore/layout/delete_intent.go
core/frontend/chunkstore/layout/delete_intent.go
core/frontend/chunkstore/layout/delete_intent.go
core/frontend/chunkstore/layout/delete_intent.go
core/frontend/chunkstore/layout/delete_intent.go
core/frontend/chunkstore/layout/delete_intent.go
core/frontend/chunkstore/layout/format_level.go
core/frontend/chunkstore/layout/format_level.go
core/frontend/chunkstore/layout/head.go
core/frontend/chunkstore/layout/head.go
42 core/frontend/chunkstore/layout/head.go
43 core/frontend/chunkstore/layout/head.go
44 core/frontend/chunkstore/layout/head.go
45 core/frontend/chunkstore/layout/head.go
core/frontend/chunkstore/layout/list_chain.go
core/frontend/chunkstore/layout/list_chain.go
core/frontend/chunkstore/layout/list_chain.go
core/frontend/chunkstore/layout/list_chain.go
core/frontend/chunkstore/layout/list_chain.go
core/frontend/chunkstore/layout/list_chain.go
core/frontend/chunkstore/layout/list_chain.go
core/frontend/chunkstore/layout/list_chain.go
core/frontend/chunkstore/layout/list_chain.go
core/frontend/chunkstore/layout/list_chain.go
core/frontend/chunkstore/layout/maintenance_progress.go
46 core/frontend/chunkstore/layout/objects.go
core/frontend/chunkstore/layout/read.go
core/frontend/chunkstore/layout/remove.go
core/frontend/chunkstore/layout/remove.go
core/frontend/chunkstore/layout/remove.go
47 core/frontend/chunkstore/layout/remove.go
48 core/frontend/chunkstore/layout/remove.go
49 core/frontend/chunkstore/layout/remove.go
core/frontend/chunkstore/layout/remove.go
core/frontend/chunkstore/layout/remove.go
core/frontend/chunkstore/layout/remove.go
core/frontend/chunkstore/layout/remove.go
50 core/frontend/chunkstore/layout/snapshots.go
51 core/frontend/chunkstore/layout/snapshots.go
52 core/frontend/chunkstore/layout/snapshots.go
56 core/frontend/chunkstore/layout/start.go
57 core/frontend/chunkstore/layout_create.go
58 core/frontend/chunkstore/layout_create.go
core/frontend/chunkstore/layout_remote.go
core/frontend/chunkstore/layout_remote.go
core/frontend/chunkstore/layout_remote.go
59 core/frontend/chunkstore/layout_remote.go
60 core/frontend/chunkstore/layout_remote.go
61 core/frontend/chunkstore/layout_remote.go
62 core/frontend/chunkstore/layout_remote.go
63 core/frontend/chunkstore/layout_remote.go
core/frontend/chunkstore/layout_remote.go
core/frontend/chunkstore/layout_remote.go
core/frontend/chunkstore/layout_remote.go
64 core/frontend/chunkstore/layout_remote.go
65 core/frontend/chunkstore/layout_remote.go
core/frontend/chunkstore/layout_store.go
core/frontend/chunkstore/layout_store.go
66 core/frontend/chunkstore/layout_store.go
67 core/frontend/chunkstore/layout_store.go
core/frontend/chunkstore/layout_store.go
core/frontend/chunkstore/maintenance_request.go
core/frontend/chunkstore/retain_b.go
core/frontend/chunkstore/retain_b.go
core/frontend/chunkstore/retain_b.go
core/frontend/chunkstore/snapshot_delete_operation.go
core/frontend/chunkstore/snapshot_delete_operation.go
core/frontend/chunkstore/snapshot_delete_target.go
core/frontend/chunkstore/snapshot_operation.go
core/frontend/chunkstore/snapshot_operation.go
core/frontend/chunkstore/snapshot_operation.go
core/frontend/chunkstore/snapshot_operation_guard.go
core/frontend/chunkstore/snapshot_operation_guard.go
core/frontend/chunkstore/snapshot_operation_index.go
core/frontend/chunkstore/snapshot_operation_index.go
core/frontend/chunkstore/snapshot_operation_index.go
68 core/frontend/chunkstore/swfs.go
core/frontend/durable/maintenance_progress.go
core/frontend/durable/maintenance_progress.go
core/frontend/durable/maintenance_progress.go
core/frontend/durable/provider_chunk.go
core/frontend/durable/provider_chunk.go
69 core/frontend/durable/provider_chunk.go
70 core/frontend/durable/provider_chunk.go
core/frontend/durable/provider_chunk.go
71 core/frontend/durable/provider_chunk.go
72 core/frontend/durable/provider_chunk.go
73 core/frontend/durable/provider_chunk.go
74 core/frontend/durable/provider_layout.go
75 core/frontend/durable/provider_layout.go
core/frontend/durable/provider_preempt.go
core/frontend/durable/provider_preempt.go
76 core/frontend/durable/storage_adapter.go
77 core/frontend/durable/storage_adapter.go
core/frontend/durable/storage_adapter.go
core/frontend/iscsi/scsi.go
core/frontend/nvme/io.go
core/host/master/format_gate.go
core/host/master/format_gate.go
core/host/master/format_gate.go
core/host/master/format_gate.go
core/host/master/format_gate.go
core/host/master/journal_isolation.go
78 core/host/master/layout_ready.go
core/host/master/observation_snapshot.go
79 core/host/master/probe_round.go
80 core/host/master/probe_round.go
81 core/host/master/product_loop.go
82 core/host/master/product_loop.go
core/host/master/services.go
core/host/master/spec_retirement.go
83 core/host/master/store_attestation.go
core/host/master/workspace_binding.go
core/host/master/workspace_binding.go
core/host/master/workspace_service.go
core/host/master/workspace_service.go
84 core/host/master/workspace_service.go
85 core/host/master/workspace_service.go
core/host/volume/chunk_control.go
core/host/volume/chunk_control.go
core/host/volume/chunk_control.go
core/host/volume/chunk_control.go
core/host/volume/host.go
core/host/volume/host.go
core/host/volume/host.go
core/host/volume/manual_cut.go
core/host/volume/manual_cut.go
core/host/volume/manual_cut.go
core/host/volume/manual_cut.go
core/host/volume/plain_detach_handle.go
core/host/volume/plain_detach_handle.go
core/host/volume/plain_detach_handle.go
core/host/volume/plain_detach_handle.go
core/host/volume/plain_detach_handle.go
86 core/host/volume/primary_evidence.go
87 core/host/volume/primary_evidence.go
88 core/host/volume/primary_evidence.go
89 core/host/volume/probe_round.go
core/host/volume/recovery_watchdog.go
core/host/volume/recovery_watchdog.go
core/host/volume/recovery_watchdog.go
core/host/volume/recovery_watchdog.go
core/host/volume/recovery_watchdog.go
core/host/volume/snapshot_operation.go
core/host/volume/workspace_lease.go
90 core/host/volume/workspace_lease.go
91 core/host/volume/workspace_lease.go
92 core/host/volume/workspace_lease.go
93 core/host/volume/workspace_lease.go
94 core/host/volume/workspace_lease.go
core/host/volume/workspace_runtime.go
core/host/volume/workspace_startup.go
95 core/lifecycle/store.go
96 core/lifecycle/store.go
97 core/replication/peer.go
107 core/replication/volume.go
108 core/replication/volume.go
109 core/replication/volume.go
core/storage/chunk_coverage.go
core/storage/chunk_coverage_map.go
110 core/storage/chunk_head_belt.go
core/storage/chunk_layer.go
core/storage/chunk_layer.go
core/storage/chunk_layer.go
111 core/storage/chunk_layer.go
112 core/storage/chunk_layer.go
core/storage/chunk_layer.go
113 core/storage/chunk_layer.go
114 core/storage/chunk_layer.go
115 core/storage/chunk_layer.go
116 core/storage/chunk_layer.go
117 core/storage/chunk_layer.go
core/storage/chunk_manual_cut.go
core/storage/chunk_manual_cut.go
core/storage/chunk_manual_cut.go
core/storage/chunk_manual_cut.go
core/storage/chunk_manual_cut.go
core/storage/chunk_manual_cut.go
core/storage/chunk_preempt.go
core/storage/chunk_preempt.go
core/storage/chunk_public.go
core/storage/chunk_seam.go
118 core/storage/chunk_state_upgrade.go
119 core/storage/chunk_state_upgrade.go
core/storage/chunk_upload.go
core/storage/chunk_upload.go
core/storage/cut_progress_window.go
core/storage/cut_progress_window.go
core/storage/cut_progress_window.go
core/storage/cut_progress_window.go
core/storage/cut_progress_window.go
core/storage/flusher.go
core/storage/recovery_progress.go
core/storage/wal_admission.go
core/storage/wal_admission_fast.go
core/storage/wal_admission_fast.go
core/storage/wal_admission_fast.go
core/storage/wal_admission_fifo.go
core/storage/wal_admission_fifo.go
core/storage/wal_admission_fifo.go
core/storage/wal_hold_window.go
core/storage/wal_hold_window.go
core/storage/wal_write_hold.go
core/storage/wal_write_hold.go
core/storage/walstore.go
core/storage/walstore_v3.go
core/storage/walstore_v3.go
120 core/transport/catchup_sender.go
121 core/transport/rebuild_sender.go
122 core/transport/replica.go
123 core/transport/replica.go
124 core/transport/replica.go
125 core/transport/replica.go
126 core/storage/chunk_coverage.go
127 core/storage/chunk_coverage_map.go
128 core/storage/walstore_v3.go
129 core/frontend/chunkstore/snapshot_operation.go
130 core/frontend/chunkstore/snapshot_operation.go
131 core/frontend/chunkstore/snapshot_operation.go
132 core/frontend/chunkstore/snapshot_operation_index.go
133 core/frontend/chunkstore/snapshot_operation_index.go
134 core/frontend/chunkstore/snapshot_operation_index.go
135 core/frontend/chunkstore/snapshot_operation_guard.go
136 core/frontend/chunkstore/snapshot_operation_guard.go
137 core/host/volume/chunk_control.go
138 cmd/sw-block/snapshot_operation.go
139 core/host/volume/snapshot_operation.go
140 cmd/blockvolume/snapshot_operation_shutdown.go
141 core/frontend/chunkstore/snapshot_delete_operation.go
142 core/storage/wal_admission_fast.go
143 core/storage/wal_admission_fast.go
144 core/storage/wal_admission_fast.go
145 core/storage/wal_admission.go
146 core/storage/wal_admission_fifo.go
147 core/storage/wal_admission_fifo.go
148 core/storage/wal_admission_fifo.go
149 core/storage/walstore.go
150 core/frontend/durable/storage_adapter.go
151 core/storage/flusher.go
152 core/storage/wal_hold_window.go
153 core/storage/wal_write_hold.go
154 core/storage/wal_hold_window.go
155 core/storage/wal_write_hold.go
156 core/frontend/nvme/io.go
157 core/frontend/iscsi/scsi.go
158 core/host/master/format_gate.go
159 core/host/master/format_gate.go
160 core/host/master/workspace_service.go
161 core/host/master/format_gate.go
162 core/host/master/workspace_binding.go
163 core/host/master/format_gate.go
164 core/host/master/services.go
165 core/host/master/format_gate.go
166 core/host/volume/host.go
167 core/host/volume/host.go
168 core/frontend/chunkstore/layout/format_level.go
169 core/frontend/chunkstore/layout/format_level.go
170 core/frontend/chunkstore/snapshot_delete_target.go
171 core/frontend/chunkstore/snapshot_delete_operation.go
172 core/storage/recovery_progress.go
173 core/host/volume/recovery_watchdog.go
174 core/storage/walstore_v3.go
175 core/host/volume/recovery_watchdog.go
176 core/host/volume/recovery_watchdog.go
177 core/host/volume/recovery_watchdog.go
178 core/host/volume/recovery_watchdog.go
179 core/frontend/chunkstore/layout/delete_intent.go
180 core/frontend/chunkstore/layout/list_chain.go
181 core/frontend/chunkstore/layout/delete_intent.go
182 core/frontend/chunkstore/layout/list_chain.go
183 core/frontend/chunkstore/layout/delete_intent.go
184 core/frontend/chunkstore/layout/list_chain.go
185 core/frontend/chunkstore/layout/delete_intent.go
186 core/frontend/chunkstore/layout/list_chain.go
187 core/frontend/chunkstore/layout/delete_intent.go
188 core/frontend/chunkstore/layout/delete_intent.go
189 core/frontend/chunkstore/layout/list_chain.go
190 core/frontend/chunkstore/layout/delete_intent.go
191 core/frontend/chunkstore/layout/list_chain.go
192 core/frontend/chunkstore/clean_intent_b.go
193 core/frontend/chunkstore/layout_remote.go
194 core/frontend/chunkstore/layout/remove.go
195 core/frontend/chunkstore/clean_b.go
196 core/frontend/chunkstore/layout/remove.go
197 core/frontend/chunkstore/layout/remove.go
198 core/frontend/chunkstore/layout/remove.go
199 core/frontend/chunkstore/layout/remove.go
200 core/frontend/chunkstore/layout_store.go
201 core/frontend/chunkstore/layout/commit.go
202 core/frontend/chunkstore/layout/commit.go
203 core/frontend/chunkstore/layout/delete_intent.go
204 core/frontend/chunkstore/layout/list_chain.go
205 core/frontend/chunkstore/layout/delete_intent.go
206 core/frontend/chunkstore/clean_intent_b.go
207 core/frontend/chunkstore/layout/commit.go
208
-8
View File
@@ -89,11 +89,3 @@ TestProcedureLogTimesUseTheUTCInstant
# Snapshot operation intent and publication receipts survive real holder kills.
TestSnapshotOperationIntentAndPublicationCrashBoundaries
TestSnapshotOperationKillReceiptRejectsOrdinaryExit
# Two weed clusters side by side: a filer of one that reaches the other's master
# is in its own filer group, so the other's single-filer census still passes.
TestWeedClustersSideBySideKeepTheirOwnFilerCensus
# Kubernetes state: a holder on a wiped state directory never comes up empty.
TestRF1HolderOnAWipedStateDirectoryRefusesStoreLost
TestRF3WipedPrimaryRefusesAndASurvivorServesItsData
-1
View File
@@ -3,7 +3,6 @@ Machine/INV: <kind> / <INV rows>
Model: <Module.Action; OtherModule.Action, or NONE (pure function of Module) for mapped files>
Red-first: <commit + test that failed on the base, or NONE: reason>
Simplest: <the simplest version, and what this PR did not add>
Time bounds: <none, or each fixed time bound this PR adds or changes, with its class and model row as listed in docs/time-bounds.tsv>
Five questions, answered in plain words before review:
Serves: <which statement of the specification or the docs this change serves>
-36
View File
@@ -1,36 +0,0 @@
#!/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
printf '%s\n' "$FAKE_GO_OUTPUT"
exit "$FAKE_GO_STATUS"
EOF
chmod +x "$root/bin/go"
export PATH="$root/bin:$PATH"
cd "$root"
check() {
local name=$1 status=$2 output=$3 want=$4 message=$5 actual=0
FAKE_GO_STATUS="$status" FAKE_GO_OUTPUT="$output" bash "$here/known-bugs.sh" >result 2>&1 <<'LIST' || actual=$?
#1 ./fixture TestKnown
LIST
if [ "$actual" != "$want" ] || ! grep -q "$message" result; then
echo "FAIL: $name (exit $actual, expected $want)"; cat result; exit 1
fi
if [ "$message" != 'now PASSES' ] && grep -q 'now PASSES' result; then
echo "FAIL: $name falsely called fixed"; cat result; exit 1
fi
}
check failure 1 '--- FAIL: TestKnown (0.00s)' 0 'still fails'
check pass 0 '--- PASS: TestKnown (0.00s)' 1 'now PASSES'
check missing 0 'ok fixture [no tests to run]' 1 'did not run'
check skipped 0 '--- SKIP: TestKnown (0.00s)' 1 'did not run'
check build 1 'FAIL fixture [build failed]' 1 'failed to build'
check other 1 '--- FAIL: TestKnownOther (0.00s)' 1 'did not run'
check subtest 1 ' --- FAIL: TestKnown/child (0.00s)' 1 'did not run'
check interrupted 1 '=== RUN TestKnown' 1 'did not run'
check inconsistent 0 '--- FAIL: TestKnown (0.00s)' 1 'did not run'
echo 'known-bugs: exact failure, pass, missing, skip, build, other test and interruption controls PASS'
-22
View File
@@ -1,22 +0,0 @@
#!/usr/bin/env bash
# Read "issue package test" rows. Only an observed failure of that exact test
# proves the reproduction still runs; a missing/skipped test is not a fix.
set -uo pipefail
ok=1
while read -r issue pkg test; do
[ -n "$issue" ] || continue
out="out-${test}.txt"
status=0
go test -v -count=1 -run "^${test}\$" "$pkg" >"$out" 2>&1 || status=$?
if [ "$status" -ne 0 ] && grep -q "^--- FAIL: ${test} (" "$out"; then
echo "${test} (${issue}) still fails, as expected"
elif [ "$status" = 0 ] && grep -q "^--- PASS: ${test} (" "$out"; then
echo "::error::${test} (${pkg}) now PASSES: ${issue} looks fixed, remove its skip"
ok=0
else
echo "::error::${test} (${pkg}) did not run to a verdict or failed to build (exit ${status}):"
tail -20 "$out"
ok=0
fi
done
[ "$ok" = 1 ]
-65
View File
@@ -35,19 +35,6 @@ class ModelTraceTests(unittest.TestCase):
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_line_only_rebase_keeps_committed_mapping_and_obligations(self):
with tempfile.TemporaryDirectory() as tmp:
source = Path(tmp) / "a.go"
mapping = Path(tmp) / "model-code-trace.tsv"
mapping.write_text("core/a.go\tEngineAdapter.Begin\n", encoding="utf-8")
committed = mapping.read_bytes()
for padding in ("", "// unrelated rebase\n\n\n"):
source.write_text(padding + "package a\nfunc begin() {}\n", encoding="utf-8")
actual = checker.read_mapping(mapping)
self.assertEqual(checker.check("EngineAdapter.Begin", ["core/a.go"], actual), [])
self.assertEqual(len(checker.check("Other.Begin", ["core/a.go"], actual)), 1)
self.assertEqual(mapping.read_bytes(), committed)
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"]
@@ -85,58 +72,6 @@ class ModelTraceTests(unittest.TestCase):
with self.assertRaises(ValueError):
checker.read_mapping(mapping)
def test_mapping_requires_sorted_unique_rows_after_resolution(self):
with tempfile.TemporaryDirectory() as tmp:
mapping = Path(tmp) / "map.tsv"
a = "core/a.go\tEngineAdapter.Begin\n"
b = "core/b.go\tMoveAdmission.Revoke\n"
for content in (b + a, a + a):
with self.subTest(content=content):
mapping.write_text(content, encoding="utf-8")
with self.assertRaisesRegex(ValueError, "sorted and unique"):
checker.read_mapping(mapping)
mapping.write_text(a + b, encoding="utf-8")
self.assertEqual(set(checker.read_mapping(mapping)), {"core/a.go", "core/b.go"})
def test_model_trace_deletion_and_adjacent_addition_require_resolution(self):
attributes = (SCRIPT.parent.parent.parent / ".gitattributes").read_text(encoding="utf-8")
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
def git(*args, check=True):
return subprocess.run(["git", *args], cwd=root, capture_output=True,
check=check, text=True, timeout=15)
git("init", "-b", "base")
git("config", "user.name", "Example")
git("config", "user.email", "example@example.invalid")
git("config", "commit.gpgsign", "false")
(root / ".gitattributes").write_text(attributes, encoding="utf-8")
mapping = root / ".github" / "model-code-trace.tsv"
mapping.parent.mkdir()
a = "core/a.go\tEngineAdapter.Begin\n"
removed = "core/b.go\tMoveAdmission.Revoke\n"
added = "core/b.go\tVolumeCreate.Claim\n"
c = "core/c.go\tVolumeCreate.Claim\n"
mapping.write_text(a + removed + c, encoding="utf-8")
git("add", ".")
git("commit", "-m", "base")
git("switch", "-c", "remove")
mapping.write_text(a + c, encoding="utf-8")
git("commit", "-am", "remove obsolete binding")
git("switch", "-c", "add", "base")
mapping.write_text(a + removed + added + c, encoding="utf-8")
git("commit", "-am", "add adjacent binding")
git("switch", "remove")
merged = git("merge", "--no-edit", "add", check=False)
self.assertEqual(merged.returncode, 1, merged.stdout + merged.stderr)
self.assertIn("<<<<<<<", mapping.read_text(encoding="utf-8"))
# Resolve deliberately: keep the new binding, preserve the deletion.
mapping.write_text(a + added + c, encoding="utf-8")
self.assertNotIn(removed, mapping.read_text(encoding="utf-8"))
self.assertEqual(checker.read_mapping(mapping)["core/b.go"], {"VolumeCreate.Claim"})
attr = subprocess.run(["git", "check-attr", "merge", "--", ".github/model-code-trace.tsv"],
cwd=SCRIPT.parent.parent.parent, capture_output=True, check=True, text=True, timeout=15)
self.assertEqual(attr.stdout.strip(), ".github/model-code-trace.tsv: merge: unspecified")
if __name__ == "__main__":
unittest.main()
-4
View File
@@ -11,7 +11,6 @@ PURE = re.compile(rf"NONE \(pure function of ({IDENT})\)")
def read_mapping(path):
mapping = {}
previous = None
for number, line in enumerate(Path(path).read_text(encoding="utf-8").splitlines(), 1):
if not line.strip() or line.startswith("#"):
continue
@@ -26,9 +25,6 @@ def read_mapping(path):
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")
if previous is not None and line <= previous:
raise ValueError(f"mapping line {number}: rows must be sorted and unique; sort and deduplicate the union")
previous = line
mapping.setdefault(file, set()).add(action)
if not mapping:
raise ValueError("model mapping is empty; populate it before enabling this gate")
-58
View File
@@ -1,58 +0,0 @@
"""Trusted-base gate contracts and a PR that replaces its own checkers."""
from pathlib import Path
import os, shutil, subprocess, tempfile, unittest
ROOT = Path(__file__).resolve().parents[2]
class BaseGateTests(unittest.TestCase):
def test_readonly_events_and_separate_base_checkout(self):
for filename in ('spec-trace.yml', 'post-merge-review.yml'):
with self.subTest(workflow=filename):
text=(ROOT/'.github/workflows'/filename).read_text()
self.assertIn(' pull_request:',text)
self.assertNotIn('pull_request_target:',text)
self.assertIn(' contents: read',text)
self.assertNotIn('secrets.',text)
self.assertIn(' runs-on: ubuntu-latest',text)
self.assertIn('ref: ${{ github.event.pull_request.base.sha }}',text)
self.assertIn('path: trusted-base',text)
self.assertIn('working-directory: trusted-base',text)
self.assertIn('persist-credentials: false',text)
self.assertNotIn('ref: ${{ github.event.pull_request.head.sha }}',text)
self.assertNotIn('ref: ${{ github.sha }}',text)
text=(ROOT/'.github/workflows/spec-trace.yml').read_text()
self.assertIn('go-version-file: trusted-base/go.mod',text)
def test_pr_cannot_replace_base_validators_or_allowlist(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp); source=root/'source'; source.mkdir()
scripts=source/'.github/scripts'; scripts.mkdir(parents=True)
names=('spec-trace-check.sh','post-merge-review-check.sh','post-merge-review-changed.sh')
for name in names: shutil.copyfile(ROOT/'.github/scripts'/name,scripts/name)
allow=source/'.github/post-merge-review-allow.txt'; allow.write_text('docs/**\n')
def git(*args,cwd=source):
return subprocess.check_output(['git',*args],cwd=cwd,stderr=subprocess.PIPE,timeout=15)
git('init','-b','main'); git('config','user.name','Example'); git('config','user.email','example@example.invalid'); git('config','commit.gpgsign','false')
git('add','.'); git('commit','-m','base')
base=git('rev-parse','HEAD').decode().strip()
(source/'docs').mkdir(); (source/'docs/example.md').write_text('Documentation')
git('add','.'); git('commit','-m','documentation')
good=git('rev-parse','HEAD').decode().strip()
for name in ('spec-trace-check.sh','post-merge-review-check.sh'):
(scripts/name).write_text('#!/bin/sh\ntouch ../pr-code-ran\nexit 0\n')
allow.write_text('*\n')
git('add','.'); git('commit','-m','replace validators')
bad=git('rev-parse','HEAD').decode().strip()
checkout=root/'trusted-base'; git('clone','--quiet',str(source),str(checkout)); git('checkout','--detach',base,cwd=checkout)
self.assertEqual(git('rev-parse','HEAD',cwd=checkout).decode().strip(),base)
body=checkout/'body.txt'
valid='Feature: documentation\nMachine/INV: DOCS\nModel: NONE (documentation fixture only)\nRed-first: fixture validation\n'
for head,description,success in ((good,valid,True),(bad,'missing trace',False)):
body.write_text(description)
changes=git('diff','-z','--name-status','--no-renames',base+'...'+head,cwd=checkout)
for command in (['spec-trace-check.sh',str(body)],['post-merge-review-check.sh','.github/post-merge-review-allow.txt']):
result=subprocess.run(['bash','.github/scripts/'+command[0],*command[1:]],cwd=checkout,input=changes,capture_output=True,timeout=15)
self.assertEqual(result.returncode==0,success,result.stdout.decode()+result.stderr.decode())
self.assertFalse((root/'pr-code-ran').exists())
if __name__=='__main__': unittest.main()
-45
View File
@@ -16,34 +16,6 @@ expect() { # expect RC NAME
}
echo "plain line" >> a.txt; git commit -q -am "add a plain line"
expect 0 "clean change" "$mb" HEAD title body
# Synthetic equivalents exercise private-path and run-metadata signatures.
for leaked in \
'Parsing file /home/example/run-1/Example.tla' \
'Synthetic model run with 1 worker on 2 cores with 123MB heap [pid: 12345]' \
'[pid: 12345]' \
'pid=12345' \
'2 cores with 123MB heap'; do
echo "$leaked" >> a.txt; git commit -q -am "model output"
expect 1 "raw run metadata in added text" "$mb" HEAD title body
git reset -q --hard HEAD~1
done
echo '/home/example/run-1' > body
expect 1 "home path in description" "$mb" HEAD title body; : > body
echo 'docs/spec/example/recorded-example/RESULT.txt' > body
expect 1 "artifact reference in description" "$mb" HEAD title body; : > body
echo '[pid: 12345]' > title
expect 1 "run metadata in title" "$mb" HEAD title body; : > title
for artifact in docs/spec/example/recorded-example/RESULT.txt docs/spec/recorded-example.txt; do
mkdir -p "$(dirname "$artifact")"; echo 'all checks passed' > "$artifact"
git add "$artifact"; git commit -q -m "add model artifact"
expect 1 "artifact path even with clean contents" "$mb" HEAD title body
artifact_base=$(git rev-parse HEAD)
git rm -q "$artifact"; git commit -q -m "remove model artifact"
expect 0 "artifact removal is allowed" "$artifact_base" HEAD title body
git reset -q --hard HEAD~2
done
echo 'Model workers execute in parallel; heap limits and PID namespaces are documented.' > body
expect 0 "ordinary explanatory prose" "$mb" HEAD title body; : > 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
@@ -69,23 +41,6 @@ expect 1 "backslash form of the share path in the title" "$mb2" HEAD title body;
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
# Only the NUL-separated artifact enumeration fails, after partial output;
# every other git call delegates to the real executable.
real_git=$(command -v git)
mkdir -p fakegit
cat > fakegit/git <<'EOF'
#!/usr/bin/env bash
if [[ $1 == diff && ${2:-} == --name-only && ${3:-} == -z ]]; then
printf 'docs/spec/clean.txt\0'
exit 7
fi
exec "$PUBLIC_TEXT_REAL_GIT" "$@"
EOF
chmod +x fakegit/git
rc=0
PUBLIC_TEXT_REAL_GIT="$real_git" PATH="$PWD/fakegit:$PATH" bash "$here/public-text-check.sh" "$mb2" HEAD title body >out 2>&1 || rc=$?
[ "$rc" = 2 ] || { echo "public-text-check-test: failed artifact enumeration: exit $rc, want 2"; cat out; exit 1; }
if grep -q 'public-text: clean' out; then echo 'public-text-check-test: failed artifact enumeration printed clean'; cat out; exit 1; fi
# 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
+3 -15
View File
@@ -1,7 +1,7 @@
#!/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 names, machine paths and raw run artifacts do not belong in it.
# 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.
@@ -18,9 +18,8 @@ git rev-parse -q --verify "$mb^{commit}" >/dev/null && git rev-parse -q --verify
{ 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|/home/[^/[:space:]]+/|(^|[^[:alnum:]_])pid[[:space:]]*[:=][[:space:]]*[0-9]+|[0-9]+[[:space:]]+cores[[:space:]]+with[[:space:]]+[0-9]+([.][0-9]+)?[[:space:]]*(KB|MB|GB|KiB|MiB|GiB)?[[:space:]]+heap|docs/spec/([^/[:space:]]+/)*recorded-[^/[:space:]]+'
out=$(mktemp); paths=; trap 'rm -f "$out" "$paths"' EXIT
paths=$(mktemp)
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
@@ -28,17 +27,6 @@ report() { # report WHERE < matching lines
' "$where" "${line:0:160}" >>"$out"
done
}
# Raw run artifacts are not public specs, even with scrubbed contents.
# Allow deletions so existing artifacts can be removed.
if ! git diff --name-only -z --no-renames --diff-filter=ACMT "$mb" "$head" -- docs/spec/ >"$paths"; then
echo 'public-text: cannot enumerate artifact paths' >&2
exit 2
fi
while IFS= read -r -d '' path; do
if [[ $path =~ ^docs/spec/(.*/)?recorded-[^/]+(/|$) ]]; then
printf '%s\n' "$path" | report "artifact path"
fi
done <"$paths"
# 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' |
@@ -1,92 +0,0 @@
"""Exercise release packaging without Docker, GitHub writes or product builds."""
from pathlib import Path
import json, os, subprocess, tarfile, tempfile, unittest
HERE = Path(__file__).resolve().parent
REV = "a" * 40
DIGEST = "example.invalid/block@sha256:" + "b" * 64
class ReleaseAssets(unittest.TestCase):
def run_case(self, bad=None, mode="revision", existing=True, tag="v1.1.1",
docker_rm_rc=0, rm_rc=0, publish_rc=0):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp); tools=root/"tools"; tools.mkdir(); image=root/"image"; image.mkdir()
expected={}
for name in ("blockmaster", "blockvolume", "sw-block"):
revision=REV; modified="false"; suffix=""; status=0
if bad == name:
if mode == "revision": revision="c"*40
elif mode == "dirty": modified="true"
elif mode == "unknown": revision="unknown"
elif mode == "lab": suffix=" LAB BUILD(example)"
elif mode == "provenance-failure": status=17
else: self.fail("invalid fixture mode")
data=(f"#!/bin/sh\necho '{name} revision={revision} modified={modified}{suffix}'\nexit {status}\n").encode()
(image/name).write_bytes(data); (image/name).chmod(0o755); expected[name]=data
log=root/"calls.jsonl"; state=root/"release.json"; state.write_text(json.dumps({"prerelease":"-" not in tag}))
common="""#!/usr/bin/env python3
import json,os,pathlib,shutil,sys
args=sys.argv[1:]
with open(os.environ['CALLS'],'a') as f: f.write(json.dumps([pathlib.Path(sys.argv[0]).name,*args])+chr(10))
"""
(tools/"docker").write_text(common+"""
if args[0]=='create': print('owned-container')
elif args[0]=='cp': shutil.copy2(pathlib.Path(os.environ['IMAGE'])/args[1].rsplit('/',1)[1],args[2])
elif args[0]=='rm': sys.exit(int(os.environ['DOCKER_RM_RC']))
""")
(tools/"rm").write_text(common+"""
if os.environ['RM_RC']!='0': sys.exit(int(os.environ['RM_RC']))
shutil.rmtree(args[-1])
""")
(tools/"gh").write_text(common+"""
if args[:2]==['release','view']: sys.exit(0 if os.environ['EXISTING']=='1' else 1)
if args[1] in ('edit','create'):
flag=next((a for a in args if a.startswith('--prerelease')), '--prerelease=false')
pathlib.Path(os.environ['STATE']).write_text(json.dumps({'prerelease':flag in ('--prerelease','--prerelease=true')}))
if args[1] in ('upload','create'): sys.exit(int(os.environ['PUBLISH_RC']))
""")
for tool in tools.iterdir(): tool.chmod(0o755)
out=root/"assets"
env=dict(os.environ,PATH=str(tools)+os.pathsep+os.environ['PATH'],CALLS=str(log),IMAGE=str(image),
EXISTING=str(int(existing)),STATE=str(state),GITHUB_REPOSITORY='example/block',
DOCKER_RM_RC=str(docker_rm_rc),RM_RC=str(rm_rc),PUBLISH_RC=str(publish_rc))
result=subprocess.run(['bash',str(HERE/'release-binary-assets.sh'),DIGEST,REV,tag,str(out)],
env=env,capture_output=True,text=True,timeout=15)
calls=[json.loads(line) for line in log.read_text().splitlines()] if log.exists() else []
primary=(17 if mode=='provenance-failure' else 1) if bad else publish_rc
self.assertEqual(result.returncode,primary or docker_rm_rc or rm_rc,result.stderr)
if bad:
self.assertFalse(any(c[0]=='gh' for c in calls),calls)
self.assertFalse((out/'SHA256SUMS').exists())
elif not publish_rc:
archive=out/f'sw-block-{tag}-linux-amd64.tar.gz'
with tarfile.open(archive) as tar:
self.assertEqual(set(tar.getnames()),set(expected))
for name,data in expected.items(): self.assertEqual(tar.extractfile(name).read(),data)
subprocess.run(['sha256sum','--check','SHA256SUMS'],cwd=out,check=True,capture_output=True)
command='upload' if existing else 'create'
self.assertTrue(any(c[:3]==['gh','release',command] for c in calls),calls)
self.assertEqual(json.loads(state.read_text())['prerelease'],'-' in tag)
self.assertEqual(calls[0],['docker','pull',DIGEST])
self.assertIn(['docker','create',DIGEST],calls)
self.assertEqual(calls[-2],['docker','rm','owned-container'])
self.assertEqual(calls[-1][:4],['rm','-rf','--',calls[-1][-1]])
if not rm_rc: self.assertFalse(Path(calls[-1][-1]).exists())
def test_release_kind_on_create_and_existing(self):
for existing in (False,True):
for tag in ('v1.1.1','v1.1.1-rc1'):
with self.subTest(existing=existing,tag=tag): self.run_case(existing=existing,tag=tag)
def test_every_binary_refuses_invalid_provenance(self):
for name in ('blockmaster','blockvolume','sw-block'):
for mode in ('revision','dirty','unknown','lab','provenance-failure'):
with self.subTest(binary=name,mode=mode): self.run_case(bad=name,mode=mode)
def test_cleanup_preserves_primary_error_and_tries_both(self):
self.run_case(publish_rc=37,docker_rm_rc=41,rm_rc=43)
self.run_case(bad='blockmaster',mode='provenance-failure',docker_rm_rc=41,rm_rc=43)
self.run_case(docker_rm_rc=41)
self.run_case(rm_rc=43)
if __name__=='__main__': unittest.main()
-49
View File
@@ -1,49 +0,0 @@
#!/usr/bin/env bash
# Copy release executables unchanged from the exact published Linux image.
set -euo pipefail
[ "$#" = 4 ] || { echo "usage: release-binary-assets.sh IMAGE@DIGEST REVISION TAG OUT" >&2; exit 2; }
image=$1; revision=$2; tag=$3; out=$4
[[ "$image" =~ @sha256:[a-f0-9]{64}$ ]] || { echo "an immutable image digest is required" >&2; exit 2; }
[[ "$revision" =~ ^[a-f0-9]{40}$ ]] || { echo "a full Git revision is required" >&2; exit 2; }
[[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || { echo "invalid release tag" >&2; exit 2; }
work=$(mktemp -d)
container=
cleanup() {
local status=$? cleanup_status=0 next_status=0
trap - EXIT
if [ -n "$container" ]; then
docker rm "$container" >/dev/null || cleanup_status=$?
fi
rm -rf -- "${work:?}" || {
next_status=$?
if [ "$cleanup_status" = 0 ]; then cleanup_status=$next_status; fi
}
if [ "$status" = 0 ]; then status=$cleanup_status; fi
exit "$status"
}
trap cleanup EXIT
mkdir -p "$work/bin"
docker pull "$image"
container=$(docker create "$image")
for binary in blockmaster blockvolume sw-block; do
docker cp "$container:/usr/local/bin/$binary" "$work/bin/$binary"
version=$("$work/bin/$binary" -version)
if [ "$version" != "$binary revision=$revision modified=false" ]; then
echo "$binary revision mismatch: expected $revision modified=false, got $version" >&2
exit 1
fi
done
mkdir -p "$out"
asset="sw-block-${tag}-linux-amd64.tar.gz"
tar -C "$work/bin" -czf "$out/$asset" blockmaster blockvolume sw-block
(cd "$out" && sha256sum "$asset" >SHA256SUMS)
prerelease=false
if [[ "$tag" == *-* ]]; then prerelease=true; fi
if gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
gh release edit "$tag" --repo "$GITHUB_REPOSITORY" --prerelease="$prerelease"
gh release upload "$tag" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --clobber
else
args=(--repo "$GITHUB_REPOSITORY" --verify-tag --title "Seaweed Block $tag" --generate-notes)
args+=(--prerelease="$prerelease")
gh release create "$tag" "$out/$asset" "$out/SHA256SUMS" "${args[@]}"
fi
-144
View File
@@ -1,144 +0,0 @@
"""Run fake recorders through the real group executor, without product tests."""
from pathlib import Path
import json
import os
import subprocess
import time
import sys
import tempfile
import unittest
from unittest.mock import Mock, patch
import importlib.util
import signal
SCRIPT = Path(__file__).with_name("run-unit-groups.py")
FAKE = r'''import json, os, sys, time
from pathlib import Path
out = Path(sys.argv[1]); group = out.parent.name
root = Path(os.environ["FIXTURE_ROOT"])
(root / (group + ".started")).write_text("started")
deadline = time.monotonic() + 5
while not all((root / (g + ".started")).exists() for g in os.environ["EXPECTED_GROUPS"].split()):
if time.monotonic() >= deadline: sys.exit(17)
time.sleep(.01)
flags = sys.argv[2:]
assert "-p=" + ("4" if group == "g3" else "1") in flags
assert "-short" in flags and "-count=1" in flags and "20m" in flags
if sys.platform == "linux":
wal = Path(os.environ["TMPDIR"]) / "v1.bin"
with wal.open("w") as descriptor:
assert os.readlink(f"/proc/self/fd/{descriptor.fileno()}") == str(wal), "fixture WAL descriptor not found"
else:
assert Path(os.environ["TMPDIR"]) == Path(os.environ["TMPDIR"]).resolve(), "TMPDIR must identify the canonical directory"
out.write_text(json.dumps({"Action":"pass", "Package":group}) + "\n")
out.with_suffix(".stderr").write_text("fixture stderr")
(root / (group + ".finished")).write_text("finished")
sys.exit(7 if os.environ.get("FAIL_GROUP") == group else 0)
'''
class GroupRunnerTests(unittest.TestCase):
def run_groups(self, fail="", empty=False, alias=False):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp); plan = root / "plan"; plan.mkdir()
for group in ("g1", "g2", "g3"):
(plan / (group + ".txt")).write_text("" if empty and group != "g3" else "example/" + group + "\n")
fake = root / "fake.py"; fake.write_text(FAKE)
env = dict(os.environ, FIXTURE_ROOT=str(root), EXPECTED_GROUPS="g3" if empty else "g1 g2 g3", FAIL_GROUP=fail)
scratch = root / "tmp"
if alias:
scratch.mkdir()
link = root / "runner-temp"
link.symlink_to(scratch, target_is_directory=True)
scratch = link
result = subprocess.run([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(scratch), sys.executable, str(fake)], env=env, text=True, capture_output=True, timeout=20)
self.assertEqual(result.returncode, 1 if fail else 0, result.stdout + result.stderr)
expected = ["g3"] if empty else ["g1", "g2", "g3"]
for group in expected:
self.assertTrue((root / (group + ".finished")).exists(), result.stdout + result.stderr)
self.assertTrue((root / "evidence" / group / "go-test.stderr").exists())
self.assertTrue((root / "tmp" / group).is_dir())
events = [json.loads(line) for line in (root / "evidence" / "go-test.json").read_text().splitlines()]
self.assertCountEqual([e["Package"] for e in events], expected)
statuses = json.loads((root / "evidence" / "unit-groups.json").read_text())
self.assertEqual(statuses["groups"]["g2"]["status"], 7 if fail == "g2" else 0)
@unittest.skipUnless(os.name == "posix", "Linux runner temp symlink control")
def test_runner_temp_symlink_passes_canonical_scratch_paths(self): self.run_groups(alias=True)
def test_all_groups_overlap_and_keep_separate_events(self): self.run_groups()
def test_failure_fails_job_after_every_group_finishes(self): self.run_groups(fail="g2")
def test_scope_empty_groups_launch_no_recorder(self): self.run_groups(empty=True)
def test_cancel_escalates_even_after_group_leader_exits(self):
spec = importlib.util.spec_from_file_location("unit_groups", SCRIPT)
module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
leader = Mock(pid=12345)
leader.wait.return_value = 0
with patch.object(module.signal, "SIGKILL", 9, create=True), patch.object(module.os, "name", "posix"), patch.object(module.os, "killpg", create=True) as killpg, patch.object(module.time, "monotonic", side_effect=[0, 6]):
module.terminate([leader])
self.assertIn(unittest.mock.call(12345, signal.SIGTERM), killpg.call_args_list)
self.assertIn(unittest.mock.call(12345, 9), killpg.call_args_list)
leader.wait.assert_called()
@unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control")
def test_cancel_kills_resistant_child_after_recorder_exits(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp); plan = root / "plan"; plan.mkdir()
for group in ("g1", "g2", "g3"):
(plan / (group + ".txt")).write_text("example/g1\n" if group == "g1" else "")
child = root / "child.py"
child.write_text("import os,signal,sys,time\nfrom pathlib import Path\nsignal.signal(signal.SIGTERM,signal.SIG_IGN)\np=Path(sys.argv[1])\np.with_suffix('.tmp').write_text(str(os.getpid()))\np.with_suffix('.tmp').replace(p)\nwhile True: time.sleep(.1)\n")
fake = root / "recorder.py"
fake.write_text("import subprocess,sys,time\nsubprocess.Popen([sys.executable,sys.argv[1],sys.argv[2]])\nwhile True: time.sleep(.1)\n")
marker = root / "child"
runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake), str(child), str(marker)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
pid = None
try:
deadline = time.monotonic() + 5
while not marker.exists():
if time.monotonic() >= deadline: self.fail("resistant child did not start")
time.sleep(.01)
pid = int(marker.read_text())
runner.terminate()
self.assertEqual(runner.wait(timeout=12), 130)
deadline = time.monotonic() + 2
while True:
stat = Path(f"/proc/{pid}/stat")
if not stat.exists() or stat.read_text().split(") ", 1)[1].startswith("Z"): break
if time.monotonic() >= deadline: self.fail("resistant child survived cancellation")
time.sleep(.01)
finally:
if pid is not None:
try: os.kill(pid, signal.SIGKILL)
except ProcessLookupError: pass
if runner.poll() is None: runner.kill()
runner.communicate(timeout=5)
@unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control")
def test_cancel_joins_every_started_group(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp); plan = root / "plan"; plan.mkdir()
for group in ("g1", "g2", "g3"):
(plan / (group + ".txt")).write_text("example/" + group + "\n")
fake = root / "held.py"
fake.write_text("import os,sys,time\nfrom pathlib import Path\np=Path(sys.argv[1]).parent\n(p/'process.tmp').write_text(str(os.getpid()))\n(p/'process.tmp').replace(p/'process')\nwhile True: time.sleep(.1)\n")
runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
try:
deadline = time.monotonic() + 5
markers = [root / "evidence" / g / "process" for g in ("g1", "g2", "g3")]
while not all(p.exists() for p in markers):
if time.monotonic() >= deadline: self.fail("groups did not start")
time.sleep(.01)
children = [int(p.read_text()) for p in markers]
runner.terminate()
self.assertEqual(runner.wait(timeout=10), 130)
for child in children:
with self.assertRaises(ProcessLookupError): os.kill(child, 0)
finally:
if runner.poll() is None: runner.terminate()
runner.communicate(timeout=10)
if __name__ == "__main__": unittest.main()
-123
View File
@@ -1,123 +0,0 @@
"""Run the three default unit groups concurrently on the current runner.
Usage: run-unit-groups.py PLAN_DIR EVIDENCE_DIR TMP_DIR RECORDER [RECORDER_ARG ...]
The recorder accepts OUTPUT followed by go-test flags and packages. Each group
owns its logs/events; they are combined only after all group processes exit.
"""
from contextlib import ExitStack
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
def stop(_signum, _frame):
raise KeyboardInterrupt
def terminate(processes):
for process in processes:
try:
if os.name == "posix": os.killpg(process.pid, signal.SIGTERM)
elif process.poll() is None: process.terminate()
except ProcessLookupError:
pass
if os.name == "posix":
# The leader may exit on TERM while its descendants remain in the group.
# Bound the grace period by group lifetime, never by leader lifetime.
deadline = time.monotonic() + 5
remaining = list(processes)
while remaining and time.monotonic() < deadline:
alive = []
for process in remaining:
process.poll() # Reap an exited leader without forgetting its PGID.
try:
os.killpg(process.pid, 0)
alive.append(process)
except ProcessLookupError:
pass
remaining = alive
if remaining: time.sleep(.05)
for process in remaining:
try: os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError: pass
for process in processes:
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=5)
def run(plan, evidence, temp, recorder):
groups = {g: (plan / (g + ".txt")).read_text().splitlines() for g in ("g1", "g2", "g3")}
evidence.mkdir(parents=True, exist_ok=True)
started = time.monotonic()
processes, results, times = {}, {}, {}
with ExitStack() as files:
try:
for group, packages in groups.items():
results[group] = {"packages": len(packages), "status": 0, "elapsed_seconds": 0}
if not packages:
print(f"{group}: no packages selected by scope", flush=True)
continue
out = evidence / group; out.mkdir(parents=True, exist_ok=True)
scratch = temp / group; scratch.mkdir(parents=True, exist_ok=True)
# /proc/self/fd exposes resolved paths; preserve fixture identity even
# when the runner temp directory is a symlink to its data disk.
scratch = scratch.resolve(strict=True)
log = files.enter_context((out / "console.log").open("w", encoding="utf-8"))
command = recorder + [str(out / "go-test.json"), "-p=" + ("4" if group == "g3" else "1"), "-short", "-count=1", "-timeout", "20m", *packages]
times[group] = time.monotonic()
processes[group] = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
env=dict(os.environ, TMPDIR=str(scratch)), start_new_session=os.name == "posix")
print(f"{group}: started {len(packages)} packages", flush=True)
remaining = set(processes)
while remaining:
for group in tuple(remaining):
status = processes[group].poll()
if status is not None:
results[group]["status"] = status
results[group]["elapsed_seconds"] = round(time.monotonic() - times[group], 3)
remaining.remove(group)
if remaining: time.sleep(.05)
except BaseException:
signal.signal(signal.SIGTERM, signal.SIG_IGN)
signal.signal(signal.SIGINT, signal.SIG_IGN)
terminate(processes.values())
raise
for group in processes:
print(f"--- {group} ---", flush=True)
print((evidence / group / "console.log").read_text(errors="replace"), flush=True)
summary = {"elapsed_seconds": round(time.monotonic() - started, 3), "groups": results}
try:
(evidence / "unit-groups.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
with (evidence / "go-test.json").open("ab") as combined:
for group in processes:
events = evidence / group / "go-test.json"
if events.exists(): combined.write(events.read_bytes())
except OSError as error:
print(f"test evidence unavailable: {error}", file=sys.stderr)
print(json.dumps(summary), flush=True)
return int(any(r["status"] != 0 for r in results.values()))
def main(argv):
if len(argv) < 5:
print(__doc__.strip(), file=sys.stderr)
return 2
signal.signal(signal.SIGTERM, stop)
try:
return run(Path(argv[1]), Path(argv[2]), Path(argv[3]), argv[4:])
except KeyboardInterrupt:
return 130
except (OSError, ValueError) as error:
print(f"unit groups: {error}", file=sys.stderr)
return 2
if __name__ == "__main__": sys.exit(main(sys.argv))
-52
View File
@@ -1,52 +0,0 @@
"""Exact coverage before scope selection; old heavy-package rules afterward."""
import importlib.util
from pathlib import Path
import unittest
spec = importlib.util.spec_from_file_location("planner", Path(__file__).with_name("unit-test-shards.py"))
planner = importlib.util.module_from_spec(spec)
spec.loader.exec_module(planner)
MODULE = "example.invalid/product"
HEAVY = ("core/storage", "core/frontend/durable", "core/host/master", "core/authority")
class UnitShardTests(unittest.TestCase):
def setUp(self):
self.packages = [MODULE + "/" + p for p in (*HEAVY, "cmd/sw-block", "core/frontend/chunkstore", "internal/newpackage", "core/storage/child")]
self.groups = planner.partition(MODULE, self.packages)
def test_exact_cover_and_stable_order(self):
flat = [p for group in self.groups.values() for p in group]
self.assertCountEqual(flat, self.packages)
self.assertEqual(len(flat), len(set(flat)))
self.assertEqual(self.groups, planner.partition(MODULE, list(reversed(self.packages))))
self.assertEqual(self.groups["g1"], [MODULE + "/core/storage"])
self.assertEqual(self.groups["g2"], [MODULE + "/" + p for p in HEAVY[1:]])
self.assertIn(MODULE + "/internal/newpackage", self.groups["g3"])
self.assertIn(MODULE + "/core/storage/child", self.groups["g3"])
def test_existing_heavy_scope_on_main_train_and_prs(self):
all_changed = [p + "/changed.go" for p in HEAVY]
for event, ref in (("push", ""), ("pull_request", "train/next")):
selected = planner.select(MODULE, self.groups, event, ref, all_changed)
self.assertEqual(selected["g1"], [])
self.assertEqual(selected["g2"], [])
self.assertEqual(selected["g3"], self.groups["g3"])
self.assertEqual(planner.select(MODULE, self.groups, "pull_request", "fix/x", all_changed), self.groups)
for path in HEAVY:
selected = planner.select(MODULE, self.groups, "pull_request", "fix/x", [path + "/x.go"])
heavy = selected["g1"] + selected["g2"]
self.assertEqual(heavy, [MODULE + "/" + path])
nested = planner.select(MODULE, self.groups, "pull_request", "fix/x", ["core/storage/child/x.go", "core/storage/"])
self.assertEqual(nested["g1"], [])
self.assertEqual(nested["g2"], [])
self.assertEqual(nested["g3"], self.groups["g3"])
def test_invalid_inventory_is_refused(self):
for packages in ([], self.packages + [self.packages[0]], self.packages[1:], self.packages + ["other/pkg"]):
with self.subTest(packages=packages), self.assertRaises(ValueError):
planner.partition(MODULE, packages)
if __name__ == "__main__":
unittest.main()
-55
View File
@@ -1,55 +0,0 @@
"""Plan the default unit groups from the full go-list inventory.
Usage: go list ./... | python3 unit-test-shards.py MODULE OUT_DIR EVENT HEAD_REF CHANGED_FILE
The complete partition covers every package exactly once. Existing scope rules
then select heavy packages only on ordinary PRs that touch their direct files.
"""
from pathlib import Path
import sys
HEAVY = ("core/storage", "core/frontend/durable", "core/host/master", "core/authority")
def partition(module, packages):
if not module or any(c.isspace() for c in module):
raise ValueError("expected one module path")
if not packages or len(packages) != len(set(packages)):
raise ValueError("empty package list or duplicate package")
if any(p != module and not p.startswith(module + "/") for p in packages):
raise ValueError("package outside the selected module")
heavy = [module + "/" + p for p in HEAVY]
if not set(heavy) <= set(packages):
raise ValueError("required heavy packages missing from go list")
return {"g1": heavy[:1], "g2": heavy[1:], "g3": sorted(set(packages) - set(heavy))}
def select(module, groups, event, head_ref, changed):
selected = set()
if event != "push" and not head_ref.startswith("train/"):
for p in HEAVY:
if any(f.startswith(p + "/") and f[len(p) + 1:] and "/" not in f[len(p) + 1:] for f in changed):
selected.add(module + "/" + p)
return {name: [p for p in packages if name == "g3" or p in selected]
for name, packages in groups.items()}
def main(argv):
if len(argv) != 6:
print(__doc__.strip(), file=sys.stderr)
return 2
try:
groups = partition(argv[1], sys.stdin.read().split())
groups = select(argv[1], groups, argv[3], argv[4], Path(argv[5]).read_text().splitlines())
out = Path(argv[2])
out.mkdir(parents=True, exist_ok=True)
for name, packages in groups.items():
(out / (name + ".txt")).write_text("".join(p + "\n" for p in packages), encoding="utf-8")
print(f"{name}: {len(packages)} packages")
except (OSError, ValueError) as error:
print(f"unit-test-shards: {error}", file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+17 -4
View File
@@ -42,12 +42,25 @@ jobs:
go-version-file: go.mod
cache: false
- name: Known-bug verdict controls
run: bash .github/scripts/known-bugs-test.sh
- name: Each reproduction still fails
run: |
bash .github/scripts/known-bugs.sh <<'LIST'
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 ]
+9 -6
View File
@@ -4,10 +4,11 @@ name: post-merge-review paths
# every changed file is allowed by .github/post-merge-review-allow.txt.
# This check fails such a PR otherwise; without the label it passes.
#
# A read-only pull_request run executes validators and the allow list from
# a separate base-commit checkout. The PR head is inspected only as objects.
# 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:
pull_request_target:
# edited: a retarget changes the base, and with it the diff.
types: [opened, synchronize, reopened, labeled, unlabeled, edited]
@@ -21,7 +22,11 @@ concurrency:
jobs:
paths:
name: post-merge-review paths
# Forks and same-repository PRs use the same disposable runner.
# 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:
@@ -34,12 +39,10 @@ jobs:
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
ref: ${{ github.event.pull_request.base.sha }}
path: trusted-base
fetch-depth: 0
persist-credentials: false
- name: Check changed paths
working-directory: trusted-base
if: ${{ contains(github.event.pull_request.labels.*.name, 'post-merge-review') }}
env:
BASE: ${{ github.event.pull_request.base.sha }}
+1 -16
View File
@@ -7,7 +7,7 @@ on:
- "v*"
permissions:
contents: write
contents: read
packages: write
env:
@@ -72,16 +72,11 @@ jobs:
echo "EOF"
} >> "$GITHUB_OUTPUT"
- name: Release asset controls
run: python3 -I .github/scripts/release-binary-assets-test.py
- name: Build and push block image
id: block
uses: docker/build-push-action@v6
with:
context: .
file: deploy/k8s/g15b/Dockerfile.sw-block
platforms: linux/amd64
push: true
tags: ${{ steps.tags.outputs.block_tags }}
@@ -92,13 +87,3 @@ jobs:
file: deploy/k8s/g15b/Dockerfile.blockcsi
push: true
tags: ${{ steps.tags.outputs.csi_tags }}
- name: Attach matching Linux binaries to the release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BLOCK_DIGEST: ${{ steps.block.outputs.digest }}
run: |
set -euo pipefail
revision=$(git rev-parse HEAD)
bash .github/scripts/release-binary-assets.sh "${BLOCK_IMAGE}@${BLOCK_DIGEST}" \
"$revision" "$GITHUB_REF_NAME" "$RUNNER_TEMP/block-release"
+18 -12
View File
@@ -3,11 +3,12 @@ name: spec trace
# Every PR description carries the spec trace (see the PR template); this
# check fails a PR whose description does not.
#
# A read-only pull_request run checks out the event's base commit into its
# own directory. Validators and data come from that checkout; the PR head
# is fetched only as Git objects. The body is passed as data, not shell code.
# 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:
pull_request_target:
# edited: the check reads the description and the base.
types: [opened, synchronize, reopened, edited]
@@ -21,27 +22,33 @@ concurrency:
jobs:
trace:
name: spec trace
# Both same-repository and fork PRs use disposable hosted runners.
runs-on: ubuntu-latest
# 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:
ref: ${{ github.event.pull_request.base.sha }}
path: trusted-base
# 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
# The token-comparison helper is built from the base checkout too.
# 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: trusted-base/go.mod
go-version-file: go.mod
cache: false
- name: Check spec trace
working-directory: trusted-base
env:
BASE: ${{ github.event.pull_request.base.sha }}
HEAD: ${{ github.event.pull_request.head.sha }}
@@ -71,7 +78,6 @@ jobs:
bash .github/scripts/public-text-check.sh "$mb" "$HEAD" title.txt body.txt
- name: Invariants ledger anchors (report only)
working-directory: trusted-base
# 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
+18 -24
View File
@@ -34,17 +34,14 @@ jobs:
# 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 self-hosted runner (seaweed.slice,
# 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' }}
# unit: a PR touching core/storage and core/frontend/durable adds both packages to the
# default step (measured 32 min on the self-hosted runner) before the v3-tagged step
# (measured 7-8 min), so 40 min cancelled the job; 60 min is about 1.5x that sum.
# process: 44 tests in 4 parallel shards of about 13 min each (55 min in sequence).
timeout-minutes: ${{ matrix.suite == 'unit' && 60 || 90 }}
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.
@@ -143,8 +140,6 @@ jobs:
set -euo pipefail
bash .github/scripts/lab-tag-check.sh .
bash .github/scripts/lab-tag-check-test.sh
python3 -I .github/scripts/release-binary-assets-test.py
python3 -I .github/scripts/pr-gate-base-test.py
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/
@@ -153,30 +148,29 @@ jobs:
- name: Test default configuration
if: matrix.suite == 'unit'
# Preserve the existing scope: main/train omit the four heavy packages;
# ordinary PRs add each only when its direct package files are touched.
# Three subprocesses share this ONE runner: storage, durable plus touched
# master/authority, and the remaining selected packages at -p=4.
# 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
python3 -I .github/scripts/unit-test-shards-test.py
python3 -I .github/scripts/run-unit-groups-test.py
plan="$RUNNER_TEMP/unit-groups"
mkdir -p "$plan"
go list ./... >"$plan/all.txt"
mod=$(go list -m)
# Main pushes need no changed-path list; a shallow initial push may
# have no parent. Ordinary PRs use the merge commit's base parent.
: >"$plan/changed.txt"
pkgs=$(go list ./... | grep -vE '/core/(storage|frontend/durable|host/master|authority)$')
if [ "$EVENT" != push ] && [[ "$HEAD_REF" != train/* ]]; then
git diff --name-only HEAD^1 HEAD >"$plan/changed.txt"
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
python3 -I .github/scripts/unit-test-shards.py "$mod" "$plan" "$EVENT" "$HEAD_REF" "$plan/changed.txt" <"$plan/all.txt"
python3 -I .github/scripts/run-unit-groups.py "$plan" "$CI_EVIDENCE_DIR" "$RUNNER_TEMP/unit-group-tmp" \
bash .github/scripts/record-go-test.sh
# 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'
+256 -179
View File
@@ -1,231 +1,308 @@
# Seaweed Block
[![tag](https://img.shields.io/github/v/tag/seaweedfs/seaweed-block?sort=semver&label=release)](docs/releases/README.md)
[![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)
**Local-first block storage for AI agents.**
*Run locally. Persist incrementally. Resume anywhere.*
Seaweed Block gives each agent sandbox or microVM its own block disk on the host's local storage, and checkpoints the
changed data to your own [SeaweedFS](https://github.com/seaweedfs/seaweedfs). Writes and `fsync` complete locally;
checkpoints, named snapshots and restores carry the workspace's state beyond that host. High density per host is a
design goal; see [Vision](#vision).
**[Quick start](#quick-start)** · [How it works](#how-it-works) · [Project status](#project-status) ·
[Documentation](#documentation)
**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).
<p align="center">
<img src="docs/assets/seaweed-block-lifecycle.svg" alt="The Seaweed Block lifecycle. Run locally: agent VMs on host A write to the host's local disk, where writes and fsync complete with no network round trip. Persist incrementally: checkpoints send only the changed 4 MiB chunks to your SeaweedFS in the background, and named snapshots share those chunks. Resume anywhere: host B restores a snapshot into a new volume, or takes a volume over in a planned move; it serves at once and fetches chunks on first read. Normal I/O to locally available data stays on the host." width="100%">
<img src="docs/assets/seaweed-block-hero.svg" alt="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." width="100%">
</p>
## Why not just use...
**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.
| | Local disk | Conventional network block storage | Seaweed Block |
|---|---|---|---|
| Where writes and `fsync` complete | On the host | Typically on a remote storage service | On the host |
| Network in the I/O path | No | Typically, for every read and write | No, for data on the host; a restored or moved volume fetches chunks on first read |
| If the host is lost | The state is lost with it | The volume typically survives | The state survives up to its last confirmed checkpoint |
| Resume on another host | Copy the data yourself | Typically, detach the volume and attach it there | Move the volume there, or restore a snapshot into a new volume there (placed by the cluster spec) |
| What persistence sends | Nothing | Typically every write, as it happens | Only the whole 4 MiB chunks that changed, at each checkpoint |
## Install
<p align="center">
<img src="docs/assets/seaweed-block-storage-models.svg" alt="Three ways to give an agent VM a disk. Local disk: all I/O stays on the host, fast, but the state is tied to that host. Network block storage: I/O typically crosses the network to a remote volume, so the state outlives the host, but the network is in the I/O path. Seaweed Block: normal I/O to locally available data stays on the host's local disk, and changed chunks go to your SeaweedFS in the background, so it runs at near-local speed and the state outlives the host up to its last checkpoint." width="100%">
</p>
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`):
## Run, checkpoint, snapshot, restore
```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
```
1. **Run.** Start a volume on the host where the agent runs. The guest attaches it over NVMe/TCP or iSCSI, formats it
with its own file system, and works at near-local speed.
2. **Checkpoint.** The changed chunks go to your SeaweedFS: on demand (`sw-block ops chunk cut`), periodically (the
holder's `--chunk-capture-interval`, 5 minutes or more), with the default daily snapshot, and when you stop the
volume (`sw-block volume stop`).
3. **Snapshot.** `sw-block volume backup <volume> --name <name>` (or `sw-block ops chunk snapshot`) names a point in
time. Snapshots share chunks with each other.
4. **Restore.** A restore makes a new volume from a snapshot, on the host that its placement in the cluster spec
names. It serves at once and fetches chunks on first read.
**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
```
The commands and what each needs: [snapshots, restore and verification](docs/operations-manual.md#5-snapshots-restore-and-verification).
**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).
## Features
## Try it
- **Near-local speed for agent workloads.** Writes and `fsync` complete on the host's disk, with no network round
trip, and every guest `fsync` reaches it.
- **Any file system, unchanged tools.** The guest sees a plain block device, so `git`, `npm` and builds run as on a
local disk.
- **Incremental checkpoints.** Only the changed 4 MiB chunks upload: on demand, periodically, or with the daily
snapshot.
- **Snapshots and instant restore.** Named snapshots share chunks, and a restored volume serves before its data
arrives.
- **Safe moves between hosts.** Epochs and leases fence the old host, so a stale host cannot publish over the
workspace's state.
- **Self-hosted and open source.** Your data stays in your SeaweedFS. Apache-2.0, written in Go.
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).
## Use cases
### `sw-block mini`
- **AI coding agents** whose repositories, dependencies and build caches must outlive the sandbox.
- **Agent sandboxes and microVM platforms** that give each sandbox its own disk.
- **Long-running agents** that stop, resume and move between hosts.
- **Also:** Kubernetes block volumes through the CSI driver (alpha), and replicated volumes for workloads that need
synchronous copies (`sync-quorum`, `sync-all`; preview).
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:
## One engine, two durability profiles
```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
```
Agent workspaces are the focus. The same block engine (write-ahead log and extent, NVMe/TCP and iSCSI frontends,
blockmaster's epochs) also runs replicated volumes, for workloads that need copies on other hosts before `fsync`
completes (`sync-quorum`, `sync-all`).
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).
| | Checkpointed volume | Replicated volume (preview) |
|---|---|---|
| Built for | Agent workspaces: many independent, portable disks | Workloads that need online copies on other hosts |
| When `fsync` completes | Once the data is on the host's local disk | With `sync-quorum` or `sync-all`, once a quorum or every replica has it (the default `best-effort` waits for none) |
| After a host is lost | An operator's forced move continues from the last checkpoint in SeaweedFS | With `--cluster-spec` and the lifecycle loop enabled (`--lifecycle-product-loop-interval`, off by default), blockmaster fails a `sync-quorum` or `sync-all` volume over to a replica when its fencing round decides; the operator then starts the guest on the new primary's host (no path failover in the guest). `best-effort` is not failed over automatically; the operator's forced failover may lose the last acknowledged writes |
| Snapshots, restore, moves | Yes | Not yet: the two profiles cannot be combined in v1.1.x |
| Status in v1.1.x | Supported | Preview, with [known limits](docs/releases/replicated-volumes-preview.md) |
## Why Seaweed Block
The two biggest limits of the preview: a replica that falls behind the retained log needs a manual re-add, and a
primary cut off from blockmaster is not stopped by a lease, so it may serve stale reads and, under `best-effort`,
accept writes that are later lost. Do not use replicated volumes for data you cannot lose.
- **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)).
A workload chooses the durability it needs: a checkpointed workspace does not pay for synchronous replicas, and a
replicated volume does not wait for checkpoints.
## Performance
## Measured results
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/measured-results-dark.svg">
<img src="docs/assets/measured-results-light.svg" alt="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." width="100%">
</picture>
Metadata-heavy agent work runs at local-disk speed, timing the operation itself (with the guest's final `syncfs`, 11-23%
slower); `fsync` latency and `fsync`-bound work are 1.3 to 1.5 times local. These are lab runs of pre-release builds
(the first four rows on the `walstore` engine, the last two on `walstore-chunk`) on Firecracker microVMs over NVMe/TCP
loopback, median of 3: measurements, not SLOs. Every number and how it was measured, with the build where it was
recorded: [workspace measurements](docs/workspace-measurements.md).
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`.
## Quick start
| 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 | |
A trial on a disposable Linux host, not for data you keep. You need `nvme-cli`, `sudo`, and SeaweedFS's `weed`
binary, tested with SeaweedFS 4.53 (from its [release page](https://github.com/seaweedfs/seaweedfs/releases/tag/4.53),
asset `linux_amd64.tar.gz`, which holds the one `weed` binary).
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 <filer>` and `--chunk-control-endpoint`, against a SeaweedFS
cluster. The `sw-block ops chunk` commands drive the lifecycle:
```bash
TAG=v1.1.1
curl -fsSLO https://github.com/seaweedfs/seaweed-block/releases/download/$TAG/sw-block-$TAG-linux-amd64.tar.gz
curl -fsSLO https://github.com/seaweedfs/seaweed-block/releases/download/$TAG/SHA256SUMS
sha256sum -c --ignore-missing SHA256SUMS && tar -xzf sw-block-$TAG-linux-amd64.tar.gz
export PATH="$PWD:$PATH" # so the sw-block commands that mini prints run as shown
./blockvolume --version # must print the tag's commit
# blockvolume keeps one lock per volume here, so only one live process serves a volume on a host:
sudo install -d -m 0755 -o root -g root /run/sw-block
sudo install -d -m 0755 -o "$USER" -g "$(id -gn)" /run/sw-block/locks
./sw-block mini --dir ./swb-mini --weed /path/to/weed
sw-block ops chunk cut --volume v1 --status-addr <status> # publish changed chunks, advance HEAD
sw-block ops chunk snapshot --volume v1 --status-addr <status> --name s1 # name a snapshot
sw-block ops chunk snapshots --master <blockmaster> --volume v1 --chunk-filer <filer> # list snapshots
sw-block ops chunk restore --master <blockmaster> --chunk-filer <filer> --source v1 --snapshot s1 --target v3 # new volume from a snapshot
sw-block ops chunk detach --volume v1 --status-addr <status> # final cut (seal); moving needs revoke + move, see docs/volume-lifecycle.md
sw-block ops chunk volume-delete --volume v3 --chunk-filer <filer> --master <blockmaster> --request-id del-v3
```
A failed start leaves `--dir` behind: start again with a new `--dir`, or on the same one with `--reuse`.
`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.
**What it shows today:**
- `mini` starts `weed mini`, `blockmaster` and one `blockvolume`: volume `v1`, 256 MiB, on loopback.
- It never runs `sudo` itself. It prints the `nvme connect` command that attaches `v1`, and the status, check and
snapshot commands. After the connect, `sudo nvme list` shows the disk's device (for example `/dev/nvme0n1`).
- Snapshots of `v1` work at once, through the `sw-block ops chunk snapshot` command it prints. A scheduled
`sched-<time>` snapshot also appears soon after the start. A restore into a new volume does not run inside `mini`
yet; use the standalone setup for it.
- To stop: unmount `v1`, run the `sudo nvme disconnect` that `mini` printed, then press Ctrl-C.
## Quick start: Kubernetes (alpha)
**Next:**
- Other ways to install (the release image, a build from the tag): [operations manual](docs/operations-manual.md#1-install-the-binaries-and-units).
- Services, restore and a second host: [standalone deployment](docs/standalone-deployment.md) and
[two hosts and a planned move](docs/operations-manual.md#appendix-b-two-hosts-and-a-planned-move).
- Kubernetes (alpha): [Kubernetes quick start](docs/quickstart-kubernetes.md), with v1.1.1. v1.1.0's generated pod
cannot start.
For supported lab clusters, not production. From the repository root, with
`kubectl` and `helm` configured:
## How it works
```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"
```
- **Local execution.** `blockvolume` serves the guest's block device over NVMe/TCP or iSCSI on the same host. A write
lands in a local write-ahead log, and `fsync` completes once the data is on the host's disk. The log then drains
into a local extent.
- **Incremental persistence.** A checkpoint (a *cut* in the CLI and the manuals) uploads the volume's changed 4 MiB
chunks to SeaweedFS. It then advances the volume's HEAD root with a conditional update on its generation and epoch.
A snapshot names a root and shares chunks with the others, with no backing chain.
- **Recovery and mobility.**
- A restore makes a new volume that serves at once and fetches each chunk from the snapshot on first read.
- One `blockmaster` issues epochs and leases, and the holder of a checkpointed (single-replica) volume serves only
under its current lease.
- A planned move first seals the volume with a final checkpoint, then revokes the old holder, waits for its recorded
release, and grants the next epoch on the new host, which loads chunks on first read.
- The store refuses a HEAD update from a stale holder, even before that holder notices it was replaced.
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:
<p align="center">
<img src="docs/assets/seaweed-block-hero.svg" alt="Write path: a microVM writes over NVMe/TCP or iSCSI to blockvolume, which completes write and fsync on its local WAL. Background path: a checkpoint uploads changed 4 MiB chunks to SeaweedFS and updates HEAD on generation and epoch; blockmaster issues epochs and leases; a stale holder's update is refused." width="100%">
</p>
```bash
helm uninstall sw-block --namespace kube-system
bash scripts/uninstall-k8s-alpha.sh "$PWD" && bash scripts/verify-helm-cleanup.sh
```
More: [agent workspace design](docs/design/agent-workspace-design.md), [volume lifecycle](docs/volume-lifecycle.md),
and the [TLA+ specifications](docs/spec/README.md) of the protocols where a bug would lose data.
## Detailed status
## Durability model
| Level | Reached when | Where the data is | What it protects against |
|---|---|---|---|
| Local synced | the guest's `fsync` returns | the holder host's disk | a crash or restart of the processes on that host |
| Remotely checkpointed | a checkpoint is confirmed (after its commit in SeaweedFS) | SeaweedFS | the loss of the host: a forced move continues from the last confirmed checkpoint |
| Named snapshot | a snapshot command answers ok | SeaweedFS, kept by name | a restore into a new volume at that point (in v1.1.x, not for a snapshot of a restored volume) |
- **Writes since the last confirmed checkpoint are lost if the host is lost.**
- **The default schedule is one snapshot a day.** It is attempted, not guaranteed, and it is not a recovery-point
objective. Periodic checkpoints (`--chunk-capture-interval`, 5 minutes or more) shorten the window. A persistent
agent should checkpoint at its task boundaries.
- **`sw-block volume stop` takes a checkpoint by default** (`--no-cut` skips it). A holder stopped any other way
(`systemctl stop`, a kill, or the loss of its host) takes none.
- **No production SLO, RPO or RTO is claimed.** Details: [operator guide](docs/operator-guide.md).
## Project status
| Capability | v1.1.x |
| Area | Status |
|---|---|
| Local single-replica volumes (`walstore-chunk`) | Supported |
| NVMe/TCP and iSCSI | Supported; in a standalone setup the guest runs on the holder's host |
| Incremental checkpoints | Supported |
| Named snapshots and lazy restore into a new volume | Supported |
| Planned moves between hosts (operator-run, fenced) | Supported |
| Volumes up to 1 TiB | Supported; above 256 GiB only at format level 1 (new clusters start at it; upgraded clusters run `sw-block cluster finalize-format`) and only after every host runs v1.1 |
| Replicated volumes (`replication_factor` above 1) | Preview: no snapshots, restore or moves; a replica that falls behind the retained log needs a manual re-add ([limits](docs/releases/replicated-volumes-preview.md)) |
| Kubernetes CSI | Alpha; in v1.1.x deleting a PVC may leave its volume behind, and that volume cannot be removed until v1.2 |
| Remote guests in a standalone setup, authenticated remote NVMe/TCP | Not in v1.1.x |
| Templates, instant fork | Not in v1.1.x |
| 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 |
Use tagged releases only: `main` is unreleased work. Each release's conditions are in the
[capabilities](docs/releases/capabilities.md) table and the [release notes](docs/releases/README.md).
Full table and conditions: [Kubernetes status](docs/kubernetes-status.md);
run evidence: [release notes](docs/releases/README.md).
## Vision
**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)).
Directions, not commitments; no dates.
- **Lightweight execution:** more volumes per host and less overhead per volume.
- **Instant workspaces:** shared templates, fast creation, branching.
- **Continuous persistence:** efficient rolling checkpoints.
- **Portable state:** recovery, migration and resume across hosts with less operator work.
- **Storage efficiency:** remote space that is reclaimed and reused, and rolling persistence with low write
amplification.
- **Flexible durability:** replicated volumes out of preview, and replicas combined with checkpoints and snapshots in
SeaweedFS.
### 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
| To | Read |
|---|---|
| Try it, run the services, restore a snapshot | [Standalone deployment](docs/standalone-deployment.md) |
| Install, upgrade, finalize, monitor, read typed errors | [Operations manual](docs/operations-manual.md) |
| Size a host, choose a recovery point, handle host loss | [Operator guide](docs/operator-guide.md) |
| Move, revoke, delete | [Volume lifecycle](docs/volume-lifecycle.md) |
| Run on Kubernetes (alpha) | [Kubernetes quick start](docs/quickstart-kubernetes.md), [Kubernetes status](docs/kubernetes-status.md) |
| See what each release supports | [Capabilities](docs/releases/capabilities.md), [release notes](docs/releases/README.md) |
| Check the numbers | [Workspace measurements](docs/workspace-measurements.md) |
| Read the architecture and formal specifications | [Agent workspace design](docs/design/agent-workspace-design.md), [core design](docs/design/block-design.md), [TLA+ specifications](docs/spec/README.md) |
- 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)
## Community and license
## Development
Questions and bug reports: [GitHub Issues](https://github.com/seaweedfs/seaweed-block/issues). To build and test:
`go build ./... && go vet ./... && go test -short ./...` (the unit checks; CI also runs the process-level suite).
Seaweed Block builds on [SeaweedFS](https://github.com/seaweedfs/seaweedfs). License: Apache-2.0.
```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
@@ -6,17 +6,6 @@ Next checks:
kubectl -n {{ .Release.Namespace }} rollout status ds/sw-block-csi-node --timeout=120s
Create volumes through Kubernetes PVCs using StorageClass {{ .Values.storageClass.name }}.
{{- if .Values.blockmaster.stateHostPath }}
Volume state is kept on each node under {{ include "seaweed-block.volumeStatePath" . }}; blockmaster's stores under {{ .Values.blockmaster.stateHostPath }}.
{{- if eq (include "seaweed-block.volumeStatePath" .) (clean .Values.blockmaster.stateHostPath) }}
WARNING: the generated blockvolume pods share blockmaster's state path (a v1.1.0 layout), so every one of them on blockmaster's node mounts blockmaster's authority and lifecycle stores read-write. To separate them without moving volume data, see "Kubernetes: volume state persists by default" in the v1.1.1 release notes.
{{- end }}
{{- else }}
WARNING: ephemeral restart persistence loses all data whenever a holder pod restarts (blockmaster.stateHostPath is empty).
{{- end }}
This chart is read-only/operator-free alpha packaging. It does not install a
mutating dashboard, operator CRDs, backup/restore, or upgrade safety.
@@ -98,20 +98,3 @@ helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
secret:
secretName: {{ . }}
{{- end -}}
{{/*
The generated blockvolume pods' state path on each node: restartPersistence.stateHostPath when set; empty, the
volumes directory beside blockmaster's when blockmaster's path ends in /master (this release's layout); otherwise
blockmaster's own path (the shared layout of a v1.1.0 install). "" with ephemeral state.
*/}}
{{- define "seaweed-block.volumeStatePath" -}}
{{- $master := .Values.blockmaster.stateHostPath | default "" -}}
{{- if not $master -}}
{{- else if .Values.restartPersistence.stateHostPath -}}
{{- clean .Values.restartPersistence.stateHostPath -}}
{{- else if eq (base (clean $master)) "master" -}}
{{- printf "%s/volumes" (dir (clean $master)) | clean -}}
{{- else -}}
{{- clean $master -}}
{{- end -}}
{{- end -}}
@@ -10,28 +10,6 @@
{{- 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 -}}
{{- if and .Values.blockmaster.stateHostPath (not (index (.Values.blockmaster.nodeSelector | default dict) "kubernetes.io/hostname")) -}}
{{- fail "blockmaster.stateHostPath keeps blockmaster's stores on one node: set blockmaster.nodeSelector.kubernetes.io/hostname to that node (a broader selector can start it on another node, on an empty state path)" -}}
{{- end -}}
{{- $volumeState := include "seaweed-block.volumeStatePath" . -}}
{{- if and $volumeState (ne $volumeState (clean .Values.blockmaster.stateHostPath)) (hasPrefix (printf "%s/" (trimSuffix "/" $volumeState)) (clean .Values.blockmaster.stateHostPath)) -}}
{{- fail "restartPersistence.stateHostPath is above blockmaster.stateHostPath: every generated blockvolume pod mounts its state path, so it would mount blockmaster's stores: put the two side by side (for example <base>/volumes and <base>/master)" -}}
{{- end -}}
{{- if and .Release.IsInstall .Values.blockmaster.stateHostPath (not .Values.restartPersistence.stateHostPath) (ne (base (clean .Values.blockmaster.stateHostPath)) "master") -}}
{{- fail "blockmaster.stateHostPath is outside the default layout and restartPersistence.stateHostPath is unset: a new install would put the generated blockvolume pods' state in blockmaster's directory, so they would mount its stores: set restartPersistence.stateHostPath beside blockmaster.stateHostPath (not above it)" -}}
{{- end -}}
{{- if and .Values.blockmaster.stateHostPath (not .Values.restartPersistence.acknowledgeEphemeralDataLoss) -}}
{{- $running := lookup "apps/v1" "Deployment" .Release.Namespace "sw-blockmaster" -}}
{{- if $running -}}
{{- $persistent := false -}}
{{- range $running.spec.template.spec.volumes -}}
{{- if and (eq .name "state") .hostPath -}}{{- $persistent = true -}}{{- end -}}
{{- end -}}
{{- if not $persistent -}}
{{- fail "this release runs with ephemeral state: switching to blockmaster.stateHostPath discards its volumes' data (still live in their pods until they restart), and their holders then refuse to start empty: set restartPersistence.acknowledgeEphemeralDataLoss=true to switch anyway" -}}
{{- end -}}
{{- end -}}
{{- end -}}
apiVersion: apps/v1
kind: Deployment
metadata:
@@ -42,11 +20,6 @@ metadata:
app: sw-blockmaster
spec:
replicas: {{ .Values.blockmaster.replicas }}
# blockmaster uses the host network and, with a state path, is pinned to
# one node: a rolling update's new pod can never start beside the old one
# (same host ports, only that node). An upgrade stops the old pod first.
strategy:
type: Recreate
selector:
matchLabels:
app: sw-blockmaster
@@ -117,7 +90,7 @@ spec:
- "--launcher-pvc-owner-ref"
{{- end }}
{{- if .Values.blockmaster.stateHostPath }}
- "--launcher-state-hostpath={{ include "seaweed-block.volumeStatePath" . }}"
- "--launcher-state-hostpath={{ .Values.blockmaster.stateHostPath }}"
{{- end }}
{{- if .Values.network.externalISCSI }}
- "--launcher-external-iscsi"
+4 -21
View File
@@ -46,13 +46,7 @@ blockmaster:
durableImpl: walstore
durableWALMultiBlockRecords: false
durableWALRecoveryTestDisableFlusher: false
# blockmaster's stores on this node path: set blockmaster.nodeSelector's
# kubernetes.io/hostname to the node that holds them (rendering fails
# without it; generate-helm-values sets it). Generated blockvolume state
# goes to restartPersistence.stateHostPath, a separate path, so a holder
# pod never mounts blockmaster's stores.
# "" is ephemeral: an emptyDir, and ephemeral restart persistence loses all data whenever a holder pod restarts.
stateHostPath: /var/lib/sw-block/k8s/master
stateHostPath: ""
stateHostPathType: DirectoryOrCreate
statePermissionsImage:
repository: busybox
@@ -61,21 +55,10 @@ blockmaster:
pullPolicy: IfNotPresent
restartPersistence:
# hostpath (the default) persists blockmaster and generated blockvolume state
# across Kubernetes pod restarts. ephemeral is an explicit opt-in (with
# blockmaster.stateHostPath ""): ephemeral restart persistence loses all data whenever a holder pod restarts.
mode: hostpath
# Generated blockvolume state on each node, one directory per volume
# replica (<stateHostPath>/<replica>/<volume>-<id>); the holder pod is
# pinned to its node. Empty (the default): the volumes directory beside
# blockmaster's when blockmaster.stateHostPath ends in /master
# (/var/lib/sw-block/k8s/volumes by default); otherwise
# blockmaster.stateHostPath itself, the shared layout of a v1.1.0 install.
# ephemeral keeps the alpha/dev default. hostpath persists blockmaster and
# generated blockvolume state across Kubernetes pod restarts.
mode: ephemeral
stateHostPath: ""
# Upgrading a release that runs with ephemeral state to a stateHostPath
# stops at render unless this is true: the switch discards its volumes'
# data (still live in their pods until they restart).
acknowledgeEphemeralDataLoss: false
storageClass:
create: true
@@ -135,6 +135,7 @@ func TestG15d_K8sRunner_AppliesLauncherGeneratedManifest(t *testing.T) {
"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",
@@ -444,7 +445,7 @@ func TestAlphaScripts_OwnerRefModeInjectsBothLauncherAndCSILookupFlags(t *testin
"SW_BLOCK_LAUNCHER_PVC_OWNER_REF",
"--launcher-pvc-owner-ref",
"--kubernetes-pvc-uid-lookup",
"Generated blockvolume Deployments live in the launcher namespace, PVC owner or not.",
"BLOCKVOLUME_NAMESPACE=\"$NAMESPACE\"",
} {
if !strings.Contains(body, want) {
t.Fatalf("%s missing %q", script, want)
@@ -1,55 +0,0 @@
package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// The multi-volume example counts only this run's generated Deployments and
// pods: those whose PVC annotations name its namespace and PVC prefix. A
// generated pod is labelled app=<its Deployment>, not app=sw-blockvolume, so
// pods are selected by the volume label every generated object carries. A
// fake kubectl answers like the API server: a pod matches only the volume
// label selector.
func TestMultiVolumeExampleListsOnlyThisRunsLeftovers(t *testing.T) {
bash, err := exec.LookPath("bash")
if err != nil {
t.Skip("bash not available")
}
script := g15dReadFile(t, "scripts", "run-multi-volume-example.sh")
script = strings.ReplaceAll(script, "\r\n", "\n")
start := strings.Index(script, "list_run_blockvolume_objects() {")
end := strings.Index(script, "list_matching_pvs() {")
if start < 0 || end < start {
t.Fatal("run-scoped listing functions not found in run-multi-volume-example.sh")
}
funcs := script[start:end]
dir := t.TempDir()
fake := `#!/usr/bin/env bash
kind="$2"; selector=""
while [ $# -gt 0 ]; do [ "$1" = "-l" ] && selector="$2"; shift; done
if [ "$kind" = "pod" ] && [ "$selector" != "sw-block.seaweedfs.com/volume" ]; then exit 0; fi
if [ "$kind" = "deployment" ] && [ "$selector" != "app=sw-blockvolume" ]; then exit 0; fi
echo "sw-block-system/sw-blockvolume-mine-r1 default sw-block-multi-pvc-1"
echo "sw-block-system/sw-blockvolume-other-ns-r1 team-b sw-block-multi-pvc-1"
echo "sw-block-system/sw-blockvolume-other-pvc-r1 default someone-elses-pvc"
`
if err := os.WriteFile(filepath.Join(dir, "kubectl"), []byte(fake), 0o755); err != nil {
t.Fatal(err)
}
cmd := exec.Command(bash, "-c", "NAMESPACE=default\nPVC_PREFIX=sw-block-multi-pvc\n"+funcs+"\nlist_blockvolume_deployments\nlist_blockvolume_pods\n")
cmd.Env = append(os.Environ(), "PATH="+dir+string(os.PathListSeparator)+os.Getenv("PATH"))
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("listing: %v\n%s", err, out)
}
got := strings.Fields(strings.ReplaceAll(string(out), "\r", ""))
want := []string{"deployment/sw-block-system/sw-blockvolume-mine-r1", "pod/sw-block-system/sw-blockvolume-mine-r1"}
if strings.Join(got, " ") != strings.Join(want, " ") {
t.Fatalf("listed %v, want only this run's leftovers %v", got, want)
}
}
@@ -1,175 +0,0 @@
package main
import (
"context"
"encoding/json"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/host/master"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
// Manual run 2: a placement-only restore target was never created, then
// removed from the spec. A new start must not retain that unused intent.
func TestClusterSpecImportRemovesUnusedPlacementMissingFromSpec(t *testing.T) {
h, err := master.New(master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir()})
if err != nil {
t.Fatal(err)
}
defer func() {
h.Start()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = h.Close(ctx)
}()
intent := func(id string) lifecycle.PlacementIntent {
return lifecycle.PlacementIntent{VolumeID: id, DesiredRF: 1, Slots: []lifecycle.PlacementSlotIntent{{ServerID: "s1", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}
}
if err := importLifecyclePlacementIntents(h, []lifecycle.PlacementIntent{intent("unused"), intent("kept")}); err != nil {
t.Fatal(err)
}
// The next import is the complete desired spec; neither volume has been
// created, assigned, bound, or queued because this host has not started.
if err := importLifecyclePlacementIntents(h, []lifecycle.PlacementIntent{intent("kept")}); err != nil {
t.Fatal(err)
}
if err := h.PruneUnusedSpecPlacements(context.Background(), []string{"kept"}); err != nil {
t.Fatal(err)
}
if _, ok := h.Lifecycle().Placements.GetPlacement("unused"); ok {
t.Fatal("spec-removed unused restore target still has its placement")
}
if _, ok := h.Lifecycle().Placements.GetPlacement("kept"); !ok {
t.Fatal("current spec placement was removed")
}
}
func TestClusterSpecCleanupKeepsRecordsBindingsAuthorityAndSeed(t *testing.T) {
ctx := context.Background()
dir := t.TempDir()
disk, err := authority.NewFileAuthorityStore(dir)
if err != nil {
t.Fatal(err)
}
if err := disk.Put(authority.DurableRecord{VolumeID: "line", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, WriteSeq: 1, DataAddr: "127.0.0.1:19001", CtrlAddr: "127.0.0.1:19002"}); err != nil {
t.Fatal(err)
}
_ = disk.Close()
h, err := master.New(master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: dir, LifecycleStoreDir: t.TempDir()})
if err != nil {
t.Fatal(err)
}
defer func() {
h.Start()
closeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
_ = h.Close(closeCtx)
}()
var intents []lifecycle.PlacementIntent
for _, id := range []string{"line", "record", "bound", "reserved", "spec", "seed", "unused"} {
intents = append(intents, lifecycle.PlacementIntent{VolumeID: id, DesiredRF: 1, Slots: []lifecycle.PlacementSlotIntent{{ServerID: "s1", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}})
}
if err := importLifecyclePlacementIntents(h, intents); err != nil {
t.Fatal(err)
}
if _, err := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "record", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
t.Fatal(err)
}
if err := h.Lifecycle().WorkspaceBindings.Register(lifecycle.WorkspaceBinding{VolumeID: "bound", ServerID: "s1", DataAddr: "127.0.0.1:19011", CtrlAddr: "127.0.0.1:19012"}); err != nil {
t.Fatal(err)
}
if _, err := h.Lifecycle().Deletions.Admit("reserved", "delete"); err != nil {
t.Fatal(err)
}
if _, err := h.Lifecycle().Deletions.Commit("reserved", "delete"); err != nil {
t.Fatal(err)
}
if err := h.PruneUnusedSpecPlacements(ctx, []string{"spec", "seed"}); err != nil {
t.Fatal(err)
}
for _, id := range []string{"line", "record", "bound", "reserved", "spec", "seed"} {
if _, ok := h.Lifecycle().Placements.GetPlacement(id); !ok {
t.Errorf("removed %s which still holds work or remains desired", id)
}
}
if _, ok := h.Lifecycle().Placements.GetPlacement("unused"); ok {
t.Fatal("unused placement remains")
}
if !h.Lifecycle().Deletions.CommittedSnapshot("reserved") {
t.Fatal("committed tombstone lost")
}
}
// The subprocess executes run(): it loads both actual files, imports, prunes,
// and reaches ready before we reopen the persisted placement store.
func TestClusterSpecStartupPrunesParsedSpecAndSeedUnion(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Linux daemon signals and lifecycle directory fsync")
}
for _, mode := range []string{"spec-and-seed", "empty-spec", "no-spec"} {
t.Run(mode, func(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, "lifecycle", "placements")
store, err := lifecycle.OpenPlacementIntentStore(dir)
if err != nil {
t.Fatal(err)
}
intent := func(id string) lifecycle.PlacementIntent {
return lifecycle.PlacementIntent{VolumeID: id, DesiredRF: 1, Slots: []lifecycle.PlacementSlotIntent{{ServerID: "s1", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}
}
if _, err := store.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "unused", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: "unused", ServerID: "s1", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
spec := filepath.Join(root, "spec.yaml")
text := "nodes:\n - server_id: s1\n data_addr: 127.0.0.1:9201\n ctrl_addr: 127.0.0.1:9202\nvolumes: []\n"
if mode == "spec-and-seed" {
text = strings.Replace(text, "volumes: []", "volumes:\n - id: spec\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: r1", 1)
}
if err := os.WriteFile(spec, []byte(text), 0600); err != nil {
t.Fatal(err)
}
extra := []string{"--lifecycle-product-loop-interval", "0"}
if mode == "spec-and-seed" {
seed := filepath.Join(root, "seed.json")
raw, err := json.Marshal([]lifecycle.PlacementIntent{intent("seed")})
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(seed, raw, 0600); err != nil {
t.Fatal(err)
}
extra = append(extra, "--lifecycle-placement-seed", seed)
}
if mode == "no-spec" {
topo := filepath.Join(root, "topology.yaml")
if err := os.WriteFile(topo, []byte("volumes:\n - volume_id: other\n slots:\n - replica_id: r1\n server_id: s1\n"), 0600); err != nil {
t.Fatal(err)
}
extra = append(extra, "--cluster-spec", "", "--topology", topo)
}
daemon := startClusterImportCLI(t, root, spec, extra...)
daemon.stop()
reloaded, err := lifecycle.OpenPlacementIntentStore(dir)
if err != nil {
t.Fatal(err)
}
_, kept := reloaded.GetPlacement("unused")
if kept != (mode == "no-spec") {
t.Fatalf("unused placement kept=%t mode=%s", kept, mode)
}
if mode == "spec-and-seed" {
for _, id := range []string{"spec", "seed"} {
if _, ok := reloaded.GetPlacement(id); !ok {
t.Fatalf("parsed %s was pruned", id)
}
}
}
})
}
}
@@ -45,14 +45,13 @@ type clusterImportProcess struct {
stop func()
}
func startClusterImportCLI(t *testing.T, root, spec string, extra ...string) *clusterImportProcess {
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"}
args = append(args, extra...)
argsPath := filepath.Join(tmp, "args.json")
data, _ := json.Marshal(args)
if e := os.WriteFile(argsPath, data, 0600); e != nil {
+7 -51
View File
@@ -127,7 +127,7 @@ func parseFlags(args []string) (flags, error) {
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, "name the source PVC (namespace, name, uid) in annotations on generated blockvolume Deployments; they stay in --launcher-namespace with their node TLS Secret, and the launcher removes them when the volume is gone")
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")
@@ -212,25 +212,9 @@ func parseFlags(args []string) (flags, error) {
if f.launcherExternalISCSI && f.launcherCHAPSecretName == "" {
return flags{}, fmt.Errorf("cannot enable --launcher-external-iscsi without --launcher-iscsi-chap-secret-name")
}
if err := productLoopWithinFreshness(f.lifecycleLoop, f.freshnessWindow); err != nil {
return flags{}, err
}
return f, nil
}
// productLoopWithinFreshness refuses a product-loop interval of more than
// half the freshness window: the promotion gate reads a loop gap longer than
// the window as the master's own pause and restarts every primary's silence
// clock, so with such an interval every tick would read as a pause and a
// dead primary would never be replaced.
func productLoopWithinFreshness(loop, freshness time.Duration) error {
window := authority.FreshnessConfig{FreshnessWindow: freshness}.EffectiveFreshnessWindow()
if loop > 0 && loop > window/2 {
return fmt.Errorf("--lifecycle-product-loop-interval %v is more than half of --freshness-window %v: every product-loop tick would read as the master's own pause, and a dead primary would never be replaced; set the interval to at most %v", loop, window, window/2)
}
return nil
}
func main() {
f, err := parseFlags(os.Args[1:])
if err != nil {
@@ -274,7 +258,6 @@ func run(f flags) int {
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{
EphemeralLauncherState: (f.launcherManifestDir != "" || f.launcherKubernetesApply) && f.launcherStateHostPath == "",
AuthorityStoreDir: f.authorityStore,
LifecycleStoreDir: f.lifecycleStore,
Listen: f.listen,
@@ -363,38 +346,14 @@ func run(f flags) int {
return 1
}
}
var seedPlacements []lifecycle.PlacementIntent
if f.lifecyclePlacementSeed != "" {
var err error
seedPlacements, err = importLifecyclePlacementSeed(h, f.lifecyclePlacementSeed)
if err != nil {
if err := importLifecyclePlacementSeed(h, f.lifecyclePlacementSeed); err != nil {
fmt.Fprintln(os.Stderr, "blockmaster:", err)
_ = h.Close(context.Background())
return 1
}
}
if f.clusterSpec != "" {
var desired []string
for _, p := range clusterImport.Placements {
desired = append(desired, p.VolumeID)
}
for _, p := range seedPlacements {
desired = append(desired, p.VolumeID)
}
if err := h.PruneUnusedSpecPlacements(context.Background(), desired); err != nil {
fmt.Fprintln(os.Stderr, "blockmaster:", err)
_ = h.Close(context.Background())
return 1
}
}
if err := h.ReconcileDeletedSpecVolumes(context.Background()); 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",
@@ -486,23 +445,20 @@ func importLifecycleNodeInventory(h *master.Host, nodes []lifecycle.NodeRegistra
return nil
}
func importLifecyclePlacementSeed(h *master.Host, path string) ([]lifecycle.PlacementIntent, error) {
func importLifecyclePlacementSeed(h *master.Host, path string) error {
stores := h.Lifecycle()
if stores == nil {
return nil, fmt.Errorf("--lifecycle-placement-seed requires --lifecycle-store")
return fmt.Errorf("--lifecycle-placement-seed requires --lifecycle-store")
}
raw, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read lifecycle placement seed %q: %w", path, err)
return fmt.Errorf("read lifecycle placement seed %q: %w", path, err)
}
var intents []lifecycle.PlacementIntent
if err := json.Unmarshal(raw, &intents); err != nil {
return nil, fmt.Errorf("parse lifecycle placement seed %q: %w", path, err)
return fmt.Errorf("parse lifecycle placement seed %q: %w", path, err)
}
if err := importLifecyclePlacementIntents(h, intents); err != nil {
return nil, err
}
return intents, nil
return importLifecyclePlacementIntents(h, intents)
}
func importLifecyclePlacementIntents(h *master.Host, intents []lifecycle.PlacementIntent) error {
@@ -1,28 +0,0 @@
package main
import (
"strings"
"testing"
)
// blockmaster refuses a product-loop interval of more than half the
// freshness window (every tick would read as the master's own pause, and a
// dead primary would never be replaced), typed, before it starts. Half the
// window exactly, the shipped interval and a disabled loop start.
func TestBlockmasterRefusesALoopIntervalAboveHalfTheFreshnessWindow(t *testing.T) {
refused := []string{"--lifecycle-product-loop-interval=20s", "--freshness-window=30s"}
_, err := parseFlags(append([]string{"--authority-store", t.TempDir()}, refused...))
if err == nil || !strings.Contains(err.Error(), "--lifecycle-product-loop-interval 20s is more than half of --freshness-window 30s") {
t.Fatalf("interval 20 s with window 30 s: %v; want the refusal naming both", err)
}
for _, ok := range [][]string{
{"--lifecycle-product-loop-interval=15s", "--freshness-window=30s"}, // half exactly
{"--lifecycle-product-loop-interval=100ms"}, // the shipped interval, default window
{}, // the loop off (default)
{"--lifecycle-product-loop-interval=30s", "--freshness-window=60s"},
} {
if _, err := parseFlags(append([]string{"--authority-store", t.TempDir()}, ok...)); err != nil {
t.Fatalf("%v: %v; want accepted", ok, err)
}
}
}
@@ -85,7 +85,7 @@ func TestDefaultConfigCleansAfterEachSnapshotDelete(t *testing.T) {
}
}
name := fmt.Sprintf("s%d", round)
if _, err := dp.SnapshotVolume(ctx, "v1", name, layout.SnapshotMeta{}); err != nil {
if _, err := ctl.Snapshot(ctx, "v1", volume.ChunkSnapshotRequest{Name: name}); err != nil {
t.Fatalf("round %d: snapshot: %v", round, err)
}
if prev != "" {
@@ -22,10 +22,7 @@ import (
// 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). blockmaster
// refuses an interval above half the freshness window (a longer loop gap
// reads as the master's own pause), so the window is 60 s: the dead
// primary's loss then comes at most a window after its last report.
// 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}
@@ -49,7 +46,7 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
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", "60s", "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
"--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"
@@ -1,253 +0,0 @@
package main
import (
"bytes"
"context"
"errors"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"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"
)
// storeRecordMaster answers only LifecycleService.GetReplicaStore, by mode.
type storeRecordMaster struct {
control.UnimplementedLifecycleServiceServer
mu sync.Mutex
mode string // "creating", "ended", "older", "unreadable", "unavailable"
}
func (m *storeRecordMaster) set(mode string) { m.mu.Lock(); m.mode = mode; m.mu.Unlock() }
func (m *storeRecordMaster) GetReplicaStore(_ context.Context, q *control.GetReplicaStoreRequest) (*control.GetReplicaStoreResponse, error) {
m.mu.Lock()
defer m.mu.Unlock()
switch m.mode {
case "creating":
return &control.GetReplicaStoreResponse{Listed: true}, nil
case "ended": // a recorded store that is never the one on disk here
return &control.GetReplicaStoreResponse{Listed: true, CreationEnded: true, StoreId: bytes.Repeat([]byte{0xab}, 16)}, nil
case "ended-unrecorded": // creation ended, no store recorded for this replica
return &control.GetReplicaStoreResponse{Listed: true, CreationEnded: true}, nil
case "older":
return nil, status.Error(codes.Unimplemented, "unknown method GetReplicaStore")
case "unreadable":
return nil, status.Error(codes.FailedPrecondition, "the replica's store record is unreadable")
}
return nil, status.Error(codes.Unavailable, "lifecycle store unavailable")
}
// killAndJoin kills the holder and waits for it, bounded: a process that
// cannot be joined stops the test binary (no fixture cleanup or later test
// runs beside it), so the output is only read after a proven wait.
func killAndJoin(cmd *exec.Cmd, done <-chan error) {
_ = cmd.Process.Kill()
select {
case <-done:
case <-time.After(30 * time.Second):
fmt.Fprintln(os.Stderr, "FAIL: the killed blockvolume did not exit within 30 s; stopping the test binary")
os.Exit(1)
}
}
// runHolder starts the blockvolume binary and returns its exit (nil error and
// running=true when it was still running at the deadline and was killed);
// output is read only after the process has been waited for.
func runHolder(t *testing.T, bin, master, root, locks string, until func() bool, limit time.Duration) (exit int, running bool, out string) {
t.Helper()
var buf bytes.Buffer
cmd := exec.Command(bin, "--master", master, "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1",
"--data-addr", "127.0.0.1:0", "--ctrl-addr", "127.0.0.1:0", "--durable-root", root, "--durable-impl", "walstore",
"--durable-blocks", "64", "--"+volumeLockDirTestOnlyFlag, locks)
cmd.Stdout, cmd.Stderr = &buf, &buf
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
deadline := time.After(limit)
tick := time.NewTicker(50 * time.Millisecond)
defer tick.Stop()
for {
select {
case err := <-done:
var ee *exec.ExitError
if errors.As(err, &ee) {
return ee.ExitCode(), false, buf.String()
}
return 0, false, buf.String()
case <-tick.C:
if until != nil && until() {
killAndJoin(cmd, done)
return 0, true, buf.String()
}
case <-deadline:
killAndJoin(cmd, done)
return 0, true, buf.String()
}
}
}
// A plain walstore holder asks the master for its replica's store record
// before it creates or writes anything. Composed on the real binary: while
// the volume is creating an empty state directory creates the store; once
// creation ended, a store other than the recorded one, and a wiped state
// directory, exit 78 store_lost; an older master (no GetReplicaStore) and an
// unreadable record exit 75 with an empty state directory left empty. A
// master that gives no reply is waited out inside the process, writing
// nothing, so a start during an outage does not burn the unit's start limit;
// once it answers creating, the same process creates its store.
func TestBlockvolumeAsksTheMasterBeforeCreatingItsStore(t *testing.T) {
if testing.Short() {
t.Skip("builds and runs the blockvolume binary")
}
dir := t.TempDir()
bin := filepath.Join(dir, "blockvolume")
if runtime.GOOS == "windows" {
bin += ".exe"
}
// The build writes to a file, so its exit is its whole join (no pipe
// copy outlives it). A build that does not finish in time stops the test
// binary before the temporary output is removed: go build's own children
// may still be writing there.
buildLog, err := os.Create(filepath.Join(dir, "build.log"))
if err != nil {
t.Fatal(err)
}
build := exec.Command("go", "build", "-o", bin, "github.com/seaweedfs/seaweed-block/cmd/blockvolume")
build.Stdout, build.Stderr = buildLog, buildLog
if err := build.Start(); err != nil {
t.Fatal(err)
}
built := make(chan error, 1)
go func() { built <- build.Wait() }()
select {
case err := <-built:
_ = buildLog.Close()
if err != nil {
out, _ := os.ReadFile(buildLog.Name())
t.Fatalf("build: %v\n%s", err, out)
}
case <-time.After(5 * time.Minute):
_ = build.Process.Kill()
fmt.Fprintln(os.Stderr, "FAIL: go build of blockvolume did not finish within 5 min; stopping the test binary before its temporary output is removed")
os.Exit(1)
}
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
m := &storeRecordMaster{}
srv := grpc.NewServer()
control.RegisterLifecycleServiceServer(srv, m)
go func() { _ = srv.Serve(ln) }()
defer srv.Stop()
root, locks := t.TempDir(), t.TempDir()
store := filepath.Join(root, "v1.bin")
empty := func(t *testing.T) {
t.Helper()
if entries, err := os.ReadDir(root); err != nil || len(entries) != 0 {
t.Fatalf("the refused holder wrote into its state directory: %v %v", entries, err)
}
}
m.set("creating")
created := func() bool { _, err := os.Stat(store); return err == nil }
if _, running, out := runHolder(t, bin, ln.Addr().String(), root, locks, created, 60*time.Second); !running || !created() {
t.Fatalf("a creating volume did not create its store:\n%s", out)
}
m.set("ended") // the store here is not the recorded one
if code, _, out := runHolder(t, bin, ln.Addr().String(), root, locks, nil, 60*time.Second); code != exitWorkspaceSuperseded || !strings.Contains(out, "store_lost") {
t.Fatalf("a store other than the recorded one: exit %d\n%s", code, out)
}
if err := os.RemoveAll(root); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(root, 0o755); err != nil {
t.Fatal(err)
}
if code, _, out := runHolder(t, bin, ln.Addr().String(), root, locks, nil, 60*time.Second); code != exitWorkspaceSuperseded || !strings.Contains(out, "store_lost") {
t.Fatalf("a wiped state directory after creation ended: exit %d\n%s", code, out)
}
empty(t)
m.set("ended-unrecorded") // no attestation for this replica: creation ended is what counts
if code, _, out := runHolder(t, bin, ln.Addr().String(), root, locks, nil, 60*time.Second); code != exitWorkspaceSuperseded || !strings.Contains(out, "store_lost") {
t.Fatalf("a wiped state directory, creation ended with no recorded store: exit %d\n%s", code, out)
}
empty(t)
for mode, reason := range map[string]string{"older": "master_too_old", "unreadable": "store_record_unreadable"} {
m.set(mode)
if code, _, out := runHolder(t, bin, ln.Addr().String(), root, locks, nil, 60*time.Second); code != exitWorkspaceRetry || !strings.Contains(out, reason) {
t.Fatalf("%s master, empty state: exit %d, want 75 %s\n%s", mode, code, reason, out)
}
empty(t)
}
// No reply for longer than the old 10 s read bound plus the unit's 5 s
// restart delay: the process stays, writes nothing, and creates its
// store once the master answers creating.
m.set("unavailable")
start, answered := time.Now(), false
answer := func() bool {
if !answered && time.Since(start) > 25*time.Second {
if entries, err := os.ReadDir(root); err != nil || len(entries) != 0 {
t.Errorf("the waiting holder wrote into its state directory: %v %v", entries, err)
}
m.set("creating")
answered = true
}
return created()
}
if code, running, out := runHolder(t, bin, ln.Addr().String(), root, locks, answer, 90*time.Second); !running || !created() || !strings.Contains(out, "waiting for the master at "+ln.Addr().String()) {
t.Fatalf("a master with no reply, then creating: exit %d running %v created %v\n%s", code, running, created(), out)
}
// A stop during the wait is a clean stop: exit 0, nothing created.
if runtime.GOOS == "windows" {
return // no SIGTERM to another process
}
if err := os.RemoveAll(root); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(root, 0o755); err != nil {
t.Fatal(err)
}
m.set("unavailable")
var buf bytes.Buffer
cmd := exec.Command(bin, "--master", ln.Addr().String(), "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1",
"--data-addr", "127.0.0.1:0", "--ctrl-addr", "127.0.0.1:0", "--durable-root", root, "--durable-impl", "walstore",
"--durable-blocks", "64", "--"+volumeLockDirTestOnlyFlag, locks)
cmd.Stdout, cmd.Stderr = &buf, &buf
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
time.Sleep(5 * time.Second)
_ = cmd.Process.Signal(syscall.SIGTERM)
select {
case err := <-done:
if err != nil || !strings.Contains(buf.String(), "stopped while waiting for the master") {
t.Fatalf("SIGTERM during the wait: %v\n%s", err, buf.String())
}
case <-time.After(30 * time.Second):
killAndJoin(cmd, done)
t.Fatalf("SIGTERM did not end the wait\n%s", buf.String())
}
empty(t)
}
-39
View File
@@ -17,7 +17,6 @@ import (
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
@@ -924,41 +923,6 @@ func runVolume(f flags, exits *processExit) int {
// 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 && f.durableImpl != "walstore-chunk" {
// A plain walstore store is the volume's only copy: ask the master
// before anything is created or written (GetReplicaStore).
var storeWait atomic.Bool
if status != nil {
status.SetStartupWait(storeWait.Load)
}
rec, qerr := readReplicaStore(exits.parent, f.masterAddr, h.ReplicaStoreRecord, log.Printf, storeWait.Store)
if exits.parent.Err() != nil {
// Stopped while waiting for the master: nothing was opened or
// created, and a stop is not a failure.
fmt.Fprintln(os.Stderr, "blockvolume: stopped while waiting for the master's store record; nothing was created")
_ = closeProviderAfterSnapshotOperations(status, dp.Close)
if status != nil {
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = status.Close(shutCtx)
shutCancel()
}
_ = h.Close()
return 0
}
admission, refuse := decideStoreAdmission(rec, qerr, exists)
if refuse != nil {
fmt.Fprintln(os.Stderr, "blockvolume: durable storage open refused:", refuse.reason, refuse.detail)
_ = closeProviderAfterSnapshotOperations(status, dp.Close)
if status != nil {
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = status.Close(shutCtx)
shutCancel()
}
_ = h.Close()
return reportWorkspaceExit(*refuse)
}
dp.ExpectStore(admission.mustExist, admission.id)
}
if xErr == nil && !exists {
xErr = transport.InitReplicaFloor(replicaFloorPath(f), f.volumeID)
}
@@ -989,9 +953,6 @@ func runVolume(f flags, exits *processExit) int {
}
_ = h.Close()
code, reason := durableOpenFatalExit(sErr)
if reason == "store_lost" {
return reportWorkspaceExit(workspaceExit{code: code, reason: reason, detail: lostStoreDetail})
}
if reason != "" {
return reportWorkspaceExit(workspaceExit{code: code, reason: reason, detail: "the local store was written by a newer version: run a newer binary"})
}
@@ -1,158 +0,0 @@
package main
import (
"bytes"
"context"
"path"
"strings"
"sync"
"testing"
"testing/synctest"
"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"
"github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil"
)
type progressingPreparationFiler struct {
chunkstore.Filer
mu sync.Mutex
enabled bool
seen map[string]bool
removeDelay time.Duration
prepStart, prepEnd, removeStart, removeEnd time.Time
}
func (f *progressingPreparationFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
f.mu.Lock()
key := path.Join(dir, name)
delay := f.enabled && strings.Contains(dir, "/pool/") && !f.seen[key]
if delay {
f.seen[key] = true
if f.prepStart.IsZero() {
f.prepStart = time.Now()
}
}
f.mu.Unlock()
if delay {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(15 * time.Second):
}
}
entry, err := f.Filer.LookupEntry(ctx, dir, name)
if delay && err == nil {
f.mu.Lock()
f.prepEnd = time.Now()
f.mu.Unlock()
}
return entry, err
}
func (f *progressingPreparationFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
delay := f.removeDelay
slow := delay > 0 && strings.Contains(dir, "/pool/")
if slow {
f.mu.Lock()
if f.removeStart.IsZero() {
f.removeStart = time.Now()
}
f.mu.Unlock()
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(delay):
}
}
err := f.Filer.DeleteEntry(ctx, dir, name, expected)
if slow && err == nil {
f.mu.Lock()
f.removeEnd = time.Now()
f.mu.Unlock()
}
return err
}
// A real callback, catalog sweep and provider status cross the old total bound.
func TestRealMaintenanceProgressingPastOneMinuteCompletes(t *testing.T) {
testRealMaintenanceProgress(t, 0)
}
func TestRealMaintenancePreparationAndRemovalEachOutliveWindow(t *testing.T) {
testRealMaintenanceProgress(t, 500*time.Millisecond)
}
func testRealMaintenanceProgress(t *testing.T, removeDelay time.Duration) {
t.Helper()
synctest.Test(t, func(t *testing.T) {
ctx := context.Background()
fixture := testutil.NewLayoutFixture(t, "v1", 4096, 16)
cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 4096, ChunkBlocks: 16, ChunkMaintenanceInterval: time.Hour, ChunkMaintenanceTimeout: time.Minute, ChunkStagger: true}
fixture.Configure(&cfg)
slow := &progressingPreparationFiler{Filer: fixture.Filer, seen: map[string]bool{}, removeDelay: removeDelay}
cat, err := chunkstore.NewBCatalog(slow, fixture.Blobs, "/provider-test")
if err != nil {
t.Fatal(err)
}
var p *durable.DurableProvider
cfg.ChunkMaintenance = newChunkMaintenance(cat, fixture.Ref, func(ctx context.Context) (layoutCleaner, error) {
r, e := p.LayoutRemote(ctx, "v1")
if e != nil {
return nil, e
}
return r.(layoutCleaner), nil
}, true, time.Now)
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)
}
st, err := cat.Store(fixture.Ref)
if err != nil {
t.Fatal(err)
}
if err = fixture.Filer.CreateEntry(ctx, path.Join("/provider-test", fixture.Ref.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); err != nil {
t.Fatal(err)
}
for i := uint64(0); i < 192; i++ {
data := bytes.Repeat([]byte{byte(i + 1)}, 4096)
n := layout.NameChunk(i, data)
if err = layout.EnsureObject(ctx, st, n.Path(), data, "ended"); err != nil {
t.Fatal(err)
}
}
slow.mu.Lock()
slow.enabled = true
slow.mu.Unlock()
if !p.KickMaintenance("v1") {
t.Fatal("kick refused")
}
time.Sleep(95*time.Second + 192*removeDelay)
synctest.Wait()
m := maintenanceJSON(t, p)
if m["passesOk"] != float64(1) {
t.Fatalf("real progressing sweep failed to complete: %v", m)
}
slow.mu.Lock()
prep, removal := slow.prepEnd.Sub(slow.prepStart), slow.removeEnd.Sub(slow.removeStart)
slow.mu.Unlock()
t.Logf("completed phases: preparation=%v removal=%v window=1m", prep, removal)
if prep <= time.Minute || removeDelay > 0 && removal <= time.Minute {
t.Fatalf("fixture did not cross both phase windows: preparation=%v removal=%v", prep, removal)
}
last := m["lastPass"].(map[string]any)
if last["removedChunks"] != float64(192) || last["processed"].(float64) < 192 || last["error"] != "" {
t.Fatalf("real sweep counts: %v", last)
}
})
}
@@ -280,13 +280,7 @@ func TestMaintenanceStatusRealPassAndTimeout(t *testing.T) {
} else if last["error"] != "" || last["headGenError"] != "" {
t.Fatalf("unexpected error: %v", last)
}
// Initial admission closes before enumeration, then roots, segments
// and (unless metadata-only) chunks each have their own begin/end.
pages := uint64(3)
if kind == "metadata-only" {
pages = 2
}
if after.Gen != before.Gen+2+2*pages || m["passesOk"] != float64(1) || last["headGen"].(float64) != float64(expectedGen) {
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)
+1 -18
View File
@@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"io"
"os"
"os/signal"
"sync"
@@ -137,11 +136,6 @@ func reportWorkspaceExit(out workspaceExit) int {
return out.code
}
// lostStoreDetail is store_lost's cure: the volume's creation ended with a
// store this host no longer has (a wiped or missing state directory, or a
// re-created store), and a walstore volume has no other copy here.
const lostStoreDetail = "this replica's local store is missing or was re-created; its data is not on this host: restore it from a replica or a backup (an operator's call); a fresh empty store is never served"
// 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
@@ -151,9 +145,6 @@ func durableOpenFatalExit(err error) (int, string) {
if errors.Is(err, storage.ErrStoreFormatNewer) {
return exitWorkspaceSuperseded, "store_format_newer"
}
if errors.Is(err, durable.ErrLostStore) {
return exitWorkspaceSuperseded, "store_lost"
}
return 1, ""
}
@@ -245,9 +236,6 @@ func waitWorkspaceStop(e *processExit, f flags, h *volume.Host, requests <-chan
// 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.
// closeoutLog receives the closeout's failure lines (os.Stderr; tests replace it).
var closeoutLog io.Writer = os.Stderr
func finishWorkspaceLease(e *processExit, f flags, h *volume.Host, done <-chan error) {
if done == nil {
return
@@ -258,12 +246,7 @@ func finishWorkspaceLease(e *processExit, f flags, h *volume.Host, done <-chan e
e.choose(workspaceExit{reason: "revoked"})
return
}
// A signal stopped the process: the lease worker's stop request ended
// with it (run's own shutdown closes the volume), so a cancelled stop is
// expected, not a closeout failure; the exit keeps the signal status.
if !(e.parent.Err() != nil && errors.Is(err, context.Canceled)) {
fmt.Fprintln(closeoutLog, "blockvolume: workspace lease closeout:", err)
}
fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout:", err)
case <-time.After(workspaceLeaseCloseoutTimeout):
fmt.Fprintln(os.Stderr, "blockvolume: workspace lease closeout deadline")
}
@@ -1,46 +0,0 @@
package main
import (
"bytes"
"context"
"errors"
"fmt"
"strings"
"testing"
)
// A clean stop (a signal) ends the lease worker's stop request with the
// process: its cancelled stop is not a closeout failure and prints none,
// and the exit stays the signal's. Control: any other closeout error, and
// a cancelled stop without a signal, still print the closeout line.
func TestACleanStopLogsNoCancelledCloseout(t *testing.T) {
var log bytes.Buffer
old := closeoutLog
closeoutLog = &log
t.Cleanup(func() { closeoutLog = old })
cancelled := fmt.Errorf("workspace lease fenced (revoked): stop failed: %w", context.Canceled)
run := func(signal bool, err error) workspaceExit {
log.Reset()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
e := newProcessExit(ctx)
if signal {
cancel()
}
done := make(chan error, 1)
done <- err
finishWorkspaceLease(e, flags{}, nil, done)
return <-e.decision
}
if out := run(true, cancelled); log.Len() != 0 || out.reason != "signal" {
t.Fatalf("signal + cancelled stop: logged %q, exit %+v; want no line and reason signal", log.String(), out)
}
if run(true, errors.New("ack refused")); !strings.Contains(log.String(), "blockvolume: workspace lease closeout: ack refused") {
t.Fatalf("signal + another error: logged %q; want the closeout line", log.String())
}
if run(false, cancelled); !strings.Contains(log.String(), "blockvolume: workspace lease closeout:") {
t.Fatalf("no signal + cancelled stop: logged %q; want the closeout line", log.String())
}
}
@@ -1,147 +0,0 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
)
// TestRF1HolderOnAWipedStateDirectoryRefusesStoreLost: the real RF1 path,
// composed on the production binaries with no state seeded.
//
// 1. blockmaster binds v1 to its one replica; the holder creates its store,
// the master records it, and the holder serves.
// 2. Block A is written and flushed (acknowledged) and reads back.
// 3. The holder is killed, its state directory wiped, and it is restarted.
// 4. It exits 78 store_lost and writes nothing into its state directory: it
// never comes up on a fresh empty store, which would read A as zeros.
//
// The binaries are built with a bound (an overrun stops the test binary),
// and every child is killed and joined on every exit path: a child whose
// join does not finish stops the test binary before the fixtures are
// removed.
func TestRF1HolderOnAWipedStateDirectoryRefusesStoreLost(t *testing.T) {
bins := buildRF1Binaries(t)
h := &plannedHandoffHarness{dir: t.TempDir(), t: t}
var children []*daemon
// Registered after the fixture directory and before any child, so it runs
// after every child's own cleanup and before the fixtures are removed. A
// child whose join did not finish (the harness's reap ceiling only skips)
// stops the test binary here.
t.Cleanup(func() {
for _, d := range children {
select {
case <-d.done:
default:
fmt.Fprintln(os.Stderr, "FAIL:", d.name, "was not joined; stopping the test binary before its fixtures are removed")
os.Exit(1)
}
}
})
h.masterAddr = handoffAddress(t)
data, ctrl, status, nvme := handoffAddress(t), handoffAddress(t), handoffAddress(t), handoffAddress(t)
root := filepath.Join(h.dir, "vol-s1")
spec := filepath.Join(h.dir, "cluster-spec.yaml")
if err := os.WriteFile(spec, []byte("nodes:\n - server_id: s1\n data_addr: "+data+"\n ctrl_addr: "+ctrl+
"\nvolumes:\n - id: v1\n size_bytes: 268435456\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: r1\n"), 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", "1", "--lifecycle-product-loop-interval", "200ms", "--listen", h.masterAddr)
children = append(children, master)
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired")
lockDir := root + ".locks"
if err := os.MkdirAll(lockDir, 0o700); err != nil {
t.Fatal(err)
}
args := []string{"--volume-lock-dir-test-only", lockDir, "--master", h.masterAddr, "--server-id", "s1", "--volume-id", "v1",
"--replica-id", "r1", "--data-addr", data, "--ctrl-addr", ctrl, "--status-addr", status,
"--durable-root", root, "--durable-impl", "walstore", "--durable-blocks", "65536", "--durable-blocksize", "4096",
"--heartbeat-interval", "200ms", "--t1-readiness", "--nvme-listen", nvme, "--nvme-subsysnqn", plannedHandoffNQN}
first := h.start(t, "blockvolume-s1", bins.volume, args...)
children = append(children, first)
// 1-2. It serves (only once the master recorded its store) and A is
// acknowledged.
h.waitPrimaryAt(t, status, 1)
acked := bytes.Repeat([]byte{0xa1}, 4096)
c := dialNVMe(t, nvme, plannedHandoffNQN)
c.write(t, 0, acked)
c.flush(t) // the acknowledgement
if got := c.read(t, 0, len(acked)); !bytes.Equal(got, acked) {
t.Fatal("block A did not read back before the wipe")
}
c.close()
// 3. Killed, wiped, restarted.
first.kill(t)
if err := os.RemoveAll(root); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(root, 0o755); err != nil {
t.Fatal(err)
}
wiped := h.start(t, "blockvolume-s1-wiped", bins.volume, args...)
children = append(children, wiped)
// 4. It refuses and writes nothing.
err := wiped.wait(60 * time.Second)
var ee *exec.ExitError
if !errors.As(err, &ee) || ee.ExitCode() != 78 || !wiped.has("store_lost") {
t.Fatalf("the restart on a wiped state directory: %v, want exit 78 store_lost\n%s", err, wiped.tail(40))
}
if entries, err := os.ReadDir(root); err != nil || len(entries) != 0 {
t.Fatalf("the refused holder wrote into its state directory: %v %v", entries, err)
}
}
// buildRF1Binaries builds blockmaster and blockvolume like buildG54Binaries,
// bounded: each build writes to a file (its exit is its whole join), and one
// that does not finish in 5 minutes stops the test binary before the output
// directory is removed (go build's own children may still write there).
func buildRF1Binaries(t *testing.T) l2bins {
t.Helper()
dir := t.TempDir()
suf := ""
if isWindows() {
suf = ".exe"
}
bins := l2bins{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", bins.master},
{"github.com/seaweedfs/seaweed-block/cmd/blockvolume", bins.volume},
} {
log, err := os.Create(b.out + ".build.log")
if err != nil {
t.Fatal(err)
}
cmd := exec.Command("go", "build", "-o", b.out, b.pkg)
cmd.Stdout, cmd.Stderr = log, log
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
built := make(chan error, 1)
go func() { built <- cmd.Wait() }()
select {
case err := <-built:
_ = log.Close()
if err != nil {
out, _ := os.ReadFile(log.Name())
t.Fatalf("build %s: %v: %s", b.pkg, err, out)
}
case <-time.After(5 * time.Minute):
_ = cmd.Process.Kill()
fmt.Fprintln(os.Stderr, "FAIL: go build", b.pkg, "did not finish within 5 min; stopping the test binary before its output is removed")
os.Exit(1)
}
}
return bins
}
@@ -1,124 +0,0 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
// TestRF3WipedPrimaryRefusesAndASurvivorServesItsData: the line's primary of
// an RF3 volume is answered from its own store record, never as a replica
// rebuilt from its peers. Through the production binaries:
//
// 1. r1 serves at epoch 1; block A is written and flushed (acknowledged).
// 2. r1 is killed, its state directory wiped, and it is restarted while it
// still holds the line (inside the freshness window).
// 3. r1 exits 78 store_lost and writes nothing into its state directory:
// it never serves its empty store.
// 4. The gate fails over to a survivor at epoch 2, and A reads back there.
func TestRF3WipedPrimaryRefusesAndASurvivorServesItsData(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)
}
// A 10 s freshness window: the wiped primary's restart (step 2) asks the
// master while it still holds the line.
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", "10s", "--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...)
}
p1, survivors := hosts[0], hosts[1:]
// 1. r1 serves with both replicas healthy; A is acknowledged, and the
// gate has seen both survivors ready on the stores r1 attested.
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()
poll(t, 60*time.Second, "the gate never saw r2 and r3 ready behind r1", func() bool {
data, _ := os.ReadFile(master.log)
for _, l := range strings.Split(string(data), "\n") {
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. r1 is killed, wiped and restarted while it still holds the line.
p1.d.kill(t)
if err := os.RemoveAll(p1.root); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(p1.root, 0o755); err != nil {
t.Fatal(err)
}
p1.d = h.start(t, "blockvolume-"+p1.id+"-wiped", bins.volume, p1.args...)
// 3. It refuses: exit 78 store_lost, nothing written.
err := p1.d.wait(60 * time.Second)
var ee *exec.ExitError
if !errors.As(err, &ee) || ee.ExitCode() != 78 || !p1.d.has("store_lost") {
t.Fatalf("the wiped primary's restart: %v, want exit 78 store_lost\n%s", err, p1.d.tail(40))
}
if entries, err := os.ReadDir(p1.root); err != nil || len(entries) != 0 {
t.Fatalf("the refused primary wrote into its state directory: %v %v", entries, err)
}
// 4. A survivor serves at epoch 2 and A reads back there.
var p2 *host
poll(t, 120*time.Second, "no survivor became primary at epoch 2", func() bool {
for _, b := range survivors {
if statusIsPrimaryAt(b.status, 2) {
p2 = b
return true
}
}
return false
})
rc := dialNVMe(t, p2.nvme, plannedHandoffNQN)
defer rc.close()
if got := rc.read(t, 0, len(acked)); !bytes.Equal(got, acked) {
t.Fatalf("block A did not read back on %s", p2.rid)
}
}
@@ -1,157 +0,0 @@
//go:build linux && subprocess && chunkstore_integration && systemd_integration
package main_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
// A plain walstore holder started under the shipped unit's restart policy and
// start limit while blockmaster gives no reply (nothing listens on its
// address) waits inside the process for its store record: through a
// 5-minute outage the unit stays active with no restart, /status says
// waiting_for_master and the journal names the wait; once blockmaster
// starts, the volume serves with no restart. Before, the start exited 75 at
// once, the unit restarted every RestartSec, and after StartLimitBurst
// starts it stayed failed even once the master came back.
//
// A runtime unit file (/run/systemd/system) stands for the installed unit.
func TestWalstoreUnitWaitsForAnUnreachableMasterWithoutBurningItsStartLimit(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)
exe := filepath.Join(t.TempDir(), "blockvolume")
if d := os.Getenv("SWBLOCK_TEST_BINS"); d != "" {
exe = filepath.Join(d, "blockvolume")
} else {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
out, err := exec.CommandContext(ctx, "go", "build", "-o", exe, "github.com/seaweedfs/seaweed-block/cmd/blockvolume").CombinedOutput()
cancel()
if err != nil {
t.Fatalf("build blockvolume: %v %s", err, out)
}
}
masterBin := filepath.Join(filepath.Dir(exe), "blockmaster")
if os.Getenv("SWBLOCK_TEST_BINS") == "" {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
out, err := exec.CommandContext(ctx, "go", "build", "-o", masterBin, "github.com/seaweedfs/seaweed-block/cmd/blockmaster").CombinedOutput()
cancel()
if err != nil {
t.Fatalf("build blockmaster: %v %s", err, out)
}
}
master, data, ctrl, statusAddr, nvme := handoffAddress(t), handoffAddress(t), handoffAddress(t), handoffAddress(t), handoffAddress(t)
// nothing listens at master until blockmaster starts below
unit := fmt.Sprintf("swb-c04-walstore-wait-%d.service", os.Getpid())
writeRuntimeUnit(t, unit, exe, []string{"--master", master, "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1",
"--data-addr", data, "--ctrl-addr", ctrl, "--status-addr", statusAddr, "--durable-root", t.TempDir(), "--durable-impl", "walstore",
"--durable-blocks", "64", "--nvme-listen", nvme, "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:v1"}, []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)
}
// A 5-minute outage: on the old behaviour the unit has failed after
// StartLimitBurst starts RestartSec apart, well before this.
window := 5 * time.Minute
started := time.Now()
var state map[string]string
for time.Since(started) < window {
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 master outage: NRestarts %s Result %s; journal: %s",
time.Since(started).Round(time.Second), s["NRestarts"], s["Result"], lastLines(unitJournal(unit), 15))
}
}
journal := unitJournal(unit)
t.Logf("walstore unit after %v with no master: ActiveState %s NRestarts %s", window, state["ActiveState"], state["NRestarts"])
if state["ActiveState"] != "active" || state["NRestarts"] != "0" {
t.Fatalf("after %v: ActiveState %s NRestarts %s; want active with no restart; journal: %s", window, state["ActiveState"], state["NRestarts"], lastLines(journal, 15))
}
if !strings.Contains(journal, "waiting for the master at "+master+" to answer this replica's store record: no reply for") {
t.Fatalf("the journal does not name the wait: %s", lastLines(journal, 15))
}
if reason := statusNotReadyReason(statusAddr, "v1"); reason != "waiting_for_master" {
t.Fatalf("/status NotReadyReason %q during the wait; want waiting_for_master", reason)
}
// blockmaster starts: the waiting process goes on and serves, with no restart.
dir := t.TempDir()
topo := filepath.Join(dir, "topology.yaml")
nl := string(rune(10))
if err := os.WriteFile(topo, []byte("volumes:"+nl+" - volume_id: v1"+nl+" slots:"+nl+" - replica_id: r1"+nl+" server_id: s1"+nl), 0o644); err != nil {
t.Fatal(err)
}
mlog, err := os.Create(filepath.Join(dir, "blockmaster.log"))
if err != nil {
t.Fatal(err)
}
mc := exec.Command(masterBin, "--authority-store", filepath.Join(dir, "master"), "--listen", master, "--topology", topo, "--expected-slots-per-volume", "1")
mc.Stdout, mc.Stderr = mlog, mlog
if err := mc.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = mc.Process.Kill(); _ = mc.Wait(); mlog.Close() })
back := time.Now()
for !volumeFrontendReady(statusAddr, "v1") {
if time.Since(back) > 2*time.Minute {
b, _ := os.ReadFile(mlog.Name())
t.Fatalf("v1 never served after blockmaster started; journal: %s; blockmaster: %s", lastLines(unitJournal(unit), 15), lastLines(string(b), 10))
}
time.Sleep(time.Second)
}
s, _ := gap1ReadUnit(unit)
t.Logf("walstore unit served %v after blockmaster started: ActiveState %s NRestarts %s", time.Since(back).Round(time.Second), s["ActiveState"], s["NRestarts"])
if s["ActiveState"] != "active" || s["NRestarts"] != "0" {
t.Fatalf("after serving: ActiveState %s NRestarts %s; want active with no restart", s["ActiveState"], s["NRestarts"])
}
}
// statusNotReadyReason is /status's NotReadyReason for vol ("" when unreadable).
func statusNotReadyReason(statusAddr, vol string) string {
resp, err := http.Get("http://" + statusAddr + "/status?volume=" + vol)
if err != nil {
return ""
}
defer resp.Body.Close()
var p struct{ NotReadyReason string }
if json.NewDecoder(resp.Body).Decode(&p) != nil {
return ""
}
return p.NotReadyReason
}
func lastLines(s string, n int) string {
lines := strings.Split(strings.TrimSpace(s), string(rune(10)))
if len(lines) > n {
lines = lines[len(lines)-n:]
}
return strings.Join(lines, " | ")
}
@@ -1,121 +0,0 @@
package main
import (
"context"
"time"
"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/codes"
"google.golang.org/grpc/status"
)
// replicaStoreQueryTimeout bounds the holder's GetReplicaStore read before
// its durable open.
const replicaStoreQueryTimeout = 10 * time.Second
// replicaStoreRetryEvery paces the store record read while blockmaster gives
// no reply, and replicaStoreWaitLogEvery its log line. Vars only so a test
// can shorten them.
var (
replicaStoreRetryEvery = 2 * time.Second
replicaStoreWaitLogEvery = 30 * time.Second
)
// readReplicaStore reads the master's record of this replica's store. While
// blockmaster gives no reply (volume.MasterCallClass: neither contact nor a
// credentials refusal) the process waits and reads again, with no bound, so
// a start during a master outage does not exit and burn the unit's start
// limit. It runs before the store is opened or created, so nothing is
// written meanwhile; waiting reports the wait (for /status) and the log
// repeats it every replicaStoreWaitLogEvery with the master's address and the
// time waited. Any answer, a credentials refusal, or ctx's end returns the
// last result.
func readReplicaStore(ctx context.Context, master string, read func(context.Context) (*control.GetReplicaStoreResponse, error), logf func(string, ...any), waiting func(bool)) (*control.GetReplicaStoreResponse, error) {
var since, logged time.Time
defer func() {
if !since.IsZero() {
waiting(false)
}
}()
for {
qctx, cancel := context.WithTimeout(ctx, replicaStoreQueryTimeout)
rec, err := read(qctx)
cancel()
contact, credentials := volume.MasterCallClass(err)
if contact || credentials || ctx.Err() != nil {
if !since.IsZero() && ctx.Err() == nil {
logf("blockvolume: the master at %s answered this replica's store record after %s", master, time.Since(since).Round(time.Second))
}
return rec, err
}
if since.IsZero() {
since = time.Now()
waiting(true)
}
if logged.IsZero() || time.Since(logged) >= replicaStoreWaitLogEvery {
logged = time.Now()
logf("blockvolume: waiting for the master at %s to answer this replica's store record: no reply for %s (%v); nothing is created or written meanwhile", master, time.Since(since).Round(time.Second), err)
}
select {
case <-ctx.Done():
return rec, err
case <-time.After(replicaStoreRetryEvery):
}
}
}
// storeAdmission is how the durable open may treat the local store: with
// mustExist it never creates one (a missing store is refused at the open
// itself), and a nonzero id is the store it must find.
type storeAdmission struct {
mustExist bool
id storage.StoreID
}
// decideStoreAdmission decides how a plain walstore holder (a single-replica
// volume's, or a replicated volume's line primary) may open its local store
// from the master's record (GetReplicaStore) and whether a local store
// exists:
//
// answer store present store absent
// no reply (waited out in-process by readReplicaStore; only a shutdown ends the wait)
// other error refuse 75 refuse 75
// older master (Unimplemented) open as before refuse 75 master_too_old
// not listed open as before refuse 75 volume_not_listed
// listed, replicated, non-primary open or create (peer rebuild path, as before)
// listed, creating open or create create
// listed, ended, recorded id open, must be id refuse 78 store_lost
// listed, ended, no recorded id open, must exist refuse 78 store_lost
//
// Only an explicit listed-and-creating (or replicated) answer may create.
func decideStoreAdmission(rec *control.GetReplicaStoreResponse, err error, localExists bool) (storeAdmission, *workspaceExit) {
if err != nil {
if status.Code(err) == codes.Unimplemented {
if localExists {
return storeAdmission{mustExist: true}, nil // an older master: the present store opens as before, never re-created
}
return storeAdmission{}, &workspaceExit{code: exitWorkspaceRetry, reason: "master_too_old",
detail: "blockmaster does not answer this replica's store record (an older version) and the state directory has no store: upgrade blockmaster first; an empty state directory is never assumed new"}
}
return storeAdmission{}, &workspaceExit{code: exitWorkspaceRetry, reason: "store_record_unreadable",
detail: "the master's record of this replica's store could not be read (" + err.Error() + "); nothing was written, and the start is retried"}
}
switch {
case rec.GetListed() && rec.GetReplicated():
return storeAdmission{}, nil
case rec.GetListed() && rec.GetCreationEnded():
id := storage.StoreIDFromBytes(rec.GetStoreId())
if !localExists {
return storeAdmission{mustExist: true, id: id}, &workspaceExit{code: exitWorkspaceSuperseded, reason: "store_lost", detail: lostStoreDetail}
}
return storeAdmission{mustExist: true, id: id}, nil
case rec.GetListed():
return storeAdmission{}, nil
case localExists:
return storeAdmission{mustExist: true}, nil // not listed: the present store opens, never re-created
}
return storeAdmission{}, &workspaceExit{code: exitWorkspaceRetry, reason: "volume_not_listed",
detail: "the master does not list this volume and the state directory has no store: nothing is created"}
}
@@ -1,62 +0,0 @@
package main
import (
"errors"
"testing"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// The admission table (decideStoreAdmission's comment), row by row: only an
// explicit listed-and-creating (or replicated) answer may create; an ended
// volume must find its store (its recorded id when there is one); an error
// or a timeout is never "creating"; an older master keeps a present store
// opening (never re-created) and refuses an empty state directory.
func TestStoreAdmissionCreatesOnlyOnAnExplicitCreatingAnswer(t *testing.T) {
id := storage.StoreID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
ended := &control.GetReplicaStoreResponse{Listed: true, CreationEnded: true, StoreId: id[:]}
endedNoID := &control.GetReplicaStoreResponse{Listed: true, CreationEnded: true}
creating := &control.GetReplicaStoreResponse{Listed: true}
replicated := &control.GetReplicaStoreResponse{Listed: true, CreationEnded: true, Replicated: true}
unlisted := &control.GetReplicaStoreResponse{}
older := status.Error(codes.Unimplemented, "unknown method")
for _, tc := range []struct {
name string
rec *control.GetReplicaStoreResponse
err error
exists bool
want storeAdmission
wantReason string // "" = admitted
wantCode int
}{
{"creating, empty", creating, nil, false, storeAdmission{}, "", 0},
{"creating, present", creating, nil, true, storeAdmission{}, "", 0},
{"replicated, empty", replicated, nil, false, storeAdmission{}, "", 0},
{"ended, present", ended, nil, true, storeAdmission{mustExist: true, id: id}, "", 0},
{"ended, empty", ended, nil, false, storeAdmission{}, "store_lost", exitWorkspaceSuperseded},
{"ended, no recorded id, present", endedNoID, nil, true, storeAdmission{mustExist: true}, "", 0},
{"ended, no recorded id, empty", endedNoID, nil, false, storeAdmission{}, "store_lost", exitWorkspaceSuperseded},
{"unlisted, present", unlisted, nil, true, storeAdmission{mustExist: true}, "", 0},
{"unlisted, empty", unlisted, nil, false, storeAdmission{}, "volume_not_listed", exitWorkspaceRetry},
{"older master, present", nil, older, true, storeAdmission{mustExist: true}, "", 0},
{"older master, empty", nil, older, false, storeAdmission{}, "master_too_old", exitWorkspaceRetry},
{"unreachable, empty", nil, status.Error(codes.Unavailable, "connection refused"), false, storeAdmission{}, "store_record_unreadable", exitWorkspaceRetry},
{"unreadable record, present", nil, status.Error(codes.Unavailable, "invalid recorded store id"), true, storeAdmission{}, "store_record_unreadable", exitWorkspaceRetry},
{"timeout, present", nil, status.Error(codes.DeadlineExceeded, "deadline"), true, storeAdmission{}, "store_record_unreadable", exitWorkspaceRetry},
{"plain error, empty", nil, errors.New("boom"), false, storeAdmission{}, "store_record_unreadable", exitWorkspaceRetry},
} {
got, refuse := decideStoreAdmission(tc.rec, tc.err, tc.exists)
if tc.wantReason == "" {
if refuse != nil || got != tc.want {
t.Fatalf("%s: admission %+v refuse %+v, want admitted %+v", tc.name, got, refuse, tc.want)
}
continue
}
if refuse == nil || refuse.reason != tc.wantReason || refuse.code != tc.wantCode {
t.Fatalf("%s: refuse %+v, want %s (exit %d)", tc.name, refuse, tc.wantReason, tc.wantCode)
}
}
}
@@ -1,82 +0,0 @@
package main
import (
"context"
"errors"
"testing"
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// The store record read waits inside the process while blockmaster gives no
// reply (Unavailable, DeadlineExceeded, a timed-out read), logging once, and
// returns the first answer; any other result returns at once (a credentials
// refusal, an older master, an answered error), and so does a shutdown.
func TestReadReplicaStoreWaitsOnlyWhileTheMasterGivesNoReply(t *testing.T) {
prev := replicaStoreRetryEvery
replicaStoreRetryEvery = time.Millisecond
t.Cleanup(func() { replicaStoreRetryEvery = prev })
want := &control.GetReplicaStoreResponse{Listed: true}
script := func(errs ...error) (func(context.Context) (*control.GetReplicaStoreResponse, error), *int) {
calls := 0
return func(context.Context) (*control.GetReplicaStoreResponse, error) {
calls++
if calls <= len(errs) {
return nil, errs[calls-1]
}
return want, nil
}, &calls
}
logs := 0
logf := func(string, ...any) { logs++ }
var states []bool
waiting := func(w bool) { states = append(states, w) }
read, calls := script(status.Error(codes.Unavailable, "connection refused"), status.Error(codes.DeadlineExceeded, "deadline"), context.DeadlineExceeded)
if rec, err := readReplicaStore(context.Background(), "127.0.0.1:9180", read, logf, waiting); err != nil || rec != want || *calls != 4 || logs != 2 {
t.Fatalf("no reply three times, then an answer: rec %v err %v calls %d logs %d (want the answer after 4 reads, 2 log lines)", rec, err, *calls, logs)
}
if len(states) != 2 || !states[0] || states[1] {
t.Fatalf("the wait was reported %v; want waiting, then not", states)
}
// The log line repeats at its cadence, not at every read.
prevLog := replicaStoreWaitLogEvery
replicaStoreWaitLogEvery = 50 * time.Millisecond
t.Cleanup(func() { replicaStoreWaitLogEvery = prevLog })
logs, slow := 0, 0
slowRead := func(context.Context) (*control.GetReplicaStoreResponse, error) {
slow++
if slow > 60 {
return want, nil
}
time.Sleep(5 * time.Millisecond)
return nil, status.Error(codes.Unavailable, "down")
}
if _, err := readReplicaStore(context.Background(), "m", slowRead, logf, func(bool) {}); err != nil || logs < 3 || logs > 12 {
t.Fatalf("about 300 ms of no reply at a 50 ms cadence logged %d lines (err %v); want a few, not one per read", logs, err)
}
for _, e := range []error{status.Error(codes.Unauthenticated, "bad cert"), status.Error(codes.Unimplemented, "older"), status.Error(codes.Internal, "boom"), errors.New("plain")} {
read, calls := script(e)
if _, err := readReplicaStore(context.Background(), "m", read, logf, func(bool) {}); !errors.Is(err, e) || *calls != 1 {
t.Fatalf("%v: waited (%d reads) instead of returning it", e, *calls)
}
}
ctx, cancel := context.WithCancel(context.Background())
never := func(context.Context) (*control.GetReplicaStoreResponse, error) {
cancel()
return nil, status.Error(codes.Unavailable, "down")
}
done := make(chan error, 1)
go func() { _, err := readReplicaStore(ctx, "m", never, logf, func(bool) {}); done <- err }()
select {
case err := <-done:
if status.Code(err) != codes.Unavailable {
t.Fatalf("a shutdown during the wait: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("a shutdown did not end the wait")
}
}
@@ -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 }
@@ -1,6 +1,6 @@
//go:build unix
package weedtest
package main_test
import (
"errors"
@@ -32,11 +32,11 @@ func testPortClaimDir() string {
return "/tmp/swblock-test-port-claims"
}
// Claim takes port p for this process, host-wide; false when another
// 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 Claim(p int) bool {
func claimHostPort(p int) bool {
hostPortClaims.Lock()
defer hostPortClaims.Unlock()
if hostPortClaims.files == nil {
@@ -1,10 +1,39 @@
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} {
@@ -1,12 +0,0 @@
package main_test
import "github.com/seaweedfs/seaweed-block/internal/weedtest"
// The harness's ports come from internal/weedtest, which every
// process-level harness on a host shares: outside the ephemeral range,
// sliced per CI shard and claimed host-wide.
func claimHostPort(p int) bool { return weedtest.Claim(p) }
func testPortSpan(lo, hi int) (int, int) { return weedtest.Span(lo, hi) }
func weedPairRange(ephemeralLo int) (int, int) { return weedtest.WeedPairRange(ephemeralLo) }
func ephemeralPorts() (int, int) { return weedtest.EphemeralRange() }
@@ -4,7 +4,6 @@
"currentStartNs": 0,
"lastPass": {
"atNs": 1,
"processed": 0,
"planned": 0,
"removed": 0,
"plannedChunks": 0,
@@ -1,6 +1,6 @@
# 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 a lab host (archive sha256
# captured from that run on tp04 (archive sha256
# 0905c3af83b3a1dc226b417fa5acf7071907cc3e53478bc14a531481b717c5c1).
# "file <name> <size> <octal mode>", then "<offset> <hex>" for each run of
# non-zero bytes; every other byte is zero.
@@ -77,17 +77,13 @@ func (env *handoffEnv) deletePastPrintedHorizon(t *testing.T, volume, request st
// deleteLeaseHorizon accepts only the documented typed CLI refusal, never
// a matching stderr fragment or a successful exit with an error-shaped body.
// A signal stop does not retire the master lease: step 4 still returns the
// Reserve refusal still requires keeping the holder stopped (exit 1); after
// reservation commits, the final horizon refusal is temporary (exit 75).
func deleteLeaseHorizon(out string, code int) (time.Time, error) {
var body struct {
Code string `json:"code"`
Message string `json:"message"`
Retryable bool `json:"retryable"`
Code string `json:"code"`
Message string `json:"message"`
}
if code != 75 && code != 1 {
return time.Time{}, fmt.Errorf("exit %d is not temporary refusal", code)
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
@@ -95,12 +91,6 @@ func deleteLeaseHorizon(out string, code int) (time.Time, error) {
if body.Code != "not_admitted" {
return time.Time{}, fmt.Errorf("code %q is not not_admitted", body.Code)
}
if code == 75 && !body.Retryable {
return time.Time{}, fmt.Errorf("final lease refusal is not retryable")
}
if code == 1 && (body.Retryable || !strings.HasPrefix(body.Message, "stop the volume first: ")) {
return time.Time{}, fmt.Errorf("Reserve refusal must require stopping the volume first")
}
_, rest, ok := strings.Cut(body.Message, "live until ")
if !ok {
return time.Time{}, fmt.Errorf("missing lease horizon")
@@ -115,26 +105,20 @@ func deleteLeaseHorizon(out string, code int) (time.Time, error) {
// 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","retryable":true,"message":"workspace delete: live until 2026-11-26T13:00:00.125Z: lease expiry plus clock-skew margin has not elapsed"}`
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 retryable horizon", valid, 75, true},
{"Reserve horizon after holder already stopped", strings.Replace(strings.Replace(valid, `"retryable":true`, `"retryable":false`, 1), `"message":"`, `"message":"stop the volume first: `, 1), 1, true},
{"Reserve without stop cure", strings.Replace(valid, `"retryable":true`, `"retryable":false`, 1), 1, false},
{"old refusal exit", valid, 1, false},
{"non-retryable refusal", strings.Replace(valid, `"retryable":true`, `"retryable":false`, 1), 75, false},
{"missing retryable", strings.Replace(valid, `"retryable":true,`, "", 1), 75, false},
{"wrong typed code", strings.Replace(valid, "not_admitted", "remote_unavailable", 1), 75, false},
{"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", 75, 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","retryable":true,"message":"restart required"}`, 75, false},
{"missing time", `{"code":"not_admitted","retryable":true,"message":"live until "}`, 75, false},
{"invalid time", `{"code":"not_admitted","retryable":true,"message":"live until tomorrow: refused"}`, 75, 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)
@@ -211,11 +195,10 @@ func TestProcedureDeleteAVolume(t *testing.T) {
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"`
Retryable bool `json:"retryable"`
Code string `json:"code"`
Message string `json:"message"`
}
if err := json.Unmarshal([]byte(out), &refusal); err != nil || code != 1 || refusal.Retryable || refusal.Code != "snapshot_has_dependents" || !strings.Contains(refusal.Message, `snapshot "s1"`) {
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 {
@@ -1,158 +0,0 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"context"
"errors"
"fmt"
"net"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
// filerGroupOf is the filer group a cluster's filer was started with ("" when
// its arguments name none).
func filerGroupOf(c *w4WeedCluster) string {
for _, a := range c.procs["filer"].args {
if g, ok := strings.CutPrefix(a, "-filerGroup="); ok {
return g
}
}
return ""
}
// strayFiler starts, under from's procs as name, a filer with from's filer
// arguments but registering with master on fresh ports and its own store, as
// from's filer does when a port pair two concurrent starts picked alike
// sends it to another cluster's master. group replaces its filer group when
// set. It returns the stray's HTTP port.
func strayFiler(t *testing.T, from *w4WeedCluster, name, master, group string) int {
t.Helper()
used := map[int]bool{}
fp := w4FreePortPair(t, used)
var args []string
for _, a := range from.procs["filer"].args {
switch {
case strings.HasPrefix(a, "-master="):
a = "-master=" + master
case strings.HasPrefix(a, "-port="):
a = fmt.Sprintf("-port=%d", fp)
case strings.HasPrefix(a, "-defaultStoreDir="):
a = "-defaultStoreDir=" + filepath.Join(t.TempDir(), name)
case strings.HasPrefix(a, "-filerGroup=") && group != "":
a = "-filerGroup=" + group
}
args = append(args, a)
}
if group != "" && !strings.Contains(strings.Join(args, " "), "-filerGroup=") {
args = append(args, "-filerGroup="+group)
}
from.startProc(t, name, args...)
t.Cleanup(func() {
if !from.stopProcWithin(name, 5*time.Second) {
t.Errorf("weed %s did not exit after kill", name)
}
from.procs[name].log.Close()
})
if err := w4ListeningWithin(net.JoinHostPort(testListenHost(), strconv.Itoa(fp+10000)), 30*time.Second); err != nil {
t.Fatalf("%s: %v", name, err)
}
return fp
}
// listedBy waits until master lists a filer on port in group (a filer
// registers some seconds after it serves).
func listedBy(t *testing.T, master, group string, port int) {
t.Helper()
host, p, err := net.SplitHostPort(master)
if err != nil {
t.Fatal(err)
}
mp, _ := strconv.Atoi(p)
conn, err := link.Dial(net.JoinHostPort(host, strconv.Itoa(mp+10000)))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
want := ":" + strconv.Itoa(port) + "."
deadline := time.Now().Add(60 * time.Second)
for {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
resp, err := masterpb.NewSeaweedClient(conn).ListClusterNodes(ctx, &masterpb.ListClusterNodesRequest{ClientType: "filer", FilerGroup: group})
cancel()
if err == nil {
for _, n := range resp.GetClusterNodes() {
if strings.Contains(n.GetAddress(), want) {
return
}
}
}
if time.Now().After(deadline) {
t.Fatalf("master %s never listed the filer on port %d in group %q (last error %v)", master, port, group, err)
}
time.Sleep(500 * time.Millisecond)
}
}
// Two weed clusters side by side on one host: when a filer started for
// cluster B registers with cluster A's master (a port pair two concurrent
// starts picked alike), A's single-filer census still passes, because each
// cluster's filer has its own filer group. Control: a stray filer in A's own
// group is counted, and the census refuses it.
func TestWeedClustersSideBySideKeepTheirOwnFilerCensus(t *testing.T) {
a := startWorkspaceWeed(t)
b := startWorkspaceWeed(t)
port := strayFiler(t, b, "stray-b-filer", a.master, "")
listedBy(t, a.master, filerGroupOf(b), port)
requireLive(t, a, b)
if err := census(t, a, "/swblock/vols/census-a"); err != nil {
t.Fatalf("A's census with B's filer registered at A's master: %v", err)
}
own := filerGroupOf(a)
if own == "" {
t.Fatal("A's filer has no filer group of its own: a stray filer of another cluster lands in A's census")
}
port = strayFiler(t, b, "stray-a-filer", a.master, own)
listedBy(t, a.master, own, port)
requireLive(t, a, b)
err := census(t, a, "/swblock/vols/census-a2")
if !errors.Is(err, chunkstore.ErrNotSingleFiler) || !strings.Contains(err.Error(), fmt.Sprintf("filer group %q has 2 filers", own)) {
t.Fatalf("A's census with a second filer in A's own group: %v; want the refusal naming 2 filers in group %q", err, own)
}
}
// census runs A's single-filer census with its own bounded context, so one
// census never inherits another's waits; a cancellation is reported as such,
// never as a census verdict.
func census(t *testing.T, c *w4WeedCluster, assignPath string) error {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 75*time.Second)
defer cancel()
err := c.client(t, assignPath).CheckSingleFiler(ctx)
if ctx.Err() != nil {
t.Fatalf("the census ran out of its own time: %v", err)
}
return err
}
// requireLive fails unless every weed server of the clusters still runs.
func requireLive(t *testing.T, clusters ...*w4WeedCluster) {
t.Helper()
for _, c := range clusters {
for name := range c.procs {
if err := c.exitedEarly(name); err != nil {
t.Fatalf("cluster at %s: %v", c.master, err)
}
}
}
}
@@ -6,13 +6,11 @@ package main_test
// Only real loopback SeaweedFS processes and per-test temporary state are used.
import (
"context"
crand "crypto/rand"
"encoding/hex"
"fmt"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/internal/weedtest"
"math"
"math/rand"
"net"
"os"
"os/exec"
@@ -42,13 +40,54 @@ func testListenHost() string {
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()
p, ok := weedtest.FreeWeedPair(testListenHost(), used)
if !ok {
t.Fatal("no free port pair")
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
}
}
return p
t.Fatal("no free port pair")
return 0
}
func w4WaitTCP(t *testing.T, addr string, d time.Duration) {
@@ -201,19 +240,12 @@ func startWorkspaceWeedOnce(t *testing.T, dir, weed string, o w4WeedOpts) (*w4We
if err := w4ListeningWithin(c.master, 20*time.Second); err != nil {
return c, err
}
if err := c.exitedEarly("master"); 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)
// Each cluster's filer has its own filer group: a filer of another
// cluster that reaches this cluster's master (a port pair two concurrent
// starts picked alike) registers in its own group, so neither cluster's
// single-filer census counts it.
filerArgs := []string{"filer", "-ip=" + testListenHost(), fmt.Sprintf("-port=%d", fp), "-master=" + c.master, "-defaultStoreDir=" + filepath.Join(dir, "f"), "-filerGroup=" + w4FilerGroup(t)}
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))
@@ -242,40 +274,9 @@ func startWorkspaceWeedOnce(t *testing.T, dir, weed string, o w4WeedOpts) (*w4We
}
time.Sleep(500 * time.Millisecond)
}
// A master that could not bind its port has exited by now; the port
// answered for another cluster's master, which the servers above then
// joined. Start again on fresh ports.
if err := c.exitedEarly("master"); err != nil {
return c, err
}
return c, nil
}
// exitedEarly reports a server of this start that has already exited: its
// port answered, but for another process.
func (c *w4WeedCluster) exitedEarly(name string) error {
p := c.procs[name]
if p == nil || p.done == nil {
return nil
}
select {
case <-p.done:
return fmt.Errorf("weed %s exited (%v) although its port answered: another process holds that port", name, *p.exit)
default:
return nil
}
}
// w4FilerGroup is a filer group no other cluster on the host uses.
func w4FilerGroup(t *testing.T) string {
t.Helper()
b := make([]byte, 6)
if _, err := crand.Read(b); err != nil {
t.Fatal(err)
}
return "swt" + hex.EncodeToString(b)
}
// 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 {
@@ -1,122 +0,0 @@
package main
import (
"bytes"
"context"
"errors"
"fmt"
"net"
"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"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type unavailableCatalogRead struct{ *memChunkStore }
func (s unavailableCatalogRead) LookupEntry(context.Context, string, string) (*filerpb.Entry, error) {
return nil, fmt.Errorf("chunkstore: lookup HEAD: %w", status.Error(codes.Unavailable, "connection refused"))
}
func TestOpsChunkCatalogUnavailableIsTyped(t *testing.T) {
mem := newMemChunkStore()
useMemChunkStore(t, mem)
v := cliVolume(t, mem, "unreachable", "daily")
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
return unavailableCatalogRead{mem}, func() error { return nil }, nil
}
for _, command := range []string{"snapshots", "show"} {
code, out, _ := runChunk(cliArgs(command, volArgs("volume", v))...)
e := chunkErrorOut(t, out)
if code != 75 || e.Code != chunkstore.CodeRemoteUnavailable || !e.Retryable {
t.Fatalf("%s: exit=%d answer=%+v", command, code, e)
}
}
}
func TestSnapshotDeleteAbsentCLIUsesContractCodeAndKeepsReceipt(t *testing.T) {
ctx := context.Background()
mem := newMemChunkStore()
useMemChunkStore(t, mem)
v := cliVolume(t, mem, "absent-contract", "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", "missing", "--request-id", "absence"})
for i := 0; i < 2; i++ {
code, out, _ := runChunk(args...)
e := chunkErrorOut(t, out)
if code != chunkExitFailed || e.Code != chunkstore.CodeSnapshotNotFound || e.Retryable {
t.Errorf("attempt %d: exit=%d answer=%+v", i, code, e)
}
op, found, err := st.ReadSnapshotOperation(ctx, "absence", "delete")
if err != nil || !found || op.ErrorCode != "not_found" || op.State != "refused" || op.TargetGeneration == nil || *op.TargetGeneration != 0 {
t.Fatalf("changed durable absence fact: %+v found=%v err=%v", op, found, err)
}
if i == 0 {
// A later incarnation must not turn replay of the absence into a
// successful deletion or change its captured zero generation.
h, _, err = st.ReadHead(ctx)
if err != nil {
t.Fatal(err)
}
replacement := h.Snapshots["daily"]
replacement.Gen = h.Gen + 1
h.Snapshots["missing"] = replacement
if err := st.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil {
t.Fatal(err)
}
} else {
h, _, err = st.ReadHead(ctx)
if err != nil || h.Snapshots["missing"].Gen == 0 {
t.Fatalf("replay removed replacement: %+v %v", h, err)
}
}
}
}
func TestCatalogTransportClassificationKeepsDefiniteAnswers(t *testing.T) {
unavailable := status.Error(codes.Unavailable, "disconnected")
for _, tc := range []struct {
name string
err error
code string
retry bool
}{
{"wrapped", fmt.Errorf("lookup: %w", unavailable), "remote_unavailable", true},
{"deadline", errors.Join(context.DeadlineExceeded, unavailable), "deadline_exceeded", true},
{"caller cancellation", errors.Join(context.Canceled, unavailable), "canceled", false},
{"identity", errors.Join(layout.ErrIdentity, unavailable), "identity_mismatch", false},
{"catalog", &chunkstore.CatalogError{Code: "outcome_unknown", Retryable: true, Err: unavailable}, "outcome_unknown", true},
{"permission", status.Error(codes.PermissionDenied, "refused"), "internal", false},
{"unknown", errors.New("unexpected implementation error"), "internal", false},
{"address syntax", &net.AddrError{Err: "missing port", Addr: "filer"}, "internal", false},
} {
t.Run(tc.name, func(t *testing.T) {
var out, diag bytes.Buffer
exit := chunkResult("snapshots", nil, tc.err, &out, &diag)
e := chunkErrorOut(t, out.String())
wantExit := chunkExitFailed
if tc.code == codeUnavailableCLI {
wantExit = 75
}
if exit != wantExit || e.Code != tc.code || e.Retryable != tc.retry {
t.Fatalf("exit=%d answer=%+v", exit, e)
}
})
}
}
@@ -6,10 +6,8 @@ import (
"errors"
"fmt"
"io"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// chunkRunCatalogSnapshotDelete is the CLI-owned execution/observation seam.
@@ -31,50 +29,19 @@ func chunkRunCatalogSnapshotDelete(ctx context.Context, cat *chunkstore.BCatalog
}
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; keep the same --request-id if resuming\n", snapshotIncarnation(op), op.ID, op.Instance, op.Sequence)
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, catalogSnapshotDeleteRefusal(op)
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)
_, bounded := ctx.Deadline()
for bounded && errors.Is(err, layout.ErrBusy) {
// Resume the captured incarnation, never re-admit the snapshot name.
// The enclosing command's window bounds both pauses and attempts.
select {
case <-ctx.Done():
return nil, err
case <-time.After(100 * time.Millisecond):
}
if ctx.Err() != nil {
return nil, err
}
st, readErr := cat.Store(volume)
if readErr != nil {
return nil, readErr
}
op, readErr = st.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence)
if readErr != nil {
return nil, readErr
}
answer, err = cat.RunSnapshotDeleteOperation(ctx, volume, op, work)
}
if errors.Is(err, layout.ErrBusy) {
return nil, err // A caller without a window must not start endless retries.
}
if errors.Is(err, layout.ErrHasDependents) {
return nil, &chunkstore.CatalogError{Code: "snapshot_has_dependents", Message: "remove dependent volumes or release their dependency before resuming the same --request-id", Err: err}
}
if chunkTransportFailure(err) || chunkCanceled(err) || errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
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, catalogSnapshotDeleteRefusal(answer)
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"}
@@ -110,13 +77,3 @@ func chunkAdmitCatalogSnapshotDelete(ctx context.Context, cat *chunkstore.BCatal
}
return chunkCatalogSnapshotDeleteAnswer(ctx, cat, volume, op, nil, noWait, stderr)
}
// The retained absence fact keeps its v1.1 receipt encoding. Only its CLI
// presentation uses the public snapshot error vocabulary, including replay.
func catalogSnapshotDeleteRefusal(op chunkstore.SnapshotOperation) error {
code := op.ErrorCode
if op.Verb == "delete" && op.State == "refused" && op.TargetGeneration != nil && *op.TargetGeneration == 0 && op.ErrorCode == "not_found" && op.ErrorStatus == 404 {
code = chunkstore.CodeSnapshotNotFound
}
return &chunkstore.CatalogError{Code: code, Message: op.ErrorMessage}
}
@@ -289,7 +289,7 @@ func TestSnapshotDeletePublicInitiallyAbsentIsRetainedRefusal(t *testing.T) {
}
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 != "snapshot_not_found" {
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")
@@ -1,324 +0,0 @@
package main
import (
"bytes"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"reflect"
"strconv"
"strings"
"testing"
"text/template"
"gopkg.in/yaml.v3"
)
// renderChartTemplate renders one chart template for a new release (lookup
// answers nothing) and fails the test if the template refuses to render.
func renderChartTemplate(t *testing.T, name string, edit func(values map[string]any)) []map[string]any {
t.Helper()
docs, refused := renderChart(t, name, edit, nil)
if refused != "" {
t.Fatalf("render %s refused: %s", name, refused)
}
return docs
}
// renderChart renders one chart template (see renderChartText) and returns
// its documents decoded as YAML, or the template's fail message when it
// refuses to render.
func renderChart(t *testing.T, name string, edit func(values map[string]any), running map[string]any) ([]map[string]any, string) {
t.Helper()
text, refused := renderChartText(t, name, edit, running)
if refused != "" {
return nil, refused
}
var docs []map[string]any
for _, part := range strings.Split(text, "\n---") {
doc := map[string]any{}
if err := yaml.Unmarshal([]byte(part), &doc); err != nil {
t.Fatalf("rendered %s is not YAML: %v\n%s", name, err, part)
}
if len(doc) > 0 {
docs = append(docs, doc)
}
}
return docs, ""
}
// renderChartText renders one chart template, with the chart's helpers, from
// its values.yaml changed by edit, using the Helm functions the chart uses.
// running is the release's existing blockmaster Deployment, which lookup
// answers: nil renders an install (.Release.IsInstall), anything else an
// upgrade. It returns the rendered text, or the template's fail message.
func renderChartText(t *testing.T, name string, edit func(values map[string]any), running map[string]any) (string, string) {
t.Helper()
chart := filepath.Join("..", "..", "charts", "seaweed-block")
read := func(p ...string) []byte {
b, err := os.ReadFile(filepath.Join(append([]string{chart}, p...)...))
if err != nil {
t.Fatal(err)
}
return b
}
values, meta := map[string]any{}, map[string]any{}
if err := yaml.Unmarshal(read("values.yaml"), &values); err != nil {
t.Fatal(err)
}
if err := yaml.Unmarshal(read("Chart.yaml"), &meta); err != nil {
t.Fatal(err)
}
edit(values)
empty := func(v any) bool {
if v == nil {
return true
}
r := reflect.ValueOf(v)
switch r.Kind() {
case reflect.Map, reflect.Slice, reflect.String:
return r.Len() == 0
case reflect.Bool:
return !r.Bool()
}
return r.IsZero()
}
var tp *template.Template
funcs := template.FuncMap{
"fail": func(msg string) (string, error) { return "", &templateFail{msg} },
"include": func(name string, data any) (string, error) {
var b bytes.Buffer
err := tp.ExecuteTemplate(&b, name, data)
return b.String(), err
},
"toYaml": func(v any) (string, error) {
b, err := yaml.Marshal(v)
return strings.TrimSuffix(string(b), "\n"), err
},
"nindent": func(n int, s string) string {
pad := strings.Repeat(" ", n)
return "\n" + pad + strings.ReplaceAll(s, "\n", "\n"+pad)
},
"quote": func(v any) string {
if v == nil {
return `""`
}
return strconv.Quote(fmt.Sprint(v))
},
"default": func(d any, given ...any) any {
if len(given) == 0 || empty(given[0]) {
return d
}
return given[0]
},
"dict": func() map[string]any { return map[string]any{} },
"empty": empty,
"int": func(v any) int {
switch x := v.(type) {
case int:
return x
case float64:
return int(x)
case string:
n, _ := strconv.Atoi(x)
return n
}
return 0
},
"lookup": func(apiVersion, kind, namespace, name string) map[string]any {
if apiVersion != "apps/v1" || kind != "Deployment" || namespace != "sw" || name != "sw-blockmaster" || running == nil {
return map[string]any{} // Helm answers an absent object with an empty map
}
return running
},
"clean": path.Clean,
"base": path.Base,
"dir": path.Dir,
"replace": func(old, new, s string) string { return strings.ReplaceAll(s, old, new) },
"hasPrefix": func(prefix, s string) bool { return strings.HasPrefix(s, prefix) },
"trimSuffix": func(suffix, s string) string { return strings.TrimSuffix(s, suffix) },
"trunc": func(n int, s string) string {
if len(s) > n {
return s[:n]
}
return s
},
}
tp = template.New(name).Funcs(funcs)
if _, err := tp.New("_helpers.tpl").Parse(string(read("templates", "_helpers.tpl"))); err != nil {
t.Fatal(err)
}
if _, err := tp.New(name).Parse(string(read("templates", name))); err != nil {
t.Fatal(err)
}
var out bytes.Buffer
data := map[string]any{
"Values": values,
"Release": map[string]any{"Name": "sw-block", "Namespace": "sw", "Service": "Helm", "IsInstall": running == nil, "IsUpgrade": running != nil},
"Chart": map[string]any{"Name": meta["name"], "Version": meta["version"]},
}
if err := tp.ExecuteTemplate(&out, name, data); err != nil {
var f *templateFail
if errors.As(err, &f) {
return "", f.msg
}
t.Fatalf("render %s: %v", name, err)
}
return out.String(), ""
}
// blockmaster uses the host network and, with a state path, is pinned to one
// node by hostname: a rolling update's new pod can never be scheduled beside
// the old one (same host ports, only that node), so every upgrade that
// changes its pod would wait forever. Its Deployment is replaced, not rolled:
// rendered with the default state path and with ephemeral state alike.
func TestBlockmasterDeploymentIsRecreatedNotRolled(t *testing.T) {
section := func(v map[string]any, k string) map[string]any { return v[k].(map[string]any) }
pinned := func(v map[string]any) {
section(v, "blockmaster")["nodeSelector"] = map[string]any{"kubernetes.io/hostname": "n1"}
}
for _, c := range []struct {
name string
edit func(map[string]any)
}{
{"state path, pinned by hostname", pinned},
{"ephemeral state", func(v map[string]any) { section(v, "blockmaster")["stateHostPath"] = "" }},
} {
var deployment map[string]any
for _, doc := range renderChartTemplate(t, "blockmaster.yaml", c.edit) {
if md, _ := doc["metadata"].(map[string]any); doc["kind"] == "Deployment" && md["name"] == "sw-blockmaster" {
deployment = doc
}
}
if deployment == nil {
t.Fatalf("%s: no sw-blockmaster Deployment rendered", c.name)
}
spec, _ := deployment["spec"].(map[string]any)
strategy, _ := spec["strategy"].(map[string]any)
if strategy["type"] != "Recreate" {
t.Errorf("%s: blockmaster strategy %v, want Recreate (a rolling update never schedules its new pod)", c.name, spec["strategy"])
}
}
}
// blockmaster's stores and the generated blockvolume pods' state are on
// separate node paths: a holder pod mounts only its own state path, never
// blockmaster's authority and lifecycle stores. A release that sets one path
// for both (a v1.1.0 install) keeps that shared layout instead of moving
// its volumes; ephemeral state passes no path.
func TestHolderStateIsApartFromBlockmasterStores(t *testing.T) {
section := func(v map[string]any, k string) map[string]any { return v[k].(map[string]any) }
pinned := func(v map[string]any) {
section(v, "blockmaster")["nodeSelector"] = map[string]any{"kubernetes.io/hostname": "n1"}
}
// upgrade renders over a running blockmaster on a state path (an
// existing release); otherwise the render is a new install.
upgradeOf := blockmasterDeploymentWith(map[string]any{"name": "state", "hostPath": map[string]any{"path": "/var/lib/sw-block"}})
render := func(edit func(map[string]any), upgrade bool) ([]map[string]any, string) {
t.Helper()
var running map[string]any
if upgrade {
running = upgradeOf
}
return renderChart(t, "blockmaster.yaml", edit, running)
}
paths := func(edit func(map[string]any), upgrade bool) (master, holders string) {
t.Helper()
docs, refused := render(edit, upgrade)
if refused != "" {
t.Fatalf("render refused: %s", refused)
}
for _, doc := range docs {
if md, _ := doc["metadata"].(map[string]any); doc["kind"] != "Deployment" || md["name"] != "sw-blockmaster" {
continue
}
pod := doc["spec"].(map[string]any)["template"].(map[string]any)["spec"].(map[string]any)
for _, v := range pod["volumes"].([]any) {
if vol := v.(map[string]any); vol["name"] == "state" {
if hp, ok := vol["hostPath"].(map[string]any); ok {
master, _ = hp["path"].(string)
}
}
}
for _, c := range pod["containers"].([]any) {
for _, a := range c.(map[string]any)["args"].([]any) {
if s, _ := a.(string); strings.HasPrefix(s, "--launcher-state-hostpath=") {
holders = strings.TrimPrefix(s, "--launcher-state-hostpath=")
}
}
}
}
return master, holders
}
if m, h := paths(pinned, false); m != "/var/lib/sw-block/k8s/master" || h != "/var/lib/sw-block/k8s/volumes" {
t.Errorf("default paths: blockmaster %q, holders %q; want /var/lib/sw-block/k8s/master and /var/lib/sw-block/k8s/volumes", m, h)
}
v110 := map[string]func(map[string]any){
"a v1.1.0 values file that sets only blockmaster.stateHostPath": func(v map[string]any) {
pinned(v)
section(v, "blockmaster")["stateHostPath"] = "/var/lib/sw-block"
},
"a v1.1.0 generated values file (both paths the same)": func(v map[string]any) {
pinned(v)
section(v, "blockmaster")["stateHostPath"] = "/var/lib/sw-block"
section(v, "restartPersistence")["stateHostPath"] = "/var/lib/sw-block"
},
}
for name, edit := range v110 {
if m, h := paths(edit, true); m != "/var/lib/sw-block" || h != "/var/lib/sw-block" {
t.Errorf("%s: blockmaster %q, holders %q; want both /var/lib/sw-block (its volumes stay where they are)", name, m, h)
}
}
if m, h := paths(func(v map[string]any) {
pinned(v)
section(v, "blockmaster")["stateHostPath"] = "/srv/sw/master/"
}, false); m != "/srv/sw/master/" || h != "/srv/sw/volumes" {
t.Errorf("a master path ending in /master: blockmaster %q, holders %q; want the volumes directory beside it", m, h)
}
if m, h := paths(func(v map[string]any) { section(v, "blockmaster")["stateHostPath"] = "" }, false); m != "" || h != "" {
t.Errorf("ephemeral: blockmaster %q, holders %q; want no host paths", m, h)
}
// A new install never gets the shared layout silently: a custom
// blockmaster path outside the default layout needs the volumes path
// set; with it, the install renders apart.
custom := func(volumes string) func(map[string]any) {
return func(v map[string]any) {
pinned(v)
section(v, "blockmaster")["stateHostPath"] = "/data/swb"
section(v, "restartPersistence")["stateHostPath"] = volumes
}
}
if _, refused := render(custom(""), false); !strings.Contains(refused, "set restartPersistence.stateHostPath beside blockmaster.stateHostPath") {
t.Errorf("a new install with a custom blockmaster path and no volumes path: refused %q, want the beside-it refusal", refused)
}
if m, h := paths(custom("/data/swb-volumes"), false); m != "/data/swb" || h != "/data/swb-volumes" {
t.Errorf("a new install with both paths set: blockmaster %q, holders %q", m, h)
}
// Kept shared layout on an upgrade: the install notes warn and name the
// exposure; the default layout prints no warning.
notes := func(edit func(map[string]any), upgrade bool) string {
t.Helper()
var running map[string]any
if upgrade {
running = upgradeOf
}
text, refused := renderChartText(t, "NOTES.txt", edit, running)
if refused != "" {
t.Fatalf("NOTES refused: %s", refused)
}
return text
}
const shared = "WARNING: the generated blockvolume pods share blockmaster's state path"
for name, edit := range v110 {
if text := notes(edit, true); !strings.Contains(text, shared) || !strings.Contains(text, "authority and lifecycle stores") {
t.Errorf("%s: the install notes do not warn about the shared layout:\n%s", name, text)
}
}
if text := notes(pinned, false); strings.Contains(text, shared) {
t.Errorf("the default layout warns about a shared layout:\n%s", text)
}
}
@@ -1,79 +0,0 @@
package main
import (
"strings"
"testing"
)
// renderBlockmasterGuards renders the chart's blockmaster template with the
// chart's own values.yaml, changed by edit, while lookup answers the
// release's existing blockmaster Deployment with running (nil: none). It
// returns the template's fail message, "" when the render is admitted.
func renderBlockmasterGuards(t *testing.T, edit func(values map[string]any), running map[string]any) string {
t.Helper()
_, refused := renderChart(t, "blockmaster.yaml", edit, running)
return refused
}
type templateFail struct{ msg string }
func (f *templateFail) Error() string { return f.msg }
func blockmasterDeploymentWith(volume map[string]any) map[string]any {
return map[string]any{"spec": map[string]any{"template": map[string]any{"spec": map[string]any{
"volumes": []any{map[string]any{"name": "tls", "secret": map[string]any{}}, volume}}}}}
}
// The chart's state-path guards, rendered: a state path needs blockmaster
// pinned by hostname (none, or a broader selector, is refused); an existing
// release whose blockmaster runs with ephemeral state is not switched to a
// state path without the acknowledgement; a release already on a state path,
// or one that stays ephemeral, is admitted.
func TestChartStatePathGuardsRender(t *testing.T) {
section := func(v map[string]any, k string) map[string]any { return v[k].(map[string]any) }
pinned := func(v map[string]any) {
section(v, "blockmaster")["nodeSelector"] = map[string]any{"kubernetes.io/hostname": "n1"}
}
ephemeralRun := blockmasterDeploymentWith(map[string]any{"name": "state", "emptyDir": map[string]any{}})
hostPathRun := blockmasterDeploymentWith(map[string]any{"name": "state", "hostPath": map[string]any{"path": "/var/lib/sw-block/k8s"}})
const hostnameRefusal, ackRefusal = "set blockmaster.nodeSelector.kubernetes.io/hostname", "set restartPersistence.acknowledgeEphemeralDataLoss=true"
const aboveRefusal = "restartPersistence.stateHostPath is above blockmaster.stateHostPath"
volumes := func(p string) func(map[string]any) {
return func(v map[string]any) { pinned(v); section(v, "restartPersistence")["stateHostPath"] = p }
}
for _, c := range []struct {
name string
edit func(map[string]any)
running map[string]any
want string
}{
{"default values, no selector", func(map[string]any) {}, nil, hostnameRefusal},
{"a broader selector", func(v map[string]any) {
section(v, "blockmaster")["nodeSelector"] = map[string]any{"kubernetes.io/os": "linux"}
}, nil, hostnameRefusal},
{"pinned by hostname, new release", pinned, nil, ""},
{"pinned, over an ephemeral release, no acknowledgement", pinned, ephemeralRun, ackRefusal},
{"pinned, over an ephemeral release, acknowledged", func(v map[string]any) {
pinned(v)
section(v, "restartPersistence")["acknowledgeEphemeralDataLoss"] = true
}, ephemeralRun, ""},
{"pinned, over a release already on a state path", pinned, hostPathRun, ""},
{"volumes path above the master's (v1.1.0's default base)", volumes("/var/lib/sw-block/k8s"), nil, aboveRefusal},
{"volumes path above the master's, trailing slash", volumes("/var/lib/sw-block/k8s/"), nil, aboveRefusal},
{"volumes path is the root", volumes("/"), nil, aboveRefusal},
{"volumes path equal to the master's (kept v1.1.0 layout)", volumes("/var/lib/sw-block/k8s/master"), nil, ""},
{"volumes path empty (beside the master's)", volumes(""), nil, ""},
{"volumes path above the master's once cleaned", volumes("/var/lib/sw-block/k8s/x/.."), nil, aboveRefusal},
{"volumes path beside the master's, a common name prefix", volumes("/var/lib/sw-block/k8s/mast"), nil, ""},
{"volumes path below the master's", volumes("/var/lib/sw-block/k8s/master/volumes"), nil, ""},
{"ephemeral stays ephemeral", func(v map[string]any) {
section(v, "blockmaster")["stateHostPath"] = ""
section(v, "blockmaster")["nodeSelector"] = map[string]any{"kubernetes.io/os": "linux"}
}, ephemeralRun, ""},
} {
got := renderBlockmasterGuards(t, c.edit, c.running)
if c.want == "" && got != "" || c.want != "" && !strings.Contains(got, c.want) {
t.Errorf("%s: render refused %q, want %q", c.name, got, c.want)
}
}
}
+19 -75
View File
@@ -65,19 +65,17 @@ func refuseUnlessSingleFiler(name string, f chunkstore.Filer, timeout time.Durat
// 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.WithTimeoutCause(parent, timeout, chunkstore.ErrSingleFilerWindowExpired)
ctx, cancel := context.WithTimeout(parent, timeout)
defer cancel()
err := checkSingleFiler(ctx, f)
if err != nil && !errors.Is(err, chunkstore.ErrSingleFilerWindowExpired) && parent.Err() != nil {
if err != nil && parent.Err() != nil {
if c := context.Cause(parent); c != nil && !errors.Is(err, c) {
err = fmt.Errorf("%w (%w)", err, c)
err = fmt.Errorf("%w (%v)", err, c)
}
}
switch {
case err == nil:
return -1
case chunkCanceled(err) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled) || chunkTransportFailure(err):
return chunkResult(name, nil, err, stdout, stderr)
case errors.Is(err, chunkstore.ErrNotSingleFiler):
return chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
default:
@@ -202,11 +200,6 @@ func chunkPostUntil(name, statusAddr, route string, timeout time.Duration, waitU
a.Accepted = true
return 0
}
if resp.StatusCode == http.StatusOK && len(admission) == 1 && admission[0] != nil {
// A holder without snapshot operations predates this release: the
// asynchronous operation replaced its synchronous answer.
return chunkFail(name, stdout, stderr, chunkExitUnknown, "outcome_unknown", "the holder answered without a snapshot operation; upgrade it to this release, then repeat the command", false)
}
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)
@@ -219,41 +212,31 @@ func chunkPostUntil(name, statusAddr, route string, timeout time.Duration, waitU
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, chunkErrorAdvice(e.Code, e.Retryable, e.Message))
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
}
return chunkErrorExit(chunkExitFailed, e.Code, e.Retryable)
return chunkExitFailed
}
func chunkCut(args []string, stdout, stderr io.Writer) int {
fs := chunkFlagSet("cut", stderr)
var (
volumeID, statusAddr, deadlineText string
minLSN uint64
timeout time.Duration
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, "no-progress window for this cut; answered polls alone do not renew it")
fs.StringVar(&deadlineText, "deadline", "", "optional absolute RFC3339 deadline")
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)
}
var deadline time.Time
if deadlineText != "" {
var err error
deadline, err = time.Parse(time.RFC3339Nano, deadlineText)
if err != nil || deadline.IsZero() || !time.Unix(0, deadline.UnixNano()).Equal(deadline) {
return chunkFail("cut", stdout, stderr, 2, codeBadRequestCLI, "--deadline must be a nonzero absolute RFC3339 time representable as Unix nanoseconds", false)
}
}
return chunkObserveCut(statusAddr, timeout, deadline, map[string]any{"volumeID": volumeID, "minLSN": minLSN}, stdout, stderr)
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 {
@@ -281,11 +264,8 @@ func chunkSnapshot(args []string, stdout, stderr io.Writer) int {
if err := fs.Parse(args); err != nil {
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
}
if volumeID == "" || statusAddr == "" {
return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false)
}
if err := chunkstore.ValidateNewSnapshotName(name); err != nil {
return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, chunkstore.CodeInvalidName, 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 {
@@ -314,10 +294,10 @@ func chunkSnapshot(args []string, stdout, stderr io.Writer) int {
func chunkDetach(args []string, stdout, stderr io.Writer) int {
fs := chunkFlagSet("detach", stderr)
var (
volumeID, statusAddr, deadlineText string
timeout time.Duration
plain, frozen, allowOverBudget bool
freezeStartedAtNs int64
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)")
@@ -326,18 +306,9 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int {
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")
fs.StringVar(&deadlineText, "deadline", "", "with --plain: optional absolute RFC3339 deadline, the only total bound on the observed detach")
if err := fs.Parse(args); err != nil {
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
}
var deadline time.Time
if deadlineText != "" {
var err error
deadline, err = time.Parse(time.RFC3339Nano, deadlineText)
if err != nil || deadline.IsZero() || !time.Unix(0, deadline.UnixNano()).Equal(deadline) || !plain {
return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--deadline needs --plain and a nonzero absolute RFC3339 time representable as Unix nanoseconds", false)
}
}
if volumeID == "" || statusAddr == "" {
return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false)
}
@@ -352,7 +323,7 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int {
body := map[string]any{"volumeID": volumeID}
if plain {
body["plain"] = true
return chunkPlainDetachPost(statusAddr, volumeID, timeout, deadline, body, stdout, stderr)
return chunkPlainDetachPost(statusAddr, volumeID, timeout, body, stdout, stderr)
}
if frozen {
body["frozen"] = true
@@ -370,21 +341,11 @@ func chunkResult(name string, v any, err error, stdout, stderr io.Writer) int {
var ce *chunkstore.CatalogError
switch {
case errors.As(err, &ce):
exit := chunkExitFailed
if name == "volume-delete" && ce.Code == "not_admitted" && ce.Retryable {
exit = 75 // temporary admission refusal; retry the same request ID
}
return chunkFail(name, stdout, stderr, exit, ce.Code, ce.Detail(), ce.Retryable)
case chunkCanceled(err):
return chunkFail(name, stdout, stderr, chunkExitFailed, codeCanceledCLI, "operation interrupted by its caller", false)
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 chunkTransportFailure(err):
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, err.Error(), true)
case errors.Is(err, errVerifyStalled):
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.ErrBusy))
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)
}
@@ -404,7 +365,6 @@ func chunkResult(name string, v any, err error, stdout, stderr io.Writer) int {
// CLI-side error codes, the same as the routes' (B9 §2.2 and the rulings
// of 2026-11-15).
const (
codeCanceledCLI = "canceled"
codeBadRequestCLI = "bad_request"
codeInternalCLI = "internal"
codeUnavailableCLI = "remote_unavailable"
@@ -420,8 +380,6 @@ type chunkErrBody struct {
// {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 {
exit = chunkErrorExit(exit, code, retryable)
message = chunkErrorAdvice(code, retryable, message)
prefix := "sw-block ops chunk"
if name != "" {
prefix += " " + name
@@ -445,17 +403,3 @@ func writeAll(w io.Writer, p []byte) error {
}
return err
}
// CLI temporary remote failures use EX_TEMPFAIL consistently across commands.
func chunkErrorExit(exit int, code string, retryable bool) int {
if code == codeUnavailableCLI && retryable {
return 75
}
return exit
}
func chunkErrorAdvice(code string, retryable bool, message string) string {
if code == codeUnavailableCLI && retryable {
return message + "; retry the same operation when the remote is reachable"
}
return message
}
+2 -7
View File
@@ -44,9 +44,6 @@ func bCatalog(name, filer, base string, writes bool, timeout time.Duration, stdo
}
f, closeFn, err := dialChunkFiler(filer)
if err != nil {
if chunkCanceled(err) || chunkTransportFailure(err) {
return nil, nil, chunkResult(name, nil, err, stdout, stderr)
}
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
}
fail := func(msg string) (*chunkstore.BCatalog, func() error, int) {
@@ -145,9 +142,6 @@ func (c *bCommand) run(args []string, writes bool, refs func() error, do func(co
return chunkFail(name, c.stdout, c.stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
}
if err := refs(); err != nil {
if chunkCanceled(err) || chunkTransportFailure(err) {
return chunkResult(name, nil, err, c.stdout, c.stderr)
}
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)
}
@@ -397,6 +391,8 @@ func chunkRestore(args []string, stdout, stderr io.Writer) int {
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)
}
@@ -443,7 +439,6 @@ func layoutCode(err error) string {
code string
}{
{layout.ErrQueueFull, chunkstore.CodeQueueFull},
{layout.ErrBusy, "layout_busy"},
{layout.ErrNoSnapshot, "snapshot_not_found"},
{layout.ErrSnapshotDeleteNeedsOperation, "snapshot_delete_requires_operation"},
{layout.ErrHasDependents, "snapshot_has_dependents"},
+2 -29
View File
@@ -204,7 +204,6 @@ type fakeLifecycle struct {
control.UnimplementedLifecycleServiceServer
mu sync.Mutex
held bool
datedHorizon bool
leaseAfterReserve bool
reserved, leased bool
calls []string
@@ -219,9 +218,6 @@ func (f *fakeLifecycle) record(name string) {
func (f *fakeLifecycle) ReserveVolumeDeletion(_ context.Context, r *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) {
f.record("reserve")
if f.held {
if f.datedHorizon {
return nil, status.Error(codes.FailedPrecondition, "workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed")
}
return nil, status.Error(codes.FailedPrecondition, "volume has a live authority line")
}
f.reserved = true
@@ -234,9 +230,6 @@ func (f *fakeLifecycle) ReserveVolumeDeletion(_ context.Context, r *control.Mark
func (f *fakeLifecycle) CheckVolumeNoLiveLease(context.Context, *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) {
f.record("check")
if !f.reserved || f.leased {
if f.datedHorizon {
return nil, status.Error(codes.FailedPrecondition, "workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed")
}
return nil, status.Error(codes.FailedPrecondition, "a line of the volume holds a live lease")
}
return &control.MarkVolumeDeletingResponse{Known: true}, nil
@@ -281,33 +274,13 @@ func TestOpsChunk_VolumeDeleteOnTheLayout(t *testing.T) {
return u.OwnChunks + u.ForeignChunks
}
held := &fakeLifecycle{held: true}
if code, out := del(held, tgt); code != 1 || chunkErrorOut(t, out).Code != "not_admitted" || chunkErrorOut(t, out).Retryable || strings.Join(held.calls, ",") != "reserve" {
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)
}
for _, tc := range []struct {
name string
before bool
exit int
retry bool
calls, advice string
}{
{"Reserve live holder with dated horizon", true, 1, false, "reserve", "stop the volume first"},
{"committed reservation final dated barrier", false, 75, true, "reserve,check", "retry the same --request-id after 2026-12-03T13:00:00Z"},
} {
t.Run(tc.name, func(t *testing.T) {
lc := &fakeLifecycle{held: tc.before, leaseAfterReserve: !tc.before, datedHorizon: true}
code, out := del(lc, tgt)
answer := chunkErrorOut(t, out)
if code != tc.exit || answer.Code != "not_admitted" || answer.Retryable != tc.retry || !strings.HasPrefix(answer.Message, tc.advice+": ") || strings.Join(lc.calls, ",") != tc.calls || objects(tgt) != 1 {
t.Fatalf("exit=%d answer=%+v calls=%v objects=%d", code, answer, lc.calls, objects(tgt))
}
})
}
// 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 != 1 || chunkErrorOut(t, out).Code != "not_admitted" || chunkErrorOut(t, out).Retryable || strings.Join(race.calls, ",") != "reserve,check" || objects(tgt) != 1 {
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) {
@@ -1,101 +0,0 @@
package main
import (
"bytes"
"context"
"encoding/json"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"net"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/health/grpc_health_v1"
)
// A real gRPC call canceled by its caller keeps a cancellation answer.
func TestChunkCallerCancelIsNotTransport(t *testing.T) {
conn, err := grpc.NewClient("127.0.0.1:1", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err = grpc_health_v1.NewHealthClient(conn).Check(ctx, &grpc_health_v1.HealthCheckRequest{}, grpc.WaitForReady(true))
t.Logf("canceled call: %v; transport=%t", err, chunkTransportFailure(err))
if chunkTransportFailure(err) {
t.Errorf("caller cancellation classified as a remote transport failure")
}
var out, diag bytes.Buffer
if exit := chunkResult("snapshots", nil, err, &out, &diag); exit != chunkExitFailed {
t.Fatalf("exit=%d", exit)
}
answer := chunkErrorOut(t, out.String())
if answer.Code != "canceled" || answer.Retryable {
t.Fatalf("canceled call: %+v", answer)
}
}
func TestChunkCensusKeepsItsParentCancellationCause(t *testing.T) {
previous := checkSingleFiler
t.Cleanup(func() { checkSingleFiler = previous })
checkSingleFiler = func(context.Context, chunkstore.Filer) error { return status.Error(codes.Canceled, "context canceled") }
for _, tc := range []struct {
name string
cause error
code string
retry bool
}{
{"caller", context.Canceled, "canceled", false},
{"deadline", context.DeadlineExceeded, "deadline_exceeded", true},
{"pass silence", errVerifyStalled, "deadline_exceeded", true},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithCancelCause(context.Background())
cancel(tc.cause)
var out, diag bytes.Buffer
if exit := refuseUnlessSingleFilerWithin(ctx, "verify", nil, time.Second, &out, &diag); exit != chunkExitFailed {
t.Fatalf("exit=%d", exit)
}
var answer chunkErrBody
if err := json.Unmarshal(out.Bytes(), &answer); err != nil || answer.Code != tc.code || answer.Retryable != tc.retry {
t.Fatalf("answer=%+v error=%v", answer, err)
}
})
}
}
func TestChunkCensusInternalWinnerSurvivesLaterCallerDeadline(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := listener.Addr().String()
if err := listener.Close(); err != nil {
t.Fatal(err)
}
client, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{FilerGRPC: addr})
if err != nil {
t.Fatal(err)
}
defer client.Close()
parent, stop := context.WithCancelCause(context.Background())
defer stop(nil)
previous := checkSingleFiler
t.Cleanup(func() { checkSingleFiler = previous })
checkSingleFiler = func(ctx context.Context, f chunkstore.Filer) error {
err := previous(ctx, f)
stop(context.DeadlineExceeded) // after the internal window's classified result
return err
}
var out, diag bytes.Buffer
exit := refuseUnlessSingleFilerWithin(parent, "verify", client, time.Millisecond, &out, &diag)
answer := chunkErrorOut(t, out.String())
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable {
t.Fatalf("late caller overrode first internal expiry: %d %+v", exit, answer)
}
}
@@ -17,10 +17,7 @@ func TestChunkVolumeDeleteAuthorityRPCSites(t *testing.T) {
// resolveVolumeID reads the name binding; restoreCreateRPC makes the
// restore's one master CreateVolume call (TestOpsChunkRestoreUsesOnlyMasterCreate).
{"chunk_b.go", map[string]int{"DialMasterFromEnv": 2}},
// reserveLocked has exactly two entry points: the public Reserve
// wrapper and the RPC's already-locked call. The RPC must not call
// Reserve as well (which would take workspaceMu twice).
{"../../core/host/master/volume_delete_authority.go", map[string]int{"VolumeDeleteAuthority": 2, "reserveLocked": 2, "NoLiveLease": 1}},
{"../../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 {
@@ -37,7 +34,7 @@ func TestChunkVolumeDeleteAuthorityRPCSites(t *testing.T) {
return true
}
switch sel.Sel.Name {
case "Dial", "DialMasterFromEnv", "ReserveVolumeDeletion", "CheckVolumeNoLiveLease", "MarkVolumeDeleting", "AbortVolumeDeleting", "CommitVolumeDeleting", "VolumeDeleteAuthority", "Reserve", "reserveLocked", "NoLiveLease":
case "Dial", "DialMasterFromEnv", "ReserveVolumeDeletion", "CheckVolumeNoLiveLease", "MarkVolumeDeleting", "AbortVolumeDeleting", "CommitVolumeDeleting", "VolumeDeleteAuthority", "Reserve", "NoLiveLease":
got[sel.Sel.Name]++
}
return true
@@ -1,79 +0,0 @@
package main
import (
"context"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"syscall"
"testing"
"testing/synctest"
)
// Keep the refused-dial fixture independent of port reuse and host forwarding:
// net/http still builds and sends the request through its real Transport,
// whose dial boundary supplies the kernel's typed refusal.
func installRefusedHolderDial(t *testing.T) *atomic.Int32 {
t.Helper()
calls := new(atomic.Int32)
transport := &http.Transport{DialContext: func(context.Context, string, string) (net.Conn, error) {
calls.Add(1)
return nil, &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
}}
old := chunkHTTPClient
chunkHTTPClient = &http.Client{Transport: transport}
t.Cleanup(func() { transport.CloseIdleConnections(); chunkHTTPClient = old })
return calls
}
func TestPlainDetachRefusedDialIsRemoteUnavailable(t *testing.T) {
calls := installRefusedHolderDial(t)
code, out, errOut := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", "http://holder")
e := chunkErrorOut(t, out)
if code != 75 || e.Code != codeUnavailableCLI || !e.Retryable || strings.Contains(errOut, "outcome_unknown") || calls.Load() != 1 {
t.Fatalf("refused dial: exit=%d dials=%d stdout=%s stderr=%s", code, calls.Load(), out, errOut)
}
}
func TestPlainDetachLostAnswerAfterSendStaysUnknown(t *testing.T) {
var posts atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
t.Errorf("unexpected method %s", r.Method)
}
_, _ = io.Copy(io.Discard, r.Body)
posts.Add(1)
c, _, err := w.(http.Hijacker).Hijack()
if err != nil {
t.Error(err)
return
}
_ = c.Close() // The request arrived; its outcome cannot be inferred from EOF.
}))
defer srv.Close()
code, out, _ := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", srv.URL)
if code != chunkExitUnknown || chunkErrorOut(t, out).Code != "outcome_unknown" || posts.Load() != 1 {
t.Fatalf("lost reply: exit=%d posts=%d out=%s", code, posts.Load(), out)
}
}
func TestPlainDetachPollDialFailureKeepsAdmittedOutcomeUnknown(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
posts, polls := 0, 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodPost {
posts++
return cutPollReply(202, `{"apiVersion":1,"code":"in_progress","cutID":"d1","sequence":1}`), nil
}
polls++
return nil, &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
})
code, out, _ := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", "http://holder", "--timeout", "1ms")
if code != chunkExitUnknown || chunkErrorOut(t, out).Code != "outcome_unknown" || posts != 1 || polls == 0 {
t.Fatalf("admitted detach: exit=%d posts=%d polls=%d out=%s", code, posts, polls, out)
}
})
}
@@ -1,183 +0,0 @@
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// One output contract across every chunk command: a transport outage is a
// temporary failure, while a caller timeout or permanent refusal stays distinct.
func TestChunkErrorFamilyAnswerTable(t *testing.T) {
for _, command := range []string{"snapshots", "show", "usage", "snapshot-delete", "retain", "release", "volume-delete", "verify", "restore", "snapshot", "cut", "detach"} {
for _, tc := range []struct {
name string
err error
code string
exit int
retry bool
advice string
only string
}{
{"remote", status.Error(codes.Unavailable, "connection refused"), "remote_unavailable", 75, true, "rpc error: code = Unavailable desc = connection refused; retry the same operation when the remote is reachable", ""},
{"caller timeout", context.DeadlineExceeded, "deadline_exceeded", 1, true, context.DeadlineExceeded.Error(), ""},
{"caller cancel", context.Canceled, "canceled", 1, false, "operation interrupted by its caller", ""},
{"dependents", layout.ErrHasDependents, "snapshot_has_dependents", 1, false, layout.ErrHasDependents.Error(), ""},
{"committed reservation final barrier", finalLeaseBarrierErr(status.Error(codes.FailedPrecondition, "workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed")), "not_admitted", 75, true, "retry the same --request-id after 2026-12-03T13:00:00Z: " + chunkstore.ErrNotAdmitted.Error() + ": rpc error: code = FailedPrecondition desc = workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed", "volume-delete"},
{"Reserve live holder with moving horizon", authorityErr(status.Error(codes.FailedPrecondition, "workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed")), "not_admitted", 1, false, "stop the volume first: " + chunkstore.ErrNotAdmitted.Error() + ": rpc error: code = FailedPrecondition desc = workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed", "volume-delete"},
{"restart required", authorityErr(status.Error(codes.FailedPrecondition, "workspace delete: lease persistence uncertain; restart required")), "not_admitted", 1, false, chunkstore.ErrNotAdmitted.Error() + ": rpc error: code = FailedPrecondition desc = workspace delete: lease persistence uncertain; restart required", "volume-delete"},
{"skipped authority", authorityErr(status.Error(codes.FailedPrecondition, "workspace delete: authority records were skipped during recovery; lease absence is unknown")), "not_admitted", 1, false, chunkstore.ErrNotAdmitted.Error() + ": rpc error: code = FailedPrecondition desc = workspace delete: authority records were skipped during recovery; lease absence is unknown", "volume-delete"},
{"live holder", authorityErr(status.Error(codes.FailedPrecondition, "volume has a live authority line; stop the holder before deleting")), "not_admitted", 1, false, chunkstore.ErrNotAdmitted.Error() + ": rpc error: code = FailedPrecondition desc = volume has a live authority line; stop the holder before deleting", "volume-delete"},
{"invalid horizon", authorityErr(status.Error(codes.FailedPrecondition, "workspace delete: live until tomorrow: lease expiry unknown")), "not_admitted", 1, false, chunkstore.ErrNotAdmitted.Error() + ": rpc error: code = FailedPrecondition desc = workspace delete: live until tomorrow: lease expiry unknown", "volume-delete"},
} {
if tc.only != "" && command != tc.only {
continue
}
t.Run(command+"/"+tc.name, func(t *testing.T) {
var out, diag bytes.Buffer
exit := chunkResult(command, nil, tc.err, &out, &diag)
answer := chunkErrorOut(t, out.String())
if exit != tc.exit || answer.Code != tc.code || answer.Retryable != tc.retry || answer.Message != tc.advice {
t.Fatalf("exit=%d answer=%+v; want %d/%s/retry=%v/advice=%q", exit, answer, tc.exit, tc.code, tc.retry, tc.advice)
}
})
}
}
}
func TestUnreachableFilerAtTheCommandWindowIsTemporary(t *testing.T) {
previousResolve := resolveVolumeID
t.Cleanup(func() { resolveVolumeID = previousResolve })
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{4}, nil }
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := listener.Addr().String()
if err := listener.Close(); err != nil {
t.Fatal(err)
}
for _, command := range []string{"snapshot-delete", "verify"} {
t.Run(command, func(t *testing.T) {
args := []string{command, "--volume", "v1", "--chunk-filer", addr, "--timeout", "100ms"}
if command == "snapshot-delete" {
args = append(args, "--master", "fixture:1", "--name", "daily", "--request-id", "offline-filer")
}
exit, out, diag := runChunk(args...)
answer := chunkErrorOut(t, out)
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable {
t.Fatalf("exit=%d answer=%+v stderr=%s", exit, answer, diag)
}
})
}
}
func TestChunkHTTPRemoteAnswerKeepsItsBodyAndUsesTemporaryExit(t *testing.T) {
const body = `{"code":"remote_unavailable","message":"filer stopped","retryable":true}`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(503); fmt.Fprint(w, body) }))
defer server.Close()
for _, command := range []string{"snapshot", "detach"} {
t.Run(command, func(t *testing.T) {
var out, diag bytes.Buffer
exit := chunkPost(command, server.URL, "/chunk/"+command, time.Second, map[string]any{"volumeID": "v1"}, &out, &diag)
if exit != 75 || out.String() != body || !strings.Contains(diag.String(), "retry") {
t.Fatalf("exit=%d out=%s stderr=%s", exit, &out, &diag)
}
})
}
}
func TestSnapshotDeleteDependentsIsNotAutomaticRetry(t *testing.T) {
ctx := context.Background()
mem := newMemChunkStore()
useMemChunkStore(t, mem)
v := cliVolume(t, mem, "dependent-source", "daily")
cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI)
st, _ := cat.Store(v)
h, _, err := st.ReadHead(ctx)
if err != nil {
t.Fatal(err)
}
s := h.Snapshots["daily"]
s.Gen = h.Gen + 1
s.Dependents = []layout.Dependent{{Target: "target", TargetID: layout.VolumeID{2}, Root: s.Root}}
h.Version, h.Snapshots["daily"] = layout.HeadVersion1, s
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", "dependent-delete"})
for i := 0; i < 2; i++ {
exit, out, diag := runChunk(args...)
answer := chunkErrorOut(t, out)
if exit != 1 || answer.Code != "snapshot_has_dependents" || answer.Retryable || !strings.Contains(answer.Message, "dependent") {
t.Fatalf("attempt%d exit=%d answer=%+v stderr=%s", i, exit, answer, diag)
}
}
op, found, err := st.ReadSnapshotOperation(ctx, "dependent-delete", "delete")
if err != nil || !found || op.State != "stalled" {
t.Fatalf("receipt lost resumability: %+v %v", op, err)
}
if _, err := layout.RunReleaseDependent(ctx, st, layout.VolumeID{2}); err != nil {
t.Fatal(err)
}
if exit, out, diag := runChunk(args...); exit != 0 {
t.Fatalf("after releasing dependency: %d %s %s", exit, out, diag)
}
}
func TestSnapshotDeleteWorkTransportUsesSharedClassifier(t *testing.T) {
ctx := context.Background()
mem := newMemChunkStore()
cat, _ := chunkstore.NewBCatalog(mem, mem, "/blocks")
v := chunkstore.VolumeRef{Name: "work-failure", ID: layout.VolumeID{3}}
if _, err := cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
t.Fatal(err)
}
st, _ := cat.Store(v)
op, err := st.AdmitSnapshotDeleteOperation(ctx, "work-remote", "daily", func(context.Context) (uint64, error) { return 2, nil })
if err != nil {
t.Fatal(err)
}
var out, diag bytes.Buffer
exit := chunkRunCatalogSnapshotDelete(ctx, cat, v, op, func(context.Context, *chunkstore.LayoutStore, chunkstore.SnapshotOperation) error {
return status.Error(codes.Unavailable, "filer stopped after admission")
}, false, &out, &diag)
answer := chunkErrorOut(t, out.String())
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable {
t.Fatalf("exit=%d answer=%+v", exit, answer)
}
retained, err := st.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence)
if err != nil || retained.State != "stalled" {
t.Fatalf("lost resumability: %+v %v", retained, err)
}
}
func TestVerifyIncompleteTransportPreservesPartialProgress(t *testing.T) {
partial := layout.VerifyResult{Roots: 2, Segments: 3, Chunks: 7, ChunksZero: 1, Incomplete: "payload read interrupted", OrphansChecked: true, MasterIdentityChecked: true}
var out, diag bytes.Buffer
exit := verifyIncomplete(partial, status.Error(codes.Unavailable, "filer stopped"), &out, &diag)
var answer struct {
chunkErrBody
Verify layout.VerifyResult `json:"verify"`
}
if err := json.Unmarshal(out.Bytes(), &answer); err != nil {
t.Fatal(err)
}
const message = "rpc error: code = Unavailable desc = filer stopped; retry the same operation when the remote is reachable"
if exit != 75 || answer.Code != "remote_unavailable" || !answer.Retryable || answer.Message != message || !reflect.DeepEqual(answer.Verify, partial) || diag.String() != "sw-block ops chunk verify: remote_unavailable: "+message+" (incomplete)\n" {
t.Fatalf("exit=%d answer=%+v stderr=%q", exit, answer, diag.String())
}
}
@@ -1,79 +0,0 @@
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"testing"
"testing/synctest"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
func TestSnapshotDeleteCLILayoutBusyIsTypedRetryable(t *testing.T) {
for _, tc := range []struct {
name string
err error
code string
}{
{"open clean transaction", fmt.Errorf("delete: %w", layout.ErrBusy), "layout_busy"},
{"queue full remains specific", layout.ErrQueueFull, "queue_full"},
} {
t.Run(tc.name, func(t *testing.T) {
if got := layoutCode(tc.err); got != tc.code {
t.Errorf("layoutCode: %q; want %q", got, tc.code)
}
var out, diag bytes.Buffer
exit := chunkResult("snapshot-delete", nil, tc.err, &out, &diag)
answer := chunkErrorOut(t, out.String())
if exit != chunkExitFailed || answer.Code != tc.code || !answer.Retryable {
t.Fatalf("CLI delete: exit=%d answer=%+v; want failure with %s retryable", exit, answer, tc.code)
}
})
}
}
func TestSnapshotDeleteCLIRetriesBusyWithSameIdentityWithinWindow(t *testing.T) {
for _, neverReady := range []bool{false, true} {
t.Run(fmt.Sprintf("neverReady=%v", neverReady), func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
mem := newMemChunkStore()
useMemChunkStore(t, mem)
v := cliVolume(t, mem, "v1", "daily")
cat, _ := chunkstore.NewBCatalog(mem, mem, defaultChunkPathCLI)
st, _ := cat.Store(v)
ctx, cancel := context.WithTimeout(context.Background(), 350*time.Millisecond)
defer cancel()
op, err := st.AdmitSnapshotDeleteOperation(ctx, "same-delete", "daily", func(context.Context) (uint64, error) { return 19, nil })
if err != nil {
t.Fatal(err)
}
calls := 0
work := func(ctx context.Context, st *chunkstore.LayoutStore, running chunkstore.SnapshotOperation) error {
calls++
if running.ID != op.ID || running.Instance != op.Instance || running.Sequence != op.Sequence || *running.TargetGeneration != 19 {
t.Fatal("busy retry changed the admitted target or identity")
}
if neverReady || calls < 3 {
return layout.ErrBusy
}
_, err := st.AdvanceSnapshotOperation(ctx, running, "succeeded", json.RawMessage(`{"state":"deleted"}`), "")
return err
}
var diag bytes.Buffer
_, err = chunkCatalogSnapshotDeleteAnswer(ctx, cat, v, op, work, false, &diag)
if neverReady {
if !errors.Is(err, layout.ErrBusy) || ctx.Err() == nil || calls < 2 || calls > 4 {
t.Fatalf("busy window: calls=%d ctx=%v err=%v", calls, ctx.Err(), err)
}
} else if err != nil || calls != 3 {
t.Fatalf("retry after release: calls=%d err=%v", calls, err)
}
})
})
}
}
+7 -4
View File
@@ -42,10 +42,13 @@ func chunkMinRequest() time.Duration { return min(time.Second, chunkRequestBound
// 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 repeats snapshot and detach requests after a retryable or
// uncertain answer. Manual cuts use one POST and read-only handle polling.
// Each request carries the same snapshot intent or detach body; the holder
// answers an already committed snapshot from HEAD rather than taking it again.
// 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
@@ -12,6 +12,7 @@ import (
"net/http/httptest"
"strings"
"testing"
)
type failWriter struct{}
@@ -29,9 +30,7 @@ func (shortWriter) Write(p []byte) (int, error) {
func sizedServer(t *testing.T, n int) *httptest.Server {
t.Helper()
prefix, suffix := []byte(`{"volumeID":"v1","cutLSN":9,"headGen":4,"padding":"`), []byte(`"}`)
body := append(prefix, bytes.Repeat([]byte("a"), n-len(prefix)-len(suffix))...)
body = append(body, suffix...)
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)
@@ -44,11 +43,11 @@ func sizedServer(t *testing.T, n int) *httptest.Server {
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 != chunkExitUnknown || out.Len() > 1024 || !strings.Contains(errb.String(), "exceeds") {
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 != "outcome_unknown" {
t.Fatalf("200 body one byte over the limit: %+v, want the unknown-outcome error body", e)
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()
@@ -58,7 +57,7 @@ func TestOpsChunk_OversizedResponseIsRefused(t *testing.T) {
}
func TestOpsChunk_LostResultFailsTheCommand(t *testing.T) {
srv, _ := chunkServer(t, 200, `{"volumeID":"v1","cutLSN":9,"headGen":4}`)
srv, _ := chunkServer(t, 200, `{"volumeID":"v1","cutLSN":9}`)
store := newMemChunkStore()
useMemChunkStore(t, store)
v := cliVolume(t, store, "v1", "s1")
+2 -4
View File
@@ -12,11 +12,9 @@ import (
// 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, deadline time.Time, body map[string]any, stdout, stderr io.Writer) int {
func chunkPlainDetachPost(addr, volume string, timeout time.Duration, body map[string]any, stdout, stderr io.Writer) int {
var out bytes.Buffer
// CutTime r7: one admission, then the detach's handle is polled; only its
// sequence rises renew the wait, and --deadline is the only total bound.
code := chunkObserveHandle("detach", "/chunk/detach", addr, timeout, deadline, body, &out, stderr)
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)
+2 -43
View File
@@ -4,14 +4,12 @@ import (
"net/http"
"strings"
"testing"
"testing/synctest"
"time"
)
// 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 = `{"apiVersion":1,"volumeID":"vol","headGen":11}`
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") {
@@ -43,7 +41,7 @@ func TestOpsChunkPlainDetachRefusesInvalidMixBeforeHTTP(t *testing.T) {
func TestOpsChunkPlainDetachPreservesTypedFailure(t *testing.T) {
for _, reason := range []string{"busy", "fenced", "outcome_unknown"} {
t.Run(reason, func(t *testing.T) {
reply := `{"apiVersion":1,"code":"` + reason + `","message":"seal refused","retryable":true}`
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:") {
@@ -52,42 +50,3 @@ func TestOpsChunkPlainDetachPreservesTypedFailure(t *testing.T) {
})
}
}
// An observed plain detach whose handle the holder ends outcome_unknown is
// reported unknown (exit 3) at once: one admission, one read, no re-POST.
func TestOpsChunkPlainDetachHandleEndedUnknownIsReportedAtOnce(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
start, posts, polls := time.Now(), 0, 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodPost {
posts++
return cutPollReply(202, `{"apiVersion":1,"code":"in_progress","cutID":"d1","sequence":1}`), nil
}
polls++
return cutPollReply(503, `{"apiVersion":1,"code":"outcome_unknown","cutID":"d1","message":"publish answer lost","retryable":true}`), nil
})
code, out, _ := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", "http://holder", "--timeout", "1m")
if code != 3 || posts != 1 || polls != 1 || !strings.Contains(out, `"code":"outcome_unknown"`) || time.Since(start) >= time.Minute {
t.Fatalf("code=%d posts=%d polls=%d elapsed=%s out=%s", code, posts, polls, time.Since(start), out)
}
})
}
// A first answer that already carries the detach's id with a terminal
// outcome_unknown (the admitted worker ended unknown within the window) is
// unknown (exit 3), never a definite refusal, with one POST.
func TestOpsChunkPlainDetachFirstAnswerUnknownWithItsIDIsUnknown(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
posts := 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodPost {
posts++
}
return cutPollReply(503, `{"apiVersion":1,"code":"outcome_unknown","cutID":"d1","message":"publish answer lost","retryable":true}`), nil
})
code, out, _ := runChunk("detach", "--plain", "--volume", "v1", "--status-addr", "http://holder", "--timeout", "1m")
if code != 3 || posts != 1 || !strings.Contains(out, `"code":"outcome_unknown"`) {
t.Fatalf("code=%d posts=%d out=%s, want unknown after one POST", code, posts, out)
}
})
}
@@ -29,32 +29,15 @@ type scripted struct {
replies []scriptedReply
hold time.Duration
status func(n int, volume string) (int, string, time.Duration)
// sync answers a 200 reply as it is even to an asynchronous snapshot
// request (a holder older than this release). Otherwise such a reply is
// the snapshot operation's result: admitted (202), then read succeeded.
sync bool
mu sync.Mutex
posts []postRecord
gets int
ops map[string]string // request id -> the operation's result
}
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.MethodGet && r.URL.Path == "/chunk/operations" {
id := r.URL.Query().Get("request_id")
s.mu.Lock()
result, ok := s.ops[id]
s.mu.Unlock()
if !ok {
http.NotFound(w, r)
return
}
_, _ = io.WriteString(w, `{"operation_id":"`+id+`","state":"succeeded","result":`+result+`}`)
return
}
if r.Method != http.MethodPost {
s.mu.Lock()
n := s.gets
@@ -91,18 +74,6 @@ func (s *scripted) start(t *testing.T) *httptest.Server {
return
}
w.Header().Set("Content-Type", "application/json")
if id, _ := m["requestID"].(string); rep.status == http.StatusOK && !s.sync && r.Header.Get("Prefer") == "respond-async" {
s.mu.Lock()
if s.ops == nil {
s.ops = map[string]string{}
}
s.ops[id] = rep.body
s.mu.Unlock()
w.Header().Set("Location", "/chunk/operations?request_id="+id)
w.WriteHeader(http.StatusAccepted)
_, _ = io.WriteString(w, `{"operation_id":"`+id+`","state":"accepted"}`)
return
}
w.WriteHeader(rep.status)
_, _ = io.WriteString(w, rep.body)
}))
@@ -133,7 +104,7 @@ const (
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 = `{"apiVersion":1,"code":"outcome_unknown","message":"storage: chunk HEAD CAS outcome unknown","retryable":true}`
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
@@ -371,36 +342,23 @@ func TestChunkLoopReportsTheHolderProgressSinceTheFirstRequest(t *testing.T) {
}
}
// A cut with an unidentified admission outcome must not start a second cut.
// A plain detach runs on a handle too: a refused admission is reported as it
// is, without a second POST; a sealed answer prints its generation once.
func TestChunkCutUnknownAndPlainDetachRefusalAreNotReposted(t *testing.T) {
// 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 != chunkExitUnknown || !strings.Contains(out, `"code":"outcome_unknown"`) || len(s.recorded()) != 1 {
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 s.recorded()[0].body["observe"] != nil {
t.Fatal("cut still sends the removed observe opt-in")
}
if strings.Contains(errs, "stopped guest I/O") {
t.Fatalf("cut stderr %q: an outcome_unknown cut does not stop guest I/O", errs)
}
// A plain detach's answers speak the versioned cut API.
versioned := func(body string) string { return `{"apiVersion":1,` + body[1:] }
s2 := &scripted{replies: []scriptedReply{{503, versioned(timedOut)}, {200, versioned(sealed)}}}
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 != chunkExitFailed || out != versioned(timedOut) || len(s2.recorded()) != 1 {
t.Fatalf("refused plain detach: exit %d stdout %q stderr %q, %d requests, want the refusal and one request", code, out, errs, len(s2.recorded()))
}
s3 := &scripted{replies: []scriptedReply{{200, versioned(sealed)}}}
srv3 := s3.start(t)
code, out, errs = runChunk("detach", "--plain", "--volume", "v1", "--status-addr", srv3.URL, "--timeout", "5s")
if code != 0 || out != versioned(sealed) || len(s3.recorded()) != 1 {
t.Fatalf("plain detach: exit %d stdout %q stderr %q, %d requests", code, out, errs, len(s3.recorded()))
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)
@@ -425,10 +383,7 @@ func TestChunkDetachOutcomeUnknownSettles(t *testing.T) {
{"fenced", []scriptedReply{{503, detachUnknown}, {409, detachFenced}}, chunkExitFailed, detachFenced},
} {
t.Run(tc.name, func(t *testing.T) {
// A non-plain detach still settles by repeating the request. An observed
// plain detach is never re-posted: a handle the holder ends outcome_unknown
// is reported unknown.
for _, plain := range []bool{false} {
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"}
@@ -498,16 +453,3 @@ func TestChunkDetachTimeoutHelpNamesTheGuestStop(t *testing.T) {
t.Fatalf("detach help %q", errs)
}
}
// A holder that answers a snapshot synchronously, without an operation, is
// older than this release: the command ends unknown (exit 3) naming the
// upgrade, and relays no snapshot.
func TestChunkSnapshotSynchronousHolderIsUnsupported(t *testing.T) {
shortLoop(t, 200*time.Millisecond, 10*time.Millisecond, 10*time.Millisecond)
s := &scripted{replies: []scriptedReply{{200, published}}, sync: true}
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 != chunkExitUnknown || strings.Contains(out, `"cutLSN"`) || !strings.Contains(out, "upgrade it") {
t.Fatalf("exit %d stdout %q stderr %q: want unknown naming the upgrade", code, out, errs)
}
}
@@ -107,7 +107,7 @@ func TestOpsChunkRestoreUsesOnlyMasterCreate(t *testing.T) {
return nil, status.Error(codes.Unavailable, "filer unreachable")
}
var out, errs bytes.Buffer
if code := run(args, &out, &errs); code != 75 || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), codeUnavailableCLI) {
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())
}
}
@@ -138,9 +138,8 @@ func TestOpsChunk_StartCheckIsBoundedByTheTimeout(t *testing.T) {
case <-time.After(5 * time.Second):
t.Fatalf("%s: a stalled start check held the command past its 200ms --timeout", name)
}
answer := chunkErrorOut(t, out.String())
if code != chunkExitFailed || answer.Code != chunkstore.CodeDeadlineExceeded || !answer.Retryable {
t.Errorf("%s: exit %d, out %q; want a retryable deadline_exceeded refusal for the caller's timeout", name, code, out.String())
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())
}
}
}
+11 -25
View File
@@ -23,29 +23,15 @@ type chunkRoute struct {
func chunkServer(t *testing.T, status int, reply string) (*httptest.Server, *[]chunkRoute) {
t.Helper()
var got []chunkRoute
results := map[string]string{} // snapshot request id -> its operation's result
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 id := r.URL.Query().Get("request_id"); r.Method == http.MethodGet && r.URL.Path == "/chunk/operations" && results[id] != "" {
_, _ = io.WriteString(w, `{"operation_id":"`+id+`","state":"succeeded","result":`+results[id]+`}`)
return
}
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")
// A snapshot is an operation: its success answer is the operation's
// result, read from the handle after the admission.
if id, _ := m["requestID"].(string); status == http.StatusOK && r.Header.Get("Prefer") == "respond-async" {
results[id] = reply
w.Header().Set("Location", "/chunk/operations?request_id="+id)
w.WriteHeader(http.StatusAccepted)
_, _ = io.WriteString(w, `{"operation_id":"`+id+`","state":"accepted"}`)
return
}
w.WriteHeader(status)
_, _ = io.WriteString(w, reply)
}))
@@ -60,9 +46,9 @@ func runChunk(args ...string) (int, string, string) {
}
func TestOpsChunk_HTTPCommandsSendSpecRequests(t *testing.T) {
srv, got := chunkServer(t, 200, `{"volumeID":"v1","cutLSN":9,"headGen":4}`)
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,"headGen":4}` {
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")
@@ -98,7 +84,7 @@ func TestOpsChunk_HTTPCommandsSendSpecRequests(t *testing.T) {
}
func TestOpsChunk_HTTPFailureIsTyped(t *testing.T) {
srv, _ := chunkServer(t, 409, `{"apiVersion":1,"code":"not_primary","message":"volume v1 is not a healthy primary here","retryable":false}`)
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") {
@@ -134,14 +120,14 @@ func TestOpsChunk_ErrorsAreJSONOnStdout(t *testing.T) {
if code, out, _ := runChunk("cut", "--bogus"); code != 2 || chunkErrorOut(t, out).Code != "bad_request" {
t.Fatalf("unknown flag: exit %d %q", code, out)
}
t.Run("refused holder dial", func(t *testing.T) {
installRefusedHolderDial(t)
if code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://holder"); code != 75 {
t.Fatalf("unreachable blockvolume: exit %d %q", code, out)
} else if e := chunkErrorOut(t, out); e.Code != codeUnavailableCLI || !e.Retryable {
t.Fatalf("unreachable blockvolume: %+v, want remote_unavailable and retryable", e)
}
})
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)
@@ -1,56 +0,0 @@
package main
import (
"context"
"errors"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"net"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// chunkTransportFailure classifies transport provenance, never diagnostic text.
// Cancellation and wrapped caller deadlines are not remote failures. A gRPC
// DeadlineExceeded status alone can be a remote request timeout; callers with
// their own context must retain its cause separately.
// Known catalog/kernel outcomes keep priority in chunkResult.
func chunkTransportFailure(err error) bool {
if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return false
}
var catalog *chunkstore.CatalogError
if errors.As(err, &catalog) {
return catalog.Code == chunkstore.CodeRemoteUnavailable
}
// ErrHolderActive also wraps an unanswered NoLiveLease check. That
// wrapper is a refusal to proceed, not proof that a live holder exists.
if layoutCode(err) != "" && !errors.Is(err, layout.ErrHolderActive) {
return false
}
switch status.Code(err) {
case codes.Unavailable, codes.DeadlineExceeded:
return true
}
var address *net.AddrError
var syntax *net.ParseError
if errors.As(err, &address) || errors.As(err, &syntax) {
return false
}
var network net.Error
return errors.As(err, &network)
}
// gRPC cancellation does not wrap context.Canceled. Keep it distinct from an
// unavailable remote, including when a boundary has wrapped the status.
func chunkCanceled(err error) bool {
var catalog *chunkstore.CatalogError
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled) {
return false
}
if errors.As(err, &catalog) || (layoutCode(err) != "" && !errors.Is(err, layout.ErrHolderActive)) {
return false
}
return errors.Is(err, context.Canceled) || status.Code(err) == codes.Canceled
}
@@ -1,178 +0,0 @@
package main
import (
"bytes"
"context"
"fmt"
"google.golang.org/grpc"
"net"
"strings"
"sync/atomic"
"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/rpc/control"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type transportLookupStore struct {
*memChunkStore
failure error
calls *atomic.Int64
}
func (s transportLookupStore) LookupEntry(context.Context, string, string) (*filerpb.Entry, error) {
s.calls.Add(1)
return nil, s.failure
}
// Every ops chunk command that reaches a filer/master: resolve, lazy dial,
// topology census and metadata reads are separate boundaries. Restore is a
// single master RPC and never opens a filer. Holder-only HTTP commands are
// covered separately by TestOpsChunk_ErrorsAreJSONOnStdout.
func TestOpsChunkTransportFailureMatrix(t *testing.T) {
for _, failure := range []struct {
name string
err error
}{
{"unavailable", status.Error(codes.Unavailable, "connection refused")},
{"rpc-deadline", status.Error(codes.DeadlineExceeded, "remote request expired")},
{"rpc-canceled", status.Error(codes.Canceled, "RPC interrupted")},
{"network", &net.OpError{Op: "dial", Net: "tcp", Err: fmt.Errorf("connection refused")}},
} {
for _, phase := range []string{"resolve", "dial", "census", "read", "restore", "reserve", "no-lease"} {
for _, command := range []string{"snapshots", "show", "usage", "snapshot-delete", "retain", "retain-dry", "release", "volume-delete", "verify", "restore"} {
if (phase == "reserve" || phase == "no-lease") && (command != "volume-delete" || failure.name == "network") {
continue
}
if (command == "restore") != (phase == "restore") {
continue
}
if phase == "census" && (command == "snapshots" || command == "show" || command == "usage" || command == "retain-dry") {
continue
}
t.Run(failure.name+"/"+phase+"/"+command, func(t *testing.T) {
mem := newMemChunkStore()
useMemChunkStore(t, mem)
v := cliVolume(t, mem, "transport-source", "daily")
target := chunkstore.VolumeRef{Name: "target", ID: layout.VolumeID{2}}
var args []string
switch command {
case "restore":
args = cliArgs("restore", []string{"--source", v.Name, "--target", target.Name, "--snapshot", "daily"})
case "release":
args = cliArgs("release", volArgs("source", v), volArgs("target", target))
case "snapshot-delete":
args = cliArgs(command, volArgs("volume", v), []string{"--name", "daily"})
case "volume-delete":
args = cliArgs(command, volArgs("volume", v), []string{"--request-id", "delete", "--timeout", "20ms"})
case "retain-dry":
args = cliArgs("retain", volArgs("volume", v), []string{"--dry-run"})
default:
args = cliArgs(command, volArgs("volume", v))
}
var calls atomic.Int64
switch phase {
case "reserve", "no-lease":
addr := startTransportAuthority(t, &transportAuthority{failure: failure.err, phase: phase, calls: &calls})
args = cliArgs("volume-delete", volArgs("volume", v), []string{"--request-id", "delete", "--master", addr, "--timeout", "20ms"})
case "resolve":
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) {
calls.Add(1)
return layout.VolumeID{}, failure.err
}
case "dial":
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { calls.Add(1); return nil, nil, failure.err }
case "census":
checkSingleFiler = func(context.Context, chunkstore.Filer) error {
calls.Add(1)
return fmt.Errorf("%w: configuration: %w", chunkstore.ErrNotSingleFiler, failure.err)
}
case "read":
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
return transportLookupStore{mem, failure.err, &calls}, func() error { return nil }, nil
}
case "restore":
restoreCreateRPC = func(context.Context, string, *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
calls.Add(1)
return nil, failure.err
}
}
var out, diag bytes.Buffer
exit := runOpsChunk(args, &out, &diag)
e := chunkErrorOut(t, out.String())
wantCode, wantRetry, wantExit := "remote_unavailable", true, 75
if failure.name == "rpc-canceled" {
wantCode, wantRetry, wantExit = "canceled", false, 1
}
if calls.Load() == 0 || exit != wantExit || e.Code != wantCode || e.Retryable != wantRetry || (wantCode == codeUnavailableCLI && !strings.Contains(e.Message, "retry")) {
t.Errorf("calls=%d exit=%d answer=%+v", calls.Load(), exit, e)
}
})
}
}
}
}
// Exercise the real lazy gRPC client and census wrapper, not a seam returning
// an already-classified error. No process is listening at this address.
func TestOpsChunkVerifyUnreachableCensusPreservesTransport(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := listener.Addr().String()
if err := listener.Close(); err != nil {
t.Fatal(err)
}
// Bound the real census call separately from the pass inactivity window,
// so the test observes the unreachable remote, not a racing pass cancel.
previousCheck := checkSingleFiler
t.Cleanup(func() { checkSingleFiler = previousCheck })
checkSingleFiler = func(ctx context.Context, f chunkstore.Filer) error {
call, cancel := context.WithTimeoutCause(ctx, 50*time.Millisecond, chunkstore.ErrSingleFilerWindowExpired)
defer cancel()
return previousCheck(call, f)
}
code, out, _ := runChunk("verify", "--volume", "v1", "--chunk-filer", addr, "--timeout", "5s")
e := chunkErrorOut(t, out)
if code != 75 || e.Code != "remote_unavailable" || !e.Retryable {
t.Fatalf("exit=%d answer=%+v", code, e)
}
}
type transportAuthority struct {
control.UnimplementedLifecycleServiceServer
failure error
phase string
calls *atomic.Int64
}
func (s *transportAuthority) ReserveVolumeDeletion(context.Context, *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) {
if s.phase == "reserve" {
s.calls.Add(1)
return nil, s.failure
}
return &control.MarkVolumeDeletingResponse{Known: true}, nil
}
func (s *transportAuthority) CheckVolumeNoLiveLease(context.Context, *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) {
s.calls.Add(1)
return nil, s.failure
}
func startTransportAuthority(t *testing.T, s *transportAuthority) string {
t.Helper()
listener, 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(listener) }()
t.Cleanup(server.Stop)
return listener.Addr().String()
}
@@ -26,7 +26,7 @@ func jsonCode(t *testing.T, out []byte) string {
// 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
// transport failure is retryable remote_unavailable).
// failure stays bad_request).
func TestOpsChunkTypedRefusalCodes(t *testing.T) {
prevRestore, prevResolve := restoreCreateRPC, resolveVolumeID
t.Cleanup(func() { restoreCreateRPC, resolveVolumeID = prevRestore, prevResolve })
@@ -55,7 +55,7 @@ func TestOpsChunkTypedRefusalCodes(t *testing.T) {
code string
}{
{"unknown volume", status.Error(codes.NotFound, "volume not found"), chunkExitFailed, "volume_not_found"},
{"master unreachable", status.Error(codes.Unavailable, "connection refused"), 75, codeUnavailableCLI},
{"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
+3 -23
View File
@@ -114,9 +114,6 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
}
f, closeFn, err := dialChunkFiler(filer)
if err != nil {
if chunkCanceled(err) || chunkTransportFailure(err) {
return verifyIncomplete(layout.VerifyResult{}, err, stdout, stderr)
}
return usage(err.Error())
}
defer closeFn()
@@ -159,18 +156,7 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
// errVerifyStalled is the cause of a verify pass ended by its no-progress
// window: a transient failure, answered like a deadline.
type verifyStallError struct{}
func (verifyStallError) Error() string {
return "verify: no object read completed within the --timeout no-progress window"
}
// During startup this is an internal window, not a caller deadline.
func (verifyStallError) Is(target error) bool {
return target == chunkstore.ErrSingleFilerWindowExpired
}
var errVerifyStalled error = verifyStallError{}
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
@@ -291,16 +277,10 @@ func verifyIncomplete(res layout.VerifyResult, err error, stdout, stderr io.Writ
Verify layout.VerifyResult `json:"verify"`
}{Verify: res}
body.Code, body.Message = codeInternalCLI, err.Error()
if chunkCanceled(err) {
body.Code, body.Message = codeCanceledCLI, "operation interrupted by its caller"
} else if chunkTransportFailure(err) {
body.Code, body.Retryable = codeUnavailableCLI, true
}
if errors.Is(err, context.DeadlineExceeded) || (errors.Is(err, errVerifyStalled) && !chunkTransportFailure(err)) {
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled) {
body.Code, body.Retryable = chunkstore.CodeDeadlineExceeded, true
}
body.Message = chunkErrorAdvice(body.Code, body.Retryable, body.Message)
fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %s (incomplete)\n", body.Code, body.Message)
chunkResult("verify", body, nil, stdout, stderr)
return chunkErrorExit(chunkExitFailed, body.Code, body.Retryable)
return chunkExitFailed
}
@@ -232,9 +232,8 @@ func TestOpsChunk_VerifyStartCheckIsBoundedByTheTimeout(t *testing.T) {
case <-time.After(5 * time.Second):
t.Fatalf("a stalled start check held verify past its 200ms --timeout")
}
answer := chunkErrorOut(t, out.String())
if code != chunkExitFailed || answer.Code != chunkstore.CodeDeadlineExceeded || !answer.Retryable {
t.Errorf("verify: exit %d, out %q; want a retryable deadline_exceeded refusal for the caller's timeout", code, out.String())
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())
}
}
@@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"io"
"strings"
"sync"
"time"
@@ -86,53 +85,17 @@ func (m *masterAuthority) Reserve(ctx context.Context) error {
func (m *masterAuthority) NoLiveLease(ctx context.Context) error {
_, err := m.lc.CheckVolumeNoLiveLease(ctx, m.req)
return finalLeaseBarrierErr(err)
return authorityErr(err)
}
// authorityErr projects Reserve refusals before a reservation is committed.
// A serving holder requires stop first; only the master's verified clean-stop
// barrier detail permits a timed retry before the reservation commits.
// Anything else (unavailable, deadline, a lost response) leaves
// 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 {
// A serving holder can renew its horizon indefinitely. A clean stop is
// distinguished by the master's typed detail, never by a dated message.
result := finalLeaseBarrierErr(err)
var refusal *chunkstore.CatalogError
if errors.As(result, &refusal) && refusal.Code == "not_admitted" && refusal.Retryable && !deleteLeaseBarrierDetail(err) {
refusal.Retryable = false
refusal.Message = "stop the volume first"
}
return result
}
func deleteLeaseBarrierDetail(err error) bool {
for _, detail := range status.Convert(err).Details() {
if r, ok := detail.(*control.WorkspaceLeaseRefusal); ok && r.Kind == control.WorkspaceLeaseRefusal_BARRIER {
return true
}
}
return false
}
// finalLeaseBarrierErr projects the dated deletion barrier. Reserve callers
// additionally require the clean-stop detail before allowing timed retry.
func finalLeaseBarrierErr(err error) error {
switch status.Code(err) {
case codes.OK:
return nil
case codes.FailedPrecondition:
// The authority emits this exact horizon clause for its lease barrier.
// Other refusals need their own cure, not an automatic timed retry.
if _, rest, ok := strings.Cut(status.Convert(err).Message(), "workspace delete: live until "); ok {
if stamp, reason, ok := strings.Cut(rest, ": "); ok && reason != "" {
if until, parseErr := time.Parse(time.RFC3339Nano, stamp); parseErr == nil {
return &chunkstore.CatalogError{Code: "not_admitted", Message: "retry the same --request-id after " + until.UTC().Format(time.RFC3339Nano), Retryable: true, Err: fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, err)}
}
}
}
return fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, err)
case codes.InvalidArgument:
case codes.FailedPrecondition, codes.InvalidArgument:
return fmt.Errorf("%w: %v", chunkstore.ErrNotAdmitted, err)
}
return err
@@ -152,7 +115,7 @@ func deleteVolumeWithProgress(ctx context.Context, cat *chunkstore.BCatalog, ref
skippedSet := map[layout.RootName]bool{}
var lastErr error
stalled := func(err error) error {
return &chunkstore.CatalogError{Code: codeUnavailableCLI, 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}
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.
@@ -70,7 +70,7 @@ func TestVolumeDeleteContinuesAcrossTransientObjectFailures(t *testing.T) {
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 != 75 || e.Code != "remote_unavailable" || !e.Retryable || !strings.Contains(e.Message, "deleted 0 of") || !strings.Contains(e.Message, "/") || !strings.Contains(e.Message, "object deadline") {
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 {
@@ -151,7 +151,7 @@ func TestVolumeDeleteRefreshesAnExpiredSweepAndWaitsFromLastRemoval(t *testing.T
return
}
e := chunkErrorOut(t, out)
if code != 75 || e.Code != "remote_unavailable" || !e.Retryable || !strings.Contains(e.Message, "deleted 1 of 2") || !strings.Contains(e.Message, "stalled after first removal") {
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 {
@@ -182,8 +182,8 @@ func TestVolumeDeleteReportsAStalledStoreWhileItWaits(t *testing.T) {
}
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 != 75 || e.Code != "remote_unavailable" {
t.Fatalf("stalled store: code=%d out=%s logs=%s; want the bounded remote_unavailable answer", code, out, logs)
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") {
@@ -267,7 +267,7 @@ func TestVolumeDeleteAnswerDoesNotWaitOnAStuckStderr(t *testing.T) {
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 != "remote_unavailable" {
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 {
@@ -281,7 +281,7 @@ func TestVolumeDeleteAnswerDoesNotWaitOnAStuckStderr(t *testing.T) {
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 != 75 || e.Code != "remote_unavailable" {
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
@@ -48,8 +48,7 @@ func TestOpsChunkVolumeDeleteRefusalSaysNothingWasPersisted(t *testing.T) {
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 != 1 || body.Code != "not_admitted" || body.Retryable ||
!strings.Contains(body.Message, "stop the volume first") ||
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)
}
@@ -59,9 +59,7 @@ func TestOpsChunkVolumeDeleteRefusedByDependentsLeavesTheVolumeReserved(t *testi
}
before := head()
code, out, stderr := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", h.Addr(), "--request-id", "del-vol-f"})...)
wantExit := chunkExitFailed
if body := chunkErrorOut(t, out); code != wantExit || body.Code != c.wantCode || body.Retryable {
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 {
@@ -1,160 +0,0 @@
package main
import (
"bytes"
"context"
"fmt"
"github.com/seaweedfs/seaweed-block/core/authority"
"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"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestVolumeDeleteAdmissionRetryAnswer(t *testing.T) {
lease := finalLeaseBarrierErr(status.Error(codes.FailedPrecondition, "workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed"))
cleanBarrier, err := status.New(codes.FailedPrecondition, "workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed").WithDetails(&control.WorkspaceLeaseRefusal{Kind: control.WorkspaceLeaseRefusal_BARRIER})
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
err error
exit int
code string
retry bool
}{
{"Reserve live-holder horizon", authorityErr(status.Error(codes.FailedPrecondition, "workspace delete: live until 2026-12-03T13:00:00Z: lease expiry plus clock-skew margin has not elapsed")), 1, "not_admitted", false},
{"Reserve clean-stop typed horizon", authorityErr(cleanBarrier.Err()), 75, "not_admitted", true},
{"HEAD boundary horizon", fmt.Errorf("%w: %w", layout.ErrHolderActive, lease), 75, "not_admitted", true},
{"invalid admission", authorityErr(status.Error(codes.InvalidArgument, "invalid token")), 1, "not_admitted", false},
{"dependents", layout.ErrHasDependents, 1, "snapshot_has_dependents", false},
{"remote unknown", authorityErr(status.Error(codes.Unavailable, "connection refused")), 75, "remote_unavailable", true},
} {
t.Run(tc.name, func(t *testing.T) {
var out, diag bytes.Buffer
exit := chunkResult("volume-delete", nil, tc.err, &out, &diag)
answer := chunkErrorOut(t, out.String())
if exit != tc.exit || answer.Code != tc.code || answer.Retryable != tc.retry {
t.Fatalf("exit=%d answer=%+v; want exit=%d code=%s retry=%v", exit, answer, tc.exit, tc.code, tc.retry)
}
})
}
}
// Exercise the actual reservation RPC and final CLI answer, including a clean
// move to a new epoch followed by a clean stop of that target.
func TestVolumeDeleteCleanMoveLeaseBarrierAnswer(t *testing.T) {
var now atomic.Int64
now.Store(time.Now().UnixNano())
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()
p := h.Publisher()
authority.WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, now.Load()) })(p)
seedForcedVolumeLease(t, h, true)
ctx := context.Background()
conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
// End creation: otherwise the never-created-volume exception reserves
// without ACK and bypasses the ordinary Reserve refusal under test.
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)
}
ack := func(epoch uint64, holder string) authority.WorkspaceHead {
t.Helper()
head := authority.WorkspaceHead{Gen: epoch + 8, Epoch: epoch, Holder: holder, Detached: true}
if err := p.BeginWorkspaceRevocation(ctx, "vol-f", "r1", epoch); err != nil {
t.Fatal(err)
}
if err := p.AckWorkspaceRevocation(ctx, "vol-f", authority.WorkspaceRevokeAck{ReplicaID: "r1", Epoch: epoch, HeadGen: head.Gen, Holder: holder}, head); err != nil {
t.Fatal(err)
}
return head
}
head := ack(1, "node-a/r1")
moved, err := p.MoveWorkspace(ctx, authority.WorkspaceMoveRequest{RequestID: "clean", VolumeID: "vol-f", ExpectedReplicaID: "r1", ExpectedHost: "node-a", ExpectedEpoch: 1, TargetReplicaID: "r1", TargetHost: "node-b", TargetDataAddr: "127.0.0.1:29200", TargetCtrlAddr: "127.0.0.1:29100", Kind: "clean"}, head)
if err != nil || !moved.Issued {
t.Fatalf("clean move: %+v %v", moved, err)
}
ack(moved.NewEpoch, "node-b/r1")
store := newMemChunkStore()
useMemChunkStore(t, store)
v := cliVolume(t, store, "vol-f", "daily")
args := cliArgs("volume-delete", volArgs("volume", v), []string{"--master", h.Addr(), "--request-id", "delete-after-clean"})
code, out, diag := runChunk(args...)
answer := chunkErrorOut(t, out)
if code != 75 || answer.Code != "not_admitted" || !answer.Retryable || !strings.Contains(answer.Message, "retry the same --request-id after ") || strings.Contains(answer.Message, "forced move") || strings.Contains(answer.Message, "stop the volume first") {
t.Fatalf("exit=%d answer=%+v stderr=%s", code, answer, diag)
}
if h.Lifecycle().Deletions.Reserved("vol-f") {
t.Fatal("barrier answer changed the reservation guard")
}
// An early retry still gets the master's barrier, never admission on time alone.
if earlyCode, earlyOut, earlyDiag := runChunk(args...); earlyCode != 75 || !chunkErrorOut(t, earlyOut).Retryable {
t.Fatalf("early retry: exit=%d out=%s stderr=%s", earlyCode, earlyOut, earlyDiag)
}
// A new clean move clears the stopped fact. The old retry advice cannot
// make the newly serving epoch retryable or reserve it.
movedAgain, err := p.MoveWorkspace(ctx, authority.WorkspaceMoveRequest{RequestID: "clean-again", VolumeID: "vol-f", ExpectedReplicaID: "r1", ExpectedHost: "node-b", ExpectedEpoch: moved.NewEpoch, TargetReplicaID: "r1", TargetHost: "node-a", TargetDataAddr: "127.0.0.1:19200", TargetCtrlAddr: "127.0.0.1:19100", Kind: "clean"}, authority.WorkspaceHead{Gen: moved.NewEpoch + 8, Epoch: moved.NewEpoch, Holder: "node-b/r1", Detached: true})
if err != nil || !movedAgain.Issued {
t.Fatalf("second clean move: %+v %v", movedAgain, err)
}
movedCode, movedOut, movedDiag := runChunk(args...)
movedAnswer := chunkErrorOut(t, movedOut)
if movedCode != 1 || movedAnswer.Retryable || !strings.Contains(movedAnswer.Message, "stop the volume first") {
t.Fatalf("retry after a move: exit=%d answer=%+v stderr=%s", movedCode, movedAnswer, movedDiag)
}
if h.Lifecycle().Deletions.Reserved("vol-f") {
t.Fatal("retry reserved a newly serving epoch")
}
ack(movedAgain.NewEpoch, "node-a/r1")
// Waiting never bypasses the barrier; the same request succeeds afterwards.
now.Add(int64(2 * time.Minute))
if code, out, diag := runChunk(args...); code != 0 {
t.Fatalf("after horizon: exit=%d out=%s stderr=%s", code, out, diag)
}
}
func TestVolumeDeletePartialAuthorityLoadStaysNonRetryable(t *testing.T) {
authDir := t.TempDir()
if err := os.WriteFile(filepath.Join(authDir, "broken.v3auth.json"), []byte("not JSON"), 0600); err != nil {
t.Fatal(err)
}
h, stop := startDeleteMaster(t, master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: authDir, LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true,
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }})
defer stop()
if len(h.Publisher().LoadErrors()) == 0 {
t.Fatal("fixture did not skip the corrupt authority record")
}
store := newMemChunkStore()
useMemChunkStore(t, store)
v := cliVolume(t, store, "vol-f", "daily")
code, out, diag := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", h.Addr(), "--request-id", "partial-load"})...)
answer := chunkErrorOut(t, out)
if code != 1 || answer.Code != "not_admitted" || answer.Retryable || !strings.Contains(answer.Message, "skipped") {
t.Fatalf("partial load: exit=%d answer=%+v stderr=%s", code, answer, diag)
}
if h.Lifecycle().Deletions.Reserved("vol-f") {
t.Fatal("partial load committed a reservation")
}
}
+2 -2
View File
@@ -188,9 +188,9 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int
}
return finalizeExitOK
}
answer.Result, answer.Message = "finalized", "v1.0.x binaries now refuse this cluster's stores; running v1.1 holders adopt the level at their next lease renewal"
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; running v1.1 holders adopt the level at their next lease renewal\n", resp.GetFormatLevel())
fmt.Fprintf(stdout, "format level %d finalized: v1.0.x binaries now refuse this cluster's stores\n", resp.GetFormatLevel())
}
return finalizeExitOK
}
@@ -1,95 +0,0 @@
package main
import (
"bytes"
"context"
"strings"
"testing"
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
// Control: a v1.1.0 master's QueryWorkspace answer after a clean revoke+ACK.
// The ACK identity carries no server id (the old master never set it) and
// there is no current_holder. Same binding, lease and ACK epoch as a release.
func oldMasterReleased() *control.WorkspaceStatus {
return &control.WorkspaceStatus{
Lease: &control.WorkspaceLeaseFact{ReplicaId: "r1", Epoch: 3, Revoking: true, ValidForNs: 0},
RevocationAck: &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: "v1", ReplicaId: "r1", Epoch: 3}, HeadGen: 9},
Bindings: []*control.WorkspaceBinding{{VolumeId: "v1", ServerId: "s1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9202"}},
}
}
func TestControl997OldMasterStopUsesLegacyWithoutRevoke(t *testing.T) {
h := newFakeHost(t)
env := h.env(t)
old := releaseQuery
releaseQuery = func(context.Context, string, string) (*control.WorkspaceStatus, error) {
return oldMasterReleased(), nil
}
t.Cleanup(func() { releaseQuery = old })
var out bytes.Buffer
result := releaseLease(context.Background(), env, map[string]string{"SWB_MASTER_ADDR": "master", "SWB_VOLUME_ID": "v1", "SWB_REPLICA_ID": "r1", "SWB_SERVER_ID": "s1"}, true, &out)
if !result.Legacy || result.Released || len(h.lease.revoked()) != 0 {
t.Fatalf("old-master stop=%+v", result)
}
// A server-less old ACK still cannot assert the newer exact-identity fact.
if r, _ := leaseVerdict(oldMasterReleased(), "v1", "r1", "s1", 3); r.Released {
t.Fatal("weakened ACK identity check")
}
}
func TestControl997OldMasterStartRefusesTheReleasedVolume(t *testing.T) {
old := releaseQuery
releaseQuery = func(context.Context, string, string) (*control.WorkspaceStatus, error) {
return oldMasterReleased(), nil
}
t.Cleanup(func() { releaseQuery = old })
var out, errs bytes.Buffer
v := volumeSpec{VolumeID: "v1", ReplicaID: "r1", ServerID: "s1", Master: "127.0.0.1:1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9202"}
code := prepareVolumeStart(context.Background(), v, &out, &errs)
t.Logf("start against an old master: code=%d %s", code, errs.String())
if code != 0 {
t.Errorf("volume start of a cleanly stopped volume refuses against a v1.1.0 master")
}
}
func TestOwnerUnreadableDoesNotSelectLegacyStartOrStop(t *testing.T) {
h := newFakeHost(t)
env := h.env(t)
stubResolve(t, "00112233445566778899aabbccddeeff", nil)
old := releaseQuery
reply := oldMasterReleased()
reply.OwnerUnreadable = true
releaseQuery = func(context.Context, string, string) (*control.WorkspaceStatus, error) { return reply, nil }
t.Cleanup(func() { releaseQuery = old })
code, _, errs := runStart(env, h.spec(true), startOpts{Wait: time.Second})
if code != 2 || h.called("enable") != 0 || !strings.Contains(errs, "volume_start_owner_unknown") {
t.Fatalf("unreadable start=%d %s", code, errs)
}
var out bytes.Buffer
result := releaseLease(context.Background(), env, map[string]string{"SWB_MASTER_ADDR": "master", "SWB_VOLUME_ID": "v1", "SWB_REPLICA_ID": "r1", "SWB_SERVER_ID": "s1"}, true, &out)
if result.Legacy || result.Released || !strings.Contains(result.Message, "owner unknown") || len(h.lease.revoked()) != 0 {
t.Fatalf("unreadable stop=%+v", result)
}
}
func TestOwnerUnreadableShowKeepsLeaseAndMoveFacts(t *testing.T) {
newFakeHost(t)
reply := oldMasterReleased()
reply.OwnerUnreadable = true
reply.Moves = []*control.WorkspaceGrant{{RequestId: "historical", VolumeId: "v1", OldEpoch: 2, NewEpoch: 3, OldReplicaId: "r1", NewReplicaId: "r1", Issued: true}}
f := &fakeWorkspace{status: reply}
addr, _ := startFakeWorkspace(t, f)
var out, errs bytes.Buffer
code := runWorkspaceShow([]string{"--master", addr, "--volume", "v1"}, &out, &errs)
for _, want := range []string{"owner observation: unreadable", "replica: r1", "epoch: 3", "recorded ACK: r1@3", "move: request=historical", "binding: host=s1"} {
if !strings.Contains(out.String(), want) {
t.Fatalf("missing %q: code=%d %s %s", want, code, out.String(), errs.String())
}
}
if code != 0 || f.n("MoveWorkspace") != 0 {
t.Fatalf("show=%d %s", code, errs.String())
}
}
@@ -1,212 +0,0 @@
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
)
const cutObservationSlack = 5 * time.Second
const chunkExitUnknown = 3
const chunkExitCutBusy = 4
// chunkObserveCut starts once, then reads status by the holder's in-memory ID.
// Only this cut's completed-step sequence renews observation.
// A chosen deadline remains absolute across every request.
func chunkObserveCut(addr string, window time.Duration, deadline time.Time, body map[string]any, stdout, stderr io.Writer) int {
return chunkObserveHandle("cut", "/chunk/cut", addr, window, deadline, body, stdout, stderr)
}
// chunkObserveHandle admits an observed operation at route (a cut, or a
// plain detach, CutTime r7) once, then reads its status by the handle's id
// on the shared /chunk/cut status route. Only this handle's sequence rises
// renew observation; a chosen deadline stays absolute.
func chunkObserveHandle(name, route, addr string, window time.Duration, deadline time.Time, body map[string]any, stdout, stderr io.Writer) int {
if window < time.Millisecond || window > time.Duration(1<<63-1)-cutObservationSlack {
return chunkFail(name, stdout, stderr, 2, codeBadRequestCLI, "--timeout must be at least 1ms and leave room for observation slack", false)
}
body["timeoutMs"] = window.Milliseconds()
if !deadline.IsZero() {
body["deadlineNs"] = deadline.UnixNano()
}
payload, err := json.Marshal(body)
if err != nil {
return chunkFail(name, stdout, stderr, 2, codeBadRequestCLI, err.Error(), false)
}
if !strings.Contains(addr, "://") {
addr = "http://" + addr
}
id := ""
last := time.Now()
seen := uint64(0)
bound := window + cutObservationSlack
// A 307/308 redirect can replay a POST inside Client.Do. An admission
// whose answer is ambiguous must remain unknown, never start again.
client := *chunkHTTPClient
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
unknown := func(why string) int {
if id != "" {
why += "; id " + id
}
return chunkFail(name, stdout, stderr, chunkExitUnknown, "outcome_unknown", why, true)
}
for {
until := last.Add(bound)
if !deadline.IsZero() && deadline.Before(until) {
until = deadline
}
if !time.Now().Before(until) {
return unknown(name + " observation window or explicit deadline expired")
}
ctx, cancel := context.WithDeadline(context.Background(), until)
method, endpoint := http.MethodPost, strings.TrimRight(addr, "/")+route
var requestBody io.Reader = bytes.NewReader(payload)
if id != "" {
method = http.MethodGet
endpoint = strings.TrimRight(addr, "/") + "/chunk/cut?" + url.Values{"volumeID": {fmt.Sprint(body["volumeID"])}, "cutID": {id}}.Encode()
requestBody = nil
}
req, err := http.NewRequestWithContext(ctx, method, endpoint, requestBody)
if err != nil {
cancel()
return chunkFail(name, stdout, stderr, 2, codeBadRequestCLI, err.Error(), false)
}
if method == http.MethodPost {
req.Header.Set("Content-Type", "application/json")
}
resp, err := client.Do(req)
var raw []byte
if err != nil && id == "" {
cancel()
// A failed dial sent no admission request. Other transport
// failures may have lost an applied request's answer.
var network *net.OpError
if errors.As(err, &network) && network.Op == "dial" && chunkTransportFailure(err) {
return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "blockvolume not reachable: "+err.Error(), true)
}
return unknown(name + " admission answer was not received (" + err.Error() + "); no second one was started")
}
if err == nil {
raw, err = io.ReadAll(io.LimitReader(resp.Body, chunkResponseLimit+1))
_ = resp.Body.Close()
if len(raw) > chunkResponseLimit {
err = fmt.Errorf("cut answer exceeds response limit")
}
}
cancel()
// Late sequence rises cannot revive silence already exhausted.
if !time.Now().Before(until) {
return unknown(name + " observation window or explicit deadline expired")
}
if err == nil {
var protocol struct {
Version json.RawMessage `json:"apiVersion"`
}
protocolErr := json.Unmarshal(raw, &protocol)
versionText := strings.TrimSpace(string(protocol.Version))
if versionText == "" {
versionText = "missing"
}
var version int
supported := protocolErr == nil && versionText != "null" && json.Unmarshal(protocol.Version, &version) == nil && version >= max(0, chunkstore.CutAPIVersion-1) && version <= chunkstore.CutAPIVersion
// Only an initial, unversioned synchronous 200 can be a v1.0 answer.
// A polling answer must always identify its response protocol.
legacy := protocolErr == nil && len(protocol.Version) == 0 && id == "" && resp.StatusCode == http.StatusOK
unsupported := func() int {
// An unsupported protocol cannot prove non-admission, even on
// an initial error: the worker may have finished before its reply.
return chunkFail("cut", stdout, stderr, chunkExitUnknown, "unsupported_api_version", fmt.Sprintf("server cut API version %s is unsupported by CLI version %d (supports %d and %d); cut outcome not established", versionText, chunkstore.CutAPIVersion, chunkstore.CutAPIVersion, max(0, chunkstore.CutAPIVersion-1)), false)
}
if !supported && !legacy {
return unsupported()
}
if resp.StatusCode == http.StatusOK {
var result struct {
VolumeID string `json:"volumeID"`
CutID string `json:"cutID"`
CutLSN *uint64 `json:"cutLSN"`
HeadGen *uint64 `json:"headGen"`
}
if json.Unmarshal(raw, &result) == nil && (id == "" || result.CutID == id) && result.VolumeID == body["volumeID"] && (result.CutLSN != nil || name == "detach") && result.HeadGen != nil && (!legacy || result.CutID == "") {
if err := writeAll(stdout, raw); err != nil {
fmt.Fprintf(stderr, "sw-block ops chunk %s: write the result: %v\n", name, err)
return chunkExitFailed
}
return 0
}
}
if legacy {
return unsupported()
}
var answer struct {
Code string `json:"code"`
Message string `json:"message"`
ID string `json:"cutID"`
Sequence uint64 `json:"sequence"`
Retryable bool `json:"retryable"`
}
if json.Unmarshal(raw, &answer) == nil && answer.Code != "" {
if resp.StatusCode == http.StatusAccepted && answer.Code == "in_progress" {
if id == "" && answer.ID != "" {
id = answer.ID
fmt.Fprintf(stderr, "sw-block ops chunk "+name+": id %s\n", id)
}
if answer.ID == id && answer.Sequence > seen {
seen = answer.Sequence
last = time.Now()
}
} else if id == "" && answer.Code == "cut_busy" {
fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, answer.Code, answer.Message)
if err := writeAll(stdout, raw); err != nil {
fmt.Fprintf(stderr, "sw-block ops chunk %s: write the result: %v\n", name, err)
return chunkExitFailed
}
return chunkExitCutBusy
} else if id == "" && name == "detach" && resp.StatusCode != http.StatusAccepted && answer.ID == "" {
// A plain detach refused at admission started nothing: report the
// typed refusal as it is (the detach keeps its existing failure answer).
if err := writeAll(stdout, raw); err != nil {
return chunkExitFailed
}
return chunkExitFailed
} else if answer.Code == "unknown_cut_id" && answer.ID == id && id != "" {
return unknown("holder no longer knows this id")
} else if answer.Code == "outcome_unknown" && answer.ID == id && id != "" {
return unknown(name + " publication settlement exhausted its progress window")
} else if (id == "" || answer.ID == id) && (answer.Code == "cut_stalled" || (!answer.Retryable && answer.Code != "outcome_unknown")) {
fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s\n", name, answer.Code, answer.Message)
if err := writeAll(stdout, raw); err != nil {
fmt.Fprintf(stderr, "sw-block ops chunk %s: write the result: %v\n", name, err)
return chunkExitFailed
}
return chunkExitFailed
}
}
}
if id == "" {
if err != nil {
return unknown(name + " admission answer could not be read: " + err.Error())
}
return unknown(name + " admission answer did not identify its outcome")
}
// Prompt short polling keeps the observation gap within the modeled slack.
next := last.Add(bound)
if !deadline.IsZero() && deadline.Before(next) {
next = deadline
}
pause := min(100*time.Millisecond, max(time.Duration(0), time.Until(next)))
if pause > 0 {
time.Sleep(pause)
}
}
}
@@ -1,525 +0,0 @@
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"testing"
"testing/synctest"
"time"
)
type cutPollTransport func(*http.Request) (*http.Response, error)
func (f cutPollTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func cutPollReply(code int, body string) *http.Response {
return &http.Response{StatusCode: code, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}
}
func installCutPollTransport(t *testing.T, f cutPollTransport) {
t.Helper()
old := chunkHTTPClient
chunkHTTPClient = &http.Client{Transport: f}
t.Cleanup(func() { chunkHTTPClient = old })
}
func TestCutCLIStartsOnceThenOnlyPollsTheReturnedID(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
posts, polls := 0, 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodPost {
posts++
var admission map[string]any
if err := json.NewDecoder(r.Body).Decode(&admission); err != nil || admission["observe"] != nil {
t.Errorf("unexpected observe opt-in: %v err=%v", admission, err)
}
if posts > 1 {
return cutPollReply(503, `{"apiVersion":1,"code":"cut_busy","retryable":true}`), nil
}
return cutPollReply(202, `{"apiVersion":1,"code":"in_progress","cutID":"server-cut","sequence":1}`), nil
}
if r.Method != http.MethodGet || r.URL.Path != "/chunk/cut" || r.URL.Query().Get("cutID") != "server-cut" || r.URL.Query().Get("volumeID") != "v1" {
t.Errorf("not a read-only poll of the admitted cut: %s %s", r.Method, r.URL)
}
polls++
return cutPollReply(200, `{"apiVersion":1,"volumeID":"v1","cutID":"server-cut","cutLSN":16,"headGen":4}`), nil
})
code, out, errOut := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut", "--deadline", time.Now().Add(2*time.Minute).Format(time.RFC3339Nano))
if code != 0 || posts != 1 || polls != 1 || !strings.Contains(out, `"cutLSN":16`) || !strings.Contains(errOut, "server-cut") {
t.Fatalf("code=%d posts=%d polls=%d out=%s stderr=%s", code, posts, polls, out, errOut)
}
})
}
func TestCutCLIRestartLosesTheHandleWithoutClaimingFailure(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
posts, polls := 0, 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodPost {
posts++
return cutPollReply(202, `{"apiVersion":1,"code":"in_progress","cutID":"before-restart","sequence":1}`), nil
}
polls++
return cutPollReply(404, `{"apiVersion":1,"code":"unknown_cut_id","cutID":"before-restart","retryable":false}`), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
if code != chunkExitUnknown || posts != 1 || polls != 1 || !strings.Contains(out, `"code":"outcome_unknown"`) || strings.Contains(out, "cut_stalled") {
t.Fatalf("code=%d posts=%d polls=%d out=%s", code, posts, polls, out)
}
})
}
func TestCutCLIBusyIsDistinctAndDoesNotStartAnotherCut(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
calls := 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
return cutPollReply(503, `{"apiVersion":1,"code":"cut_busy","cutID":"other-cut","retryable":true}`), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
if code != chunkExitCutBusy || calls != 1 || !strings.Contains(out, `"code":"cut_busy"`) {
t.Fatalf("code=%d calls=%d out=%s", code, calls, out)
}
})
}
func TestCutCLISettlementUnknownEndsWithoutRepostingOrWaitingAnotherWindow(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
start := time.Now()
calls := 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
if calls == 1 {
return cutPollReply(202, `{"apiVersion":1,"code":"in_progress","cutID":"settling","sequence":1}`), nil
}
if r.Method != http.MethodGet || r.URL.Query().Get("cutID") != "settling" {
t.Errorf("settlement was restarted: %s %s", r.Method, r.URL)
}
return cutPollReply(503, `{"apiVersion":1,"code":"outcome_unknown","cutID":"settling","retryable":true}`), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
if code != chunkExitUnknown || calls != 2 || time.Since(start) >= time.Second || !strings.Contains(out, `"code":"outcome_unknown"`) {
t.Fatalf("code=%d calls=%d elapsed=%s out=%s", code, calls, time.Since(start), out)
}
})
}
func TestCutCLIAdmissionRedirectCannotReplayThePost(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
calls := 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
if calls > 1 {
return cutPollReply(503, `{"apiVersion":1,"code":"cut_busy","cutID":"own-cut","retryable":true}`), nil
}
resp := cutPollReply(http.StatusTemporaryRedirect, "")
resp.Header.Set("Location", "/redirected")
return resp, nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
if calls != 1 || code != chunkExitUnknown || !strings.Contains(out, `"code":"unsupported_api_version"`) {
t.Fatalf("admission replayed across redirect: code=%d calls=%d out=%s", code, calls, out)
}
})
}
func TestCutCLIProgressingFor46MinutesPollsOneCutID(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
start := time.Now()
id := "holder-cut"
calls := 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
if calls == 1 && r.Method != http.MethodPost || calls > 1 && (r.Method != http.MethodGet || r.URL.Query().Get("cutID") != id) {
t.Errorf("cut was restarted or polled with another identity: %s %s", r.Method, r.URL)
}
select {
case <-time.After(50 * time.Second):
case <-r.Context().Done():
return nil, r.Context().Err()
}
if calls == 56 {
return cutPollReply(200, `{"apiVersion":1,"volumeID":"v1","cutID":"holder-cut","cutLSN":16,"headGen":4}`), nil
}
return cutPollReply(202, fmt.Sprintf(`{"apiVersion":1,"code":"in_progress","cutID":%q,"sequence":%d}`, id, calls)), nil
})
code, out, errOut := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
if code != 0 || !strings.Contains(out, `"cutLSN":16`) || calls != 56 || time.Since(start) < 46*time.Minute || !strings.Contains(errOut, id) {
t.Fatalf("progressing default cut: code=%d calls=%d elapsed=%s out=%s stderr=%s", code, calls, time.Since(start), out, errOut)
}
})
}
func TestCutCLIUnchangedSequenceCannotRenewItsWindow(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
start := time.Now()
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
select {
case <-time.After(10 * time.Second):
case <-r.Context().Done():
return nil, r.Context().Err()
}
return cutPollReply(202, `{"apiVersion":1,"code":"in_progress","cutID":"same","sequence":1}`), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut", "--deadline", start.Add(3*time.Minute).Format(time.RFC3339Nano))
if code != 3 || !strings.Contains(out, `"code":"outcome_unknown"`) || time.Since(start) < 75*time.Second || time.Since(start) > 76*time.Second {
t.Fatalf("fixed sequence renewed silence: code=%d elapsed=%s out=%s", code, time.Since(start), out)
}
})
}
func TestCutCLIAbsoluteDeadlineEndsAProgressingCut(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
start := time.Now()
calls := 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
select {
case <-time.After(20 * time.Second):
case <-r.Context().Done():
return nil, r.Context().Err()
}
calls++
return cutPollReply(202, fmt.Sprintf(`{"apiVersion":1,"code":"in_progress","cutID":"same","sequence":%d}`, calls)), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut", "--deadline", start.Add(3*time.Minute).Format(time.RFC3339Nano))
if code != 3 || !strings.Contains(out, `"code":"outcome_unknown"`) || time.Since(start) != 3*time.Minute {
t.Fatalf("absolute deadline lost: code=%d elapsed=%s out=%s", code, time.Since(start), out)
}
})
}
func TestCutCLIUnansweredRequestEndsUnknownWithinItsOwnWindow(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
start := time.Now()
calls := 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
<-r.Context().Done()
return nil, r.Context().Err()
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut", "--deadline", start.Add(3*time.Minute).Format(time.RFC3339Nano))
if code != 3 || calls != 1 || !strings.Contains(out, `"code":"outcome_unknown"`) || time.Since(start) != 65*time.Second {
t.Fatalf("silent request: code=%d elapsed=%s out=%s", code, time.Since(start), out)
}
})
}
func TestCutCLIForeignSequenceCannotRenewItsWindow(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
start := time.Now()
n := 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodPost {
return cutPollReply(202, `{"apiVersion":1,"code":"in_progress","cutID":"same","sequence":0}`), nil
}
select {
case <-time.After(10 * time.Second):
case <-r.Context().Done():
return nil, r.Context().Err()
}
n++
return cutPollReply(202, fmt.Sprintf(`{"apiVersion":1,"code":"in_progress","cutID":"foreign","sequence":%d}`, n)), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut", "--deadline", start.Add(3*time.Minute).Format(time.RFC3339Nano))
if code != 3 || !strings.Contains(out, `"code":"outcome_unknown"`) || time.Since(start) != 65*time.Second {
t.Fatalf("foreign cut renewed silence: code=%d elapsed=%s out=%s", code, time.Since(start), out)
}
})
}
func TestCutCLIStalledAnswerIsAFailure(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
return cutPollReply(503, `{"apiVersion":1,"code":"cut_stalled","message":"upload stopped","retryable":true}`), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
if code != 1 || !strings.Contains(out, `"code":"cut_stalled"`) {
t.Fatalf("terminal stall code=%d out=%s", code, out)
}
})
}
func TestCutCLIForeignTerminalCannotSettleThisObservation(t *testing.T) {
for _, tc := range []struct {
name string
status int
body string
}{
{"success", 200, `{"apiVersion":1,"volumeID":"v1","cutID":"foreign","cutLSN":16,"headGen":4}`},
{"stalled", 503, `{"apiVersion":1,"code":"cut_stalled","cutID":"foreign","retryable":true}`},
} {
t.Run(tc.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
start := time.Now()
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodPost {
return cutPollReply(202, `{"apiVersion":1,"code":"in_progress","cutID":"same","sequence":0}`), nil
}
select {
case <-time.After(10 * time.Second):
case <-r.Context().Done():
return nil, r.Context().Err()
}
return cutPollReply(tc.status, tc.body), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut", "--deadline", start.Add(3*time.Minute).Format(time.RFC3339Nano))
if code != 3 || !strings.Contains(out, `"code":"outcome_unknown"`) || time.Since(start) != 65*time.Second {
t.Fatalf("foreign terminal settled observation: code=%d elapsed=%s out=%s", code, time.Since(start), out)
}
})
})
}
}
func TestCutCLIRejectsUnrepresentableDeadlinesBeforeAdmission(t *testing.T) {
for _, deadline := range []string{"0001-01-01T00:00:00Z", "1600-01-01T00:00:00Z", "2500-01-01T00:00:00Z"} {
t.Run(deadline, func(t *testing.T) {
calls := 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
return cutPollReply(200, `{"apiVersion":1,"volumeID":"v1","cutLSN":1,"headGen":1}`), nil
})
code, _, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut", "--deadline", deadline)
if code != 2 || calls != 0 {
t.Fatalf("deadline %s: code=%d calls=%d", deadline, code, calls)
}
})
}
}
func TestCutCLISequenceUsesStrictHighWater(t *testing.T) {
for _, final := range []uint64{5, 6} {
t.Run(fmt.Sprint(final), func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
start := time.Now()
calls := 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
if calls == 1 {
return cutPollReply(202, `{"apiVersion":1,"code":"in_progress","cutID":"same","sequence":5}`), nil
}
select {
case <-time.After(25 * time.Second):
case <-r.Context().Done():
return nil, r.Context().Err()
}
seq := uint64(4)
if calls >= 3 {
seq = final
}
if calls == 4 {
return cutPollReply(200, `{"apiVersion":1,"volumeID":"v1","cutID":"same","cutLSN":1,"headGen":1}`), nil
}
return cutPollReply(202, fmt.Sprintf(`{"apiVersion":1,"code":"in_progress","cutID":"same","sequence":%d}`, seq)), nil
})
code, _, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
if final == 5 && (code != chunkExitUnknown || time.Since(start) != 65*time.Second) {
t.Fatalf("5->4->5 renewed: code=%d elapsed=%s", code, time.Since(start))
}
if final == 6 && code != 0 {
t.Fatalf("5->4->6 did not renew: code=%d elapsed=%s", code, time.Since(start))
}
})
})
}
}
type stalledCutPollBody struct {
ctx context.Context
closed *bool
}
func (b stalledCutPollBody) Read([]byte) (int, error) { <-b.ctx.Done(); return 0, b.ctx.Err() }
func (b stalledCutPollBody) Close() error { *b.closed = true; return nil }
func TestCutCLIAdmittedPollCancellation(t *testing.T) {
for _, bodyStall := range []bool{false, true} {
t.Run(fmt.Sprint(bodyStall), func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
start := time.Now()
calls := 0
closed := false
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
if calls == 1 {
return cutPollReply(202, `{"apiVersion":1,"code":"in_progress","cutID":"same","sequence":1}`), nil
}
if r.Method != http.MethodGet {
t.Errorf("admitted request is %s", r.Method)
}
if bodyStall {
resp := cutPollReply(202, "")
resp.Body = stalledCutPollBody{r.Context(), &closed}
return resp, nil
}
<-r.Context().Done()
return nil, r.Context().Err()
})
code, _, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
if code != chunkExitUnknown || calls != 2 || time.Since(start) != 65*time.Second || bodyStall && !closed {
t.Fatalf("code=%d calls=%d elapsed=%s closed=%v", code, calls, time.Since(start), closed)
}
})
})
}
}
func TestCutCLILegacyTerminalAnswerNeedsNoPolling(t *testing.T) {
calls := 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body["observe"] != nil {
t.Errorf("unexpected opt-in: %v err=%v", body, err)
}
return cutPollReply(200, `{"volumeID":"v1","cutLSN":7,"headGen":3}`), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
if code != 0 || calls != 1 || !strings.Contains(out, `"cutLSN":7`) {
t.Fatalf("code=%d calls=%d out=%s", code, calls, out)
}
}
func TestCutCLINewerClientAcceptsOwnAndOneOlderHolder(t *testing.T) {
for _, version := range []int{0, 1} {
t.Run(fmt.Sprint(version), func(t *testing.T) {
calls := 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
var request map[string]any
if err := json.NewDecoder(r.Body).Decode(&request); err != nil || request["apiVersion"] != nil {
t.Errorf("client sent a negotiation version: %v err=%v", request, err)
}
return cutPollReply(200, fmt.Sprintf(`{"apiVersion":%d,"volumeID":"v1","cutLSN":7,"headGen":3}`, version)), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
if code != 0 || calls != 1 {
t.Fatalf("version=%d code=%d calls=%d out=%s", version, code, calls, out)
}
})
}
}
func TestCutCLIOlderClientRefusesNewerHolder(t *testing.T) {
for _, version := range []int{2, 99} {
t.Run(fmt.Sprint(version), func(t *testing.T) {
calls := 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
if r.Method != http.MethodPost {
t.Errorf("unsupported holder must not be polled: %s", r.Method)
}
return cutPollReply(202, fmt.Sprintf(`{"apiVersion":%d,"code":"in_progress","cutID":"new-version","sequence":1}`, version)), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
answer := chunkErrorOut(t, out)
if code != chunkExitUnknown || calls != 1 || answer.Code != "unsupported_api_version" || !strings.Contains(answer.Message, fmt.Sprintf("server cut API version %d", version)) || !strings.Contains(answer.Message, "CLI version 1") {
t.Fatalf("version=%d code=%d calls=%d out=%s", version, code, calls, out)
}
})
}
}
func TestCutCLIUnsupportedVersionNeverStartsAnotherCut(t *testing.T) {
for _, tc := range []struct {
name, version string
status int
admitted bool
}{
{"future terminal", `99`, 200, false},
{"missing progress", ``, 202, false},
{"null", `null`, 202, false},
{"string", `"1"`, 202, false},
{"negative", `-1`, 202, false},
{"missing poll", ``, 202, true},
{"unversioned terminal poll", ``, 200, true},
{"unsupported refusal before admission", `99`, 409, false},
{"unsupported refusal after admission", `99`, 409, true},
} {
t.Run(tc.name, func(t *testing.T) {
calls, posts := 0, 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
if r.Method == http.MethodPost {
posts++
}
if tc.admitted && calls == 1 {
return cutPollReply(202, `{"apiVersion":1,"code":"in_progress","cutID":"one-cut","sequence":1}`), nil
}
fields := `"volumeID":"v1","cutLSN":7,"headGen":3,"code":"in_progress","cutID":"one-cut","sequence":2`
if tc.version != "" {
fields = `"apiVersion":` + tc.version + `,` + fields
}
return cutPollReply(tc.status, `{`+fields+`}`), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
answer := chunkErrorOut(t, out)
wantCalls := 1
if tc.admitted {
wantCalls = 2
}
wantExit := chunkExitUnknown
if code != wantExit || posts != 1 || calls != wantCalls || answer.Code != "unsupported_api_version" || !strings.Contains(answer.Message, "CLI version 1") || !strings.Contains(answer.Message, "cut outcome not established") {
t.Fatalf("code=%d posts=%d calls=%d out=%s", code, posts, calls, out)
}
})
}
}
func TestCutCLIInvalidUnversionedInitialTerminalAnswerIsUnknown(t *testing.T) {
for _, tc := range []struct{ name, raw string }{
{"missing frontier", `{"volumeID":"v1","headGen":3}`},
{"missing generation", `{"volumeID":"v1","cutLSN":7}`},
{"wrong volume", `{"volumeID":"other","cutLSN":7,"headGen":3}`},
{"unexpected handle", `{"volumeID":"v1","cutID":"one-cut","cutLSN":7,"headGen":3}`},
} {
t.Run(tc.name, func(t *testing.T) {
posts, calls := 0, 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
if r.Method == http.MethodPost {
posts++
}
return cutPollReply(200, tc.raw), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
answer := chunkErrorOut(t, out)
if code != chunkExitUnknown || calls != 1 || posts != 1 || answer.Code != "unsupported_api_version" || !strings.Contains(answer.Message, "cut outcome not established") {
t.Fatalf("code=%d calls=%d posts=%d out=%s", code, calls, posts, out)
}
})
}
}
func TestCutCLIUnsupportedInitialErrorNeverProvesNonAdmission(t *testing.T) {
for _, tc := range []struct {
name, raw string
status int
}{
{"missing version terminal", `{"code":"outcome_unknown","cutID":"finished-before-reply","retryable":true}`, 503},
{"future version terminal", `{"apiVersion":99,"code":"outcome_unknown","cutID":"finished-before-reply","retryable":true}`, 503},
{"forwarded gateway error", `{"code":"bad_gateway"}`, 502},
{"untrusted admission refusal", `{"apiVersion":99,"code":"not_primary"}`, 409},
} {
t.Run(tc.name, func(t *testing.T) {
posts, calls := 0, 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
if r.Method == http.MethodPost {
posts++
}
return cutPollReply(tc.status, tc.raw), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
answer := chunkErrorOut(t, out)
if code != chunkExitUnknown || calls != 1 || posts != 1 || answer.Code != "unsupported_api_version" || !strings.Contains(answer.Message, "cut outcome not established") {
t.Fatalf("code=%d calls=%d posts=%d out=%s", code, calls, posts, out)
}
})
}
}
func TestCutCLISupportedAdmissionRefusalStillFails(t *testing.T) {
calls := 0
installCutPollTransport(t, func(r *http.Request) (*http.Response, error) {
calls++
return cutPollReply(409, `{"apiVersion":1,"code":"not_primary","message":"not admitted","retryable":false}`), nil
})
code, out, _ := runChunk("cut", "--volume", "v1", "--status-addr", "http://cut")
answer := chunkErrorOut(t, out)
if code != chunkExitFailed || calls != 1 || answer.Code != "not_primary" {
t.Fatalf("code=%d calls=%d out=%s", code, calls, out)
}
}
@@ -9,7 +9,6 @@ import (
"go/ast"
"go/parser"
"go/token"
"net/http"
"os"
"os/exec"
"path/filepath"
@@ -61,8 +60,6 @@ func TestIntegrationInvocationGuardReachesLateFlagChecks(t *testing.T) {
args []string
want string
}{
{[]string{"ops", "chunk", "cut", "--volume", "v1"}, guardRefused},
{[]string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", "127.0.0.1:1"}, guardPast},
{[]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},
@@ -136,13 +133,6 @@ func TestIntegrationInvocationChild(t *testing.T) {
restoreCreateRPC = func(context.Context, string, *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
return nil, errGuardPast
}
// The cut observer deliberately hides a lost transport answer behind
// outcome_unknown. Mark dispatch itself as the argument proof, rather
// than depending on a particular wrapped network-error message.
chunkHTTPClient = &http.Client{Transport: cutPollTransport(func(*http.Request) (*http.Response, error) {
fmt.Println(errGuardPast)
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())
+18 -29
View File
@@ -10,7 +10,6 @@ import (
"net"
"net/http"
"os"
"path"
"path/filepath"
"strconv"
"strings"
@@ -1075,7 +1074,6 @@ func loadObservationCluster(command string, args []string, stderr io.Writer) (op
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")
masterTLS := evidenceMasterTLSFlags(fs)
if err := fs.Parse(args); err != nil {
return ops.ClusterEvidence{}, "", ops.VolumeStatusExitInvalid
}
@@ -1092,7 +1090,7 @@ func loadObservationCluster(command string, args []string, stderr io.Writer) (op
} else if masterAPIAddr != "" {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
cluster, err = readMasterClusterEvidenceWithTLS(ctx, masterAPIAddr, masterTLS)
cluster, err = readMasterClusterEvidence(ctx, masterAPIAddr)
} else {
if productRevision == "" {
productRevision = buildinfo.Version("sw-block")
@@ -1192,7 +1190,16 @@ func liveNodeEvidenceNamespace(namespace string) string {
}
func readMasterClusterEvidence(ctx context.Context, masterAddr string) (ops.ClusterEvidence, error) {
return readMasterClusterEvidenceWithTLS(ctx, masterAddr, nil)
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 {
@@ -1418,7 +1425,6 @@ func runOpsReport(args []string, stdout, stderr io.Writer) int {
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")
masterTLS := evidenceMasterTLSFlags(fs)
if err := fs.Parse(args); err != nil {
return ops.VolumeStatusExitInvalid
}
@@ -1441,7 +1447,7 @@ func runOpsReport(args []string, stdout, stderr io.Writer) int {
case masterAPIAddr != "":
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
cluster, err = readMasterClusterEvidenceWithTLS(ctx, masterAPIAddr, masterTLS)
cluster, err = readMasterClusterEvidence(ctx, masterAPIAddr)
default:
if productRevision == "" {
productRevision = buildinfo.Version("sw-block")
@@ -1525,7 +1531,6 @@ func runOpsDashboard(args []string, stdout, stderr io.Writer) int {
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")
masterTLS := evidenceMasterTLSFlags(fs)
if err := fs.Parse(args); err != nil {
return ops.VolumeStatusExitInvalid
}
@@ -1540,7 +1545,6 @@ func runOpsDashboard(args []string, stdout, stderr io.Writer) int {
Namespace: namespace,
MasterAddr: masterAddr,
MasterAPIAddr: masterAPIAddr,
MasterTLS: masterTLS,
EvidenceOutDir: evidenceOutDir,
ProductRevision: productRevision,
ClaimProfile: claimProfile,
@@ -1613,7 +1617,6 @@ type dashboardClusterOptions struct {
Namespace string
MasterAddr string
MasterAPIAddr string
MasterTLS *link.TLSFiles
EvidenceOutDir string
ProductRevision string
ClaimProfile string
@@ -1633,7 +1636,7 @@ func loadDashboardCluster(options dashboardClusterOptions) (ops.ClusterEvidence,
case options.MasterAPIAddr != "":
ctx, cancel := context.WithTimeout(context.Background(), options.Timeout)
defer cancel()
cluster, err = readMasterClusterEvidenceWithTLS(ctx, options.MasterAPIAddr, options.MasterTLS)
cluster, err = readMasterClusterEvidence(ctx, options.MasterAPIAddr)
live = true
default:
productRevision := options.ProductRevision
@@ -1693,10 +1696,7 @@ type helmValuesImage struct {
}
type helmValuesBlockmaster struct {
// StateHostPath is written even when empty (ephemeral), so the chart's
// hostpath default is never inherited silently.
StateHostPath *string `yaml:"stateHostPath,omitempty"`
NodeSelector map[string]string `yaml:"nodeSelector,omitempty"`
StateHostPath string `yaml:"stateHostPath,omitempty"`
}
type helmValuesRestart struct {
@@ -1802,8 +1802,8 @@ func runOpsGenerateHelmValues(args []string, stdout, stderr io.Writer) int {
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", "hostpath", "restart persistence mode: hostpath (default) or ephemeral (ephemeral restart persistence loses all data whenever a holder pod restarts)")
fs.StringVar(&stateHostPath, "state-hostpath", "/var/lib/sw-block/k8s", "hostPath base used when --restart-persistence=hostpath")
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")
@@ -1933,15 +1933,8 @@ func runOpsGenerateHelmValues(args []string, stdout, stderr io.Writer) int {
}
values.Restart = &helmValuesRestart{Mode: restartPersistence}
if restartPersistence == "hostpath" {
// blockmaster's stores live on one node: pin it to the first selected one.
// Its stores and the volumes' state get separate paths under the base,
// so a holder pod never mounts blockmaster's stores.
masterPath := path.Join(stateHostPath, "master")
values.Blockmaster = &helmValuesBlockmaster{StateHostPath: &masterPath, NodeSelector: map[string]string{"kubernetes.io/hostname": selected[0].Name}}
values.Restart.StateHostPath = path.Join(stateHostPath, "volumes")
} else {
ephemeral := ""
values.Blockmaster = &helmValuesBlockmaster{StateHostPath: &ephemeral}
values.Blockmaster = &helmValuesBlockmaster{StateHostPath: stateHostPath}
values.Restart.StateHostPath = stateHostPath
}
for i, node := range selected {
ip := node.InternalIP
@@ -2010,10 +2003,6 @@ func runOpsGenerateHelmValues(args []string, stdout, stderr io.Writer) int {
fmt.Fprintf(stdout, "restart_persistence_mode=%s\n", restartPersistence)
if restartPersistence == "hostpath" {
fmt.Fprintf(stdout, "state_hostpath=%s\n", stateHostPath)
fmt.Fprintf(stdout, "master_state_hostpath=%s\n", path.Join(stateHostPath, "master"))
fmt.Fprintf(stdout, "volume_state_hostpath=%s\n", path.Join(stateHostPath, "volumes"))
} else {
fmt.Fprintln(stdout, "warning=ephemeral restart persistence loses all data whenever a holder pod restarts")
}
return ops.VolumeStatusExitOK
}
+61 -65
View File
@@ -250,11 +250,11 @@ func TestOpsOperatorStatusDryRunFromBundle(t *testing.T) {
},
Replicas: []ops.ReplicaFact{{
ReplicaID: "r1",
KubernetesNode: "node-b",
KubernetesNode: "m02",
Role: "primary",
Observed: true,
}},
CSIStages: []ops.CSIStageFact{{NodeName: "node-b", Target: "192.168.1.184:3260"}},
CSIStages: []ops.CSIStageFact{{NodeName: "m02", Target: "192.168.1.184:3260"}},
Workload: &ops.WorkloadCheckFact{WriterVerified: true, ReaderVerified: true},
})}
raw, err := ops.MarshalObservationJSON(cluster)
@@ -296,11 +296,11 @@ func TestOpsOperatorStatusWritesCRDStatusWhenDryRunDisabled(t *testing.T) {
},
Replicas: []ops.ReplicaFact{{
ReplicaID: "r1",
KubernetesNode: "node-b",
KubernetesNode: "m02",
Role: "primary",
Observed: true,
}},
CSIStages: []ops.CSIStageFact{{NodeName: "node-b", Target: "192.168.1.184:3260"}},
CSIStages: []ops.CSIStageFact{{NodeName: "m02", Target: "192.168.1.184:3260"}},
Workload: &ops.WorkloadCheckFact{WriterVerified: true, ReaderVerified: true},
})}
raw, err := ops.MarshalObservationJSON(cluster)
@@ -1894,7 +1894,7 @@ func TestOpsClusterMasterAPIUsesSharedInClusterNodeEvidenceEnrichment(t *testing
}
out := stdout.String()
for _, want := range []string{
`"kubernetes_node": "node-b"`,
`"kubernetes_node": "m02"`,
`"ready": false`,
`"reason": "node_not_ready"`,
} {
@@ -1926,7 +1926,7 @@ func TestOpsReportMasterAPIUsesSharedInClusterNodeEvidenceEnrichment(t *testing.
}
out := string(raw)
for _, want := range []string{
`"kubernetes_node": "node-b"`,
`"kubernetes_node": "m02"`,
`"ready": false`,
`"reason": "node_not_ready"`,
} {
@@ -1956,7 +1956,7 @@ func TestLoadObservationVolumeUsesSharedInClusterNodeEvidenceEnrichment(t *testi
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 != "node-b" {
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) {
@@ -2051,7 +2051,7 @@ func TestOpsDashboardMasterAPIUsesSharedInClusterNodeEvidenceEnrichment(t *testi
}()
body := waitForHTTPContains(t, "http://"+addr+"/cluster-evidence.json", `"reason": "node_not_ready"`)
if !strings.Contains(body, `"kubernetes_node": "node-b"`) || !strings.Contains(body, `"ready": false`) {
if !strings.Contains(body, `"kubernetes_node": "m02"`) || !strings.Contains(body, `"ready": false`) {
t.Fatalf("dashboard cluster evidence missing enriched node:\n%s", body)
}
select {
@@ -2123,8 +2123,8 @@ type fakeNodeEvidenceEnricher struct{}
func (fakeNodeEvidenceEnricher) EnrichNodeEvidence(_ context.Context, _ string, cluster ops.ClusterEvidence) (ops.ClusterEvidence, error) {
cluster.Nodes = []ops.NodeEvidence{{
NodeName: "node-b",
KubernetesNode: "node-b",
NodeName: "m02",
KubernetesNode: "m02",
Ready: false,
Schedulable: true,
Conditions: []ops.ObservationCondition{{
@@ -2538,7 +2538,7 @@ func TestOpsGenerateHelmValuesSingleNodeFromKubernetes(t *testing.T) {
code := run([]string{
"ops", "generate-helm-values",
"--out", outPath,
"--target-node", "node-b",
"--target-node", "m02",
"--node-limit", "1",
"--image", "ghcr.io/seaweedfs/seaweed-block:sha-test",
"--csi-image", "ghcr.io/seaweedfs/seaweed-block-csi:sha-test",
@@ -2551,9 +2551,8 @@ func TestOpsGenerateHelmValuesSingleNodeFromKubernetes(t *testing.T) {
"network_mode=loopback",
"ready_kubernetes_nodes=1",
"discovered_kubernetes_nodes=3",
"target_node=node-b",
"restart_persistence_mode=hostpath",
"state_hostpath=/var/lib/sw-block/k8s",
"target_node=m02",
"restart_persistence_mode=ephemeral",
} {
if !strings.Contains(stdout.String(), want) {
t.Fatalf("stdout missing %q:\n%s", want, stdout.String())
@@ -2571,12 +2570,11 @@ func TestOpsGenerateHelmValuesSingleNodeFromKubernetes(t *testing.T) {
"externalStatus: false",
"rejectLoopbackPublishTargets: false",
"restartPersistence:",
"mode: hostpath",
"stateHostPath: /var/lib/sw-block/k8s",
"mode: ephemeral",
"expectedSlotsPerVolume: 1",
"enabled: false",
"name: node-b",
"kubernetesNode: node-b",
"name: m02",
"kubernetesNode: m02",
"internalIP: 127.0.0.1",
"dataPort: 19101",
"controlPort: 19102",
@@ -2617,8 +2615,7 @@ func TestOpsGenerateHelmValuesMultiNodeExternalISCSI(t *testing.T) {
"chap_enabled=true",
"protocol=iscsi",
"ack_profile=sync-quorum",
"restart_persistence_mode=hostpath",
"state_hostpath=/var/lib/sw-block/k8s",
"restart_persistence_mode=ephemeral",
} {
if !strings.Contains(stdout.String(), want) {
t.Fatalf("stdout missing %q:\n%s", want, stdout.String())
@@ -2637,19 +2634,18 @@ func TestOpsGenerateHelmValuesMultiNodeExternalISCSI(t *testing.T) {
"externalStatus: false",
"rejectLoopbackPublishTargets: true",
"restartPersistence:",
"mode: hostpath",
"stateHostPath: /var/lib/sw-block/k8s",
"mode: ephemeral",
"enabled: true",
"secret: fixed-chap-secret",
"name: node-a",
"name: m01",
"internalIP: 192.168.1.181",
"dataPort: 19101",
"controlPort: 19102",
"name: node-b",
"name: m02",
"internalIP: 192.168.1.184",
"dataPort: 19103",
"controlPort: 19104",
"name: node-c",
"name: tp01",
"internalIP: 192.168.1.188",
"dataPort: 19105",
"controlPort: 19106",
@@ -2709,11 +2705,11 @@ func TestOpsGenerateHelmValuesMultiNodeExternalNVMe(t *testing.T) {
"enabled: false",
"create: false",
"secret: \"\"",
"name: node-a",
"name: m01",
"internalIP: 192.168.1.181",
"name: node-b",
"name: m02",
"internalIP: 192.168.1.184",
"name: node-c",
"name: tp01",
"internalIP: 192.168.1.188",
} {
if !strings.Contains(string(values), want) {
@@ -2739,7 +2735,7 @@ func TestOpsGenerateHelmValuesMultiNodeNVMeFrontendIPMap(t *testing.T) {
"--out", outPath,
"--replication-factor", "3",
"--protocol", "nvme",
"--frontend-ip-map", "node-a=10.0.0.181,node-b=10.0.0.184,node-c=10.0.0.188",
"--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 {
@@ -2747,7 +2743,7 @@ func TestOpsGenerateHelmValuesMultiNodeNVMeFrontendIPMap(t *testing.T) {
}
for _, want := range []string{
"network_mode=external-nvme",
"frontend_ip_map=node-a=10.0.0.181,node-b=10.0.0.184,node-c=10.0.0.188",
"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) {
@@ -2759,16 +2755,16 @@ func TestOpsGenerateHelmValuesMultiNodeNVMeFrontendIPMap(t *testing.T) {
t.Fatal(err)
}
for _, want := range []string{
"name: node-a",
"name: m01",
"internalIP: 192.168.1.181",
"managementIP: 192.168.1.181",
"frontendIP: 10.0.0.181",
"frontendNetworkClass: 100gbe_tcp",
"name: node-b",
"name: m02",
"internalIP: 192.168.1.184",
"managementIP: 192.168.1.184",
"frontendIP: 10.0.0.184",
"name: node-c",
"name: tp01",
"internalIP: 192.168.1.188",
"managementIP: 192.168.1.188",
"frontendIP: 10.0.0.188",
@@ -2791,7 +2787,7 @@ func TestPhase165_OpsGenerateHelmValuesNVMERDMA(t *testing.T) {
code := run([]string{
"ops", "generate-helm-values", "--out", outPath, "--replication-factor", "1",
"--protocol", "nvme", "--nvme-transport", "rdma",
"--frontend-ip-map", "node-a=10.0.0.181,node-b=10.0.0.184,node-c=10.0.0.188",
"--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 {
@@ -2817,7 +2813,7 @@ 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", "node-a=10.0.0.181", "--frontend-network-class", "100gbe_tcp"},
{"--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")}
@@ -2841,20 +2837,20 @@ func TestOpsGenerateHelmValuesRejectsIncompleteFrontendIPMap(t *testing.T) {
"--out", filepath.Join(t.TempDir(), "values.yaml"),
"--replication-factor", "3",
"--protocol", "nvme",
"--frontend-ip-map", "node-a=10.0.0.181,node-b=10.0.0.184",
"--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 "node-c"`) {
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: "node-a",
NodeName: "m01",
InternalIp: "192.168.1.181",
FrontendIp: "10.0.0.1",
FrontendNetworkClass: "100gbe_tcp",
@@ -2887,7 +2883,7 @@ func TestOpsGenerateHelmValuesRestartPersistenceHostPath(t *testing.T) {
code := run([]string{
"ops", "generate-helm-values",
"--out", outPath,
"--target-node", "node-b",
"--target-node", "m02",
"--node-limit", "1",
"--restart-persistence", "hostpath",
"--state-hostpath", "/var/lib/sw-block",
@@ -2945,7 +2941,7 @@ func TestOpsGenerateHelmValuesRejectsRFAboveSelectedNodes(t *testing.T) {
code := run([]string{
"ops", "generate-helm-values",
"--out", filepath.Join(t.TempDir(), "values.yaml"),
"--target-node", "node-b",
"--target-node", "m02",
"--replication-factor", "3",
}, &stdout, &stderr)
if code != ops.VolumeStatusExitInvalid {
@@ -2966,7 +2962,7 @@ func TestOpsDescribeVolumeFromBundle(t *testing.T) {
for _, want := range []string{
"cluster status=degraded volumes=1",
"volume pvc-observed status=ok rf=3 ack=sync-quorum",
"primary r2 on node-b frontend=192.168.1.184:3260",
"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())
@@ -2984,7 +2980,7 @@ func TestOpsDescribeVolumeFromBundlePrefersProductClusterEvidence(t *testing.T)
for _, want := range []string{
"cluster status=ok volumes=1 nodes=1",
"volume pvc-product status=ok rf=3 ack=sync-quorum",
"primary r2 on node-b frontend=192.168.1.184:3260",
"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())
@@ -3341,7 +3337,7 @@ func TestOpsReportFromBundleSkipsCorruptClusterEvidenceCandidate(t *testing.T) {
ReplicationFactor: 1,
Status: ops.ObservationStatusOK,
PrimaryReplica: "r1",
PrimaryNode: "node-b",
PrimaryNode: "m02",
PublishTarget: "192.168.1.184:3260",
}}
raw, err := ops.MarshalObservationJSON(cluster)
@@ -3513,7 +3509,7 @@ func TestOpsExplainVolumeFromBundleBlockedImagePull(t *testing.T) {
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 node-b
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)
@@ -3525,7 +3521,7 @@ deployment.apps/sw-block-csi-controller 1/1 1 1 2m3s block-csi sw-block-csi:loca
}
for _, want := range []string{
"volume pvc-blocked status=blocked rf=3 reason=csi_node_image_pull_failed",
"waiting=ImagePullBackOff on node node-b image sw-block-csi:local",
"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())
@@ -3551,7 +3547,7 @@ func TestOpsDescribeVolumeLiveInventory(t *testing.T) {
"cluster status=ok volumes=1 nodes=0",
"volume pvc-live status=ok rf=1 ack=best-effort",
"pvc default/app-live",
"primary r1 on node-b frontend=127.0.0.1:3260",
"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())
@@ -3583,7 +3579,7 @@ func TestOpsClusterAndVolumesLiveInventory(t *testing.T) {
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=node-b frontend=127.0.0.1:3260") {
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())
}
}
@@ -3601,9 +3597,9 @@ func cleanCmdResidueCommand(_ context.Context, name string, args ...string) ([]b
}
}
const cmdHelmNodeWide = `node-a Ready worker 10d v1.34.4+k3s1 192.168.1.181 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
node-b Ready control-plane 10d v1.34.4+k3s1 192.168.1.184 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
node-c Ready worker 10d v1.34.4+k3s1 192.168.1.188 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
const cmdHelmNodeWide = `m01 Ready worker 10d v1.34.4+k3s1 192.168.1.181 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
m02 Ready control-plane 10d v1.34.4+k3s1 192.168.1.184 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
tp01 Ready worker 10d v1.34.4+k3s1 192.168.1.188 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
bad1 Ready,SchedulingDisabled worker 10d v1.34.4+k3s1 192.168.1.199 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
bad2 NotReady worker 10d v1.34.4+k3s1 192.168.1.200 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
bad3 Ready worker 10d v1.34.4+k3s1 127.0.0.1 <none> Ubuntu 24.04 6.8.0 containerd://2.0.0
@@ -3630,7 +3626,7 @@ const cmdSingleDeploymentListJSON = `{
"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":"node-b"},"containers":[{"name":"blockvolume","args":["--server-id=node-b","--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"]}]}}},
"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}
}
]
@@ -3655,7 +3651,7 @@ func writeCmdObservationBundle(t *testing.T) string {
{
ReplicaID: "r2",
ServerID: "node-loss-r2",
NodeName: "node-b",
NodeName: "m02",
Observed: true,
Protocol: "iscsi",
FrontendAddress: "192.168.1.184:3260",
@@ -3677,7 +3673,7 @@ func writeCmdObservationBundle(t *testing.T) string {
{
ReplicaID: "r3",
ServerID: "node-loss-r3",
NodeName: "node-c",
NodeName: "tp01",
Observed: true,
Protocol: "iscsi",
FrontendAddress: "192.168.1.188:3260",
@@ -3705,7 +3701,7 @@ func writeCmdObservationBundle(t *testing.T) string {
if err := os.WriteFile(filepath.Join(dir, "demo", ops.NodeLossRecoverySummaryArtifact), []byte(strings.Join([]string{
"result=promoted",
"ack_profile=sync-quorum",
"promoted=r2@node-b",
"promoted=r2@m02",
"before_frontend=192.168.1.181:3260",
"after_frontend=192.168.1.184:3260",
"reader_verified=true",
@@ -3731,7 +3727,7 @@ func writeCmdProductClusterBundle(t *testing.T) string {
cluster.ProductRevision = "product-cluster-rev"
cluster.Status = ops.ObservationStatusOK
cluster.Nodes = []ops.NodeEvidence{{
NodeName: "node-b",
NodeName: "m02",
InternalIP: "192.168.1.184",
Schedulable: true,
Ready: true,
@@ -3748,11 +3744,11 @@ func writeCmdProductClusterBundle(t *testing.T) string {
ObservedReplicas: 3,
Status: ops.ObservationStatusOK,
PrimaryReplica: "r2",
PrimaryNode: "node-b",
PrimaryNode: "m02",
PublishTarget: "192.168.1.184:3260",
Replicas: []ops.ReplicaEvidence{{
ReplicaID: "r2",
KubernetesNode: "node-b",
KubernetesNode: "m02",
Observed: true,
Role: "primary",
FrontendAddr: "192.168.1.184:3260",
@@ -3796,7 +3792,7 @@ func writeCmdReturnedReplicaBundle(t *testing.T) string {
ReplicationFactor: 2,
Status: ops.ObservationStatusRecovering,
PrimaryReplica: "r2",
PrimaryNode: "node-b",
PrimaryNode: "m02",
PublishTarget: "192.168.1.184:3260",
Epoch: 2,
EndpointVersion: 1,
@@ -3804,7 +3800,7 @@ func writeCmdReturnedReplicaBundle(t *testing.T) string {
RequiredFrontierLSN: 4241,
Replicas: []ops.ReplicaEvidence{{
ReplicaID: "r1",
KubernetesNode: "node-a",
KubernetesNode: "m01",
Observed: true,
Role: "previous_primary",
ReplicationRole: "replica_ready",
@@ -3818,7 +3814,7 @@ func writeCmdReturnedReplicaBundle(t *testing.T) string {
SupportBundlePath: "returned-replica-summary.txt",
}, {
ReplicaID: "r2",
KubernetesNode: "node-b",
KubernetesNode: "m02",
Observed: true,
Role: "primary",
Healthy: true,
@@ -3856,7 +3852,7 @@ func writeCmdReturnedReplicaRebuildBundle(t *testing.T) string {
ReplicationFactor: 3,
Status: ops.ObservationStatusRecovering,
PrimaryReplica: "r2",
PrimaryNode: "node-b",
PrimaryNode: "m02",
PublishTarget: "192.168.1.184:3260",
Epoch: 3,
EndpointVersion: 7,
@@ -3864,7 +3860,7 @@ func writeCmdReturnedReplicaRebuildBundle(t *testing.T) string {
RequiredFrontierLSN: 4241,
Replicas: []ops.ReplicaEvidence{{
ReplicaID: "r1",
KubernetesNode: "node-a",
KubernetesNode: "m01",
Observed: true,
Role: "previous_primary",
ReplicationRole: "replica_behind",
@@ -3878,7 +3874,7 @@ func writeCmdReturnedReplicaRebuildBundle(t *testing.T) string {
SupportBundlePath: "returned-replica-rebuild-summary.txt",
}, {
ReplicaID: "r2",
KubernetesNode: "node-b",
KubernetesNode: "m02",
Observed: true,
Role: "primary",
Healthy: true,
@@ -4004,7 +4000,7 @@ func (cmdFakeClusterEvidenceServer) GetClusterStatus(context.Context, *control.G
ObservedReplicas: 3,
Status: ops.ObservationStatusOK,
PrimaryReplica: "r2",
PrimaryNode: "node-b",
PrimaryNode: "m02",
PublishTarget: "192.168.1.184:3260",
Epoch: 2,
EndpointVersion: 1,
@@ -4014,7 +4010,7 @@ func (cmdFakeClusterEvidenceServer) GetClusterStatus(context.Context, *control.G
EventTime: timestamppb.Now(),
VolumeId: "v1",
ReplicaId: "r2",
NodeName: "node-b",
NodeName: "m02",
EventType: ops.EventTypeCSIReattachObserved,
Severity: "info",
Message: "CSI staged volume on node",
@@ -1,91 +0,0 @@
package main
import (
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
// masterStorePathsOutsideState lists every blockmaster store path under
// /var/lib that the docs, the README or the example env give (as
// --lifecycle-store, --authority-store or SWB_MASTER_AUTHORITY_STORE) and that
// is not inside the shipped unit's StateDirectory. ProtectSystem=strict makes
// every other /var/lib path read-only, so blockmaster would stop there.
func masterStorePathsOutsideState(root string) ([]string, error) {
unit, err := os.ReadFile(filepath.Join(root, "deploy", "systemd", "sw-blockmaster.service"))
if err != nil {
return nil, err
}
m := regexp.MustCompile(`(?m)^StateDirectory=([^ ]+?)[ ]*$`).FindSubmatch([]byte(strings.ReplaceAll(string(unit), string(rune(13)), "")))
if m == nil {
return nil, os.ErrNotExist
}
state := "/var/lib/" + strings.TrimSpace(string(m[1]))
paths := regexp.MustCompile("(?:--(?:lifecycle|authority)-store[ =]+|SWB_MASTER_AUTHORITY_STORE=)(/var/lib/[^ \"'`,)]+)")
var bad []string
check := func(path string) error {
raw, err := os.ReadFile(path)
if err != nil {
return err
}
for _, p := range paths.FindAllStringSubmatch(string(raw), -1) {
got := strings.TrimRight(strings.TrimSpace(p[1]), ".;:")
if got != state && !strings.HasPrefix(got, state+"/") {
rel, _ := filepath.Rel(root, path)
bad = append(bad, filepath.ToSlash(rel)+": "+got)
}
}
return nil
}
for _, dir := range []string{"docs", filepath.Join("deploy", "config")} {
err := filepath.WalkDir(filepath.Join(root, dir), func(path string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() || !(strings.HasSuffix(path, ".md") || strings.HasSuffix(path, ".env")) {
return err
}
return check(path)
})
if err != nil {
return nil, err
}
}
if err := check(filepath.Join(root, "README.md")); err != nil && !os.IsNotExist(err) {
return nil, err
}
return bad, nil
}
// The documented blockmaster store paths and the shipped unit agree: each
// one under /var/lib is inside the unit's only writable state directory.
func TestMasterStorePathsInTheDocsAreWritableUnderTheShippedUnit(t *testing.T) {
bad, err := masterStorePathsOutsideState(filepath.Join("..", ".."))
if err != nil {
t.Fatal(err)
}
if len(bad) > 0 {
t.Fatalf("store paths outside the shipped unit's writable state directory: %v", bad)
}
}
// The guard finds a documented store path outside the unit's state directory.
func TestMasterStorePathGuardFindsAPathOutsideTheUnitState(t *testing.T) {
root := t.TempDir()
for name, body := range map[string]string{
"deploy/systemd/sw-blockmaster.service": "[Service]\nStateDirectory=sw-block-master\n",
"deploy/config/blockmaster.env": "SWB_MASTER_AUTHORITY_STORE=/var/lib/sw-block-master/authority\n",
"docs/manual.md": "blockmaster --lifecycle-store /var/lib/sw-block/lifecycle --workspace-rpc\n",
} {
p := filepath.Join(root, filepath.FromSlash(name))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
bad, err := masterStorePathsOutsideState(root)
if err != nil || len(bad) != 1 || bad[0] != "docs/manual.md: /var/lib/sw-block/lifecycle" {
t.Fatalf("guard over a wrong path: %v %v, want the manual's path", bad, err)
}
}
@@ -1,49 +0,0 @@
package main
import (
"context"
"flag"
"os"
"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"
)
func evidenceMasterTLSFlags(fs *flag.FlagSet) *link.TLSFiles {
f := evidenceMasterTLSFromEnv()
fs.StringVar(&f.Cert, "master-tls-cert", f.Cert, "client certificate for blockmaster (PEM; defaults to SW_BLOCK_TLS_CERT)")
fs.StringVar(&f.Key, "master-tls-key", f.Key, "client certificate key (PEM; defaults to SW_BLOCK_TLS_KEY)")
fs.StringVar(&f.CA, "master-ca", f.CA, "CA for blockmaster (PEM; defaults to SW_BLOCK_TLS_CA; all three TLS files required)")
return &f
}
func evidenceMasterTLSFromEnv() link.TLSFiles {
return link.TLSFiles{Cert: os.Getenv(link.EnvTLSCert), Key: os.Getenv(link.EnvTLSKey), CA: os.Getenv(link.EnvTLSCA)}
}
func readMasterClusterEvidenceWithTLS(ctx context.Context, addr string, files *link.TLSFiles) (ops.ClusterEvidence, error) {
f := evidenceMasterTLSFromEnv()
if files != nil {
f = *files
}
var tls grpc.DialOption
var err error
if f.Enabled() {
tls, err = link.ClientCredentials(f, "")
if err != nil {
return ops.ClusterEvidence{}, err
}
}
conn, err := link.DialMaster(addr, tls)
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
}
@@ -1,101 +0,0 @@
package main
import (
"bytes"
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/auth"
"github.com/seaweedfs/seaweed-block/core/auth/authtest"
"github.com/seaweedfs/seaweed-block/core/host/master"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
)
func TestOpsEvidenceFlagsReachAMutualTLSMaster(t *testing.T) {
for _, key := range []string{link.EnvTLSCert, link.EnvTLSKey, link.EnvTLSCA, "KUBERNETES_SERVICE_HOST"} {
t.Setenv(key, "")
}
ca := authtest.NewCA(t, "evidence-ca")
dir := t.TempDir()
caFile := ca.WriteCA(t, dir)
serverCert, serverKey := ca.Issue(t, "blockmaster", time.Now().Add(time.Hour)).WriteFiles(t, dir, "master")
viewer := ca.Issue(t, "operator-status", time.Now().Add(time.Hour))
cert, key := viewer.WriteFiles(t, dir, "viewer")
roles, err := auth.ParseRoleFile(strings.NewReader(viewer.Fingerprint + " viewer operator-status\n"))
if err != nil {
t.Fatal(err)
}
creds, err := link.ServerCredentials(link.TLSFiles{Cert: serverCert, Key: serverKey, CA: caFile})
if err != nil {
t.Fatal(err)
}
h, err := master.New(master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(),
Auth: auth.NewAuthenticator(roles, nil), ServerOptions: []grpc.ServerOption{creds}})
if err != nil {
t.Fatal(err)
}
h.Start()
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := h.Close(ctx); err != nil {
t.Error(err)
}
})
for _, command := range []string{"cluster", "report", "dashboard"} {
t.Run(command, func(t *testing.T) {
out := t.TempDir()
args := []string{"ops", command, "--master-api", h.Addr(), "--timeout", "2s",
"--master-tls-cert", cert, "--master-tls-key", key, "--master-ca", caFile}
switch command {
case "cluster":
args = append(args, "-o", "json")
case "report":
args = append(args, "--out", out)
case "dashboard":
args = append(args, "--listen", "127.0.0.1:0", "--serve-duration", "1ms")
}
var stdout, stderr bytes.Buffer
if code := run(args, &stdout, &stderr); code != ops.VolumeStatusExitOK {
t.Fatalf("exit=%d stderr=%s", code, &stderr)
}
if command == "report" {
if _, err := os.Stat(filepath.Join(out, ops.ObservationReportJSONArtifact)); err != nil {
t.Fatal(err)
}
}
})
}
t.Run("environment defaults", func(t *testing.T) {
t.Setenv(link.EnvTLSCert, cert)
t.Setenv(link.EnvTLSKey, key)
t.Setenv(link.EnvTLSCA, caFile)
var stdout, stderr bytes.Buffer
if code := run([]string{"ops", "cluster", "--master-api", h.Addr()}, &stdout, &stderr); code != 0 {
t.Fatalf("environment identity: exit=%d stderr=%s", code, &stderr)
}
})
wrongCA := authtest.NewCA(t, "untrusted-ca").WriteCA(t, t.TempDir())
for _, c := range []struct {
name string
flags []string
}{
{"no identity", nil},
{"partial identity", []string{"--master-tls-cert", cert}},
{"untrusted server", []string{"--master-tls-cert", cert, "--master-tls-key", key, "--master-ca", wrongCA}},
} {
t.Run(c.name, func(t *testing.T) {
var stdout, stderr bytes.Buffer
args := append([]string{"ops", "cluster", "--master-api", h.Addr(), "--timeout", "200ms"}, c.flags...)
if code := run(args, &stdout, &stderr); code != ops.VolumeStatusExitInvalid || stderr.Len() == 0 {
t.Fatalf("invalid credentials accepted: exit=%d stdout=%s stderr=%s", code, &stdout, &stderr)
}
})
}
}
+4 -15
View File
@@ -16,19 +16,8 @@ import (
)
type inspectionShell struct {
master, filer, chunkPath, serverID string
statusAddrs statusAddrList
timeout, maxClockSkew time.Duration
}
// statusAddrList is the repeatable -status-addr flag: the loopback status
// addresses of this host's holders, one per volume.
type statusAddrList []string
func (l *statusAddrList) String() string { return strings.Join(*l, ",") }
func (l *statusAddrList) Set(v string) error {
*l = append(*l, v)
return nil
master, filer, chunkPath, statusAddr, serverID string
timeout, maxClockSkew time.Duration
}
func runShell(args []string, input io.Reader, stdout, stderr io.Writer) int {
@@ -39,14 +28,14 @@ func runShell(args []string, input io.Reader, stdout, stderr io.Writer) int {
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.Var(&s.statusAddrs, "status-addr", "a loopback holder status address on this host; repeat it, one per volume")
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']")
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 != "" {
Loaded 100 of 558 files, more files were not shown because too many files have changed in this diff. Show more