From 77e150d22e5c4558ea76d9fc7c5fcdcb44ad44df Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 13:28:06 -0800 Subject: [PATCH] blockmaster: one HEAD reader, the layout catalog The master read HEAD two ways with two settings: the layout catalog (filer gRPC, --chunk-filer) for create and restore, and plain filer HTTP ?metadata=true (--workspace-head-base-url) for the workspace move admission and the revoke ACK. The workspace reader now reads through the catalog it already dials: BCatalog.ReadHeadObserved returns HEAD, decoded by the same DecodeLayoutHeadEntry, with the entry's modification time from that same lookup (seconds, as the HTTP metadata gave it). The proof mapping is unchanged: identity from the master's lifecycle record, deleting, unclaimed, detached, generation, epoch, holder and position; an absent HEAD refuses with ErrHeadAbsent. The HTTP reader and --workspace-head-base-url are deleted, with the unit's and the env file's setting and the docs. The master tests run the same refusal table against a catalog on the in-memory filer (the HTTP-only redirect and envelope cases have no counterpart). The fixtures that passed the flag give the master the filer flags instead; the head-size and F1 ladder masters had none and could not dial the catalog at all. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockmaster/main.go | 8 +- .../blockvolume/head_size_integration_test.go | 2 +- .../planned_handoff_integration_test.go | 2 +- .../snapshot_ladder_f1_integration_test.go | 42 ++-- .../startup_systemd_integration_test.go | 2 +- .../workspace_layout_move_integration_test.go | 7 +- .../workspace_lease_binary_test.go | 7 +- .../core/frontend/chunkstore/catalog_b.go | 10 + .../frontend/chunkstore/head_readers_test.go | 60 +++--- .../core/frontend/chunkstore/layout_store.go | 24 ++- .../core/host/master/workspace_layout_head.go | 78 ++----- .../host/master/workspace_layout_head_test.go | 195 +++++++++--------- .../core/host/master/workspace_protocol.md | 2 +- seaweed-block/deploy/config/blockmaster.env | 7 +- .../deploy/systemd/sw-blockmaster.service | 1 - .../docs/design/agent-workspace-design.md | 2 +- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/standalone-deployment.md | 7 +- seaweed-block/docs/volume-lifecycle.md | 10 +- 19 files changed, 229 insertions(+), 239 deletions(-) diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index d42f53dd68..45bed62682 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -63,7 +63,6 @@ type flags struct { failbackRuntimeRPC bool workspaceMaxClockSkew time.Duration workspaceRPC bool - workspaceHEADBase string chunkFiler string chunkPath string chunkCollection string @@ -127,7 +126,6 @@ func parseFlags(args []string) (flags, error) { fs.BoolVar(&f.failbackRuntimeRPC, "failback-runtime-rpc", false, "enable disabled-by-default authority failback RPC; requires expected-current and terminal evidence") fs.DurationVar(&f.workspaceMaxClockSkew, "workspace-max-clock-skew", 20*time.Second, "maximum workspace clock skew; host lease shortens by half, forced moves wait the full bound") fs.BoolVar(&f.workspaceRPC, "workspace-rpc", false, "enable RF1 workspace lease/revocation/move RPCs") - fs.StringVar(&f.workspaceHEADBase, "workspace-head-base-url", "", "filer HTTP base containing -/HEAD; required with --workspace-rpc") chunkstore.RegisterSWFSFlags(fs, &f.chunkFiler, &f.chunkPath, &f.chunkCollection, &f.chunkReplication) fs.BoolVar(&f.frontendPublicationRuntimeHTTP, "frontend-publication-runtime-http", false, "enable disabled-by-default frontend publication HTTP runtime; confirms post-failback authority publication only") fs.StringVar(&f.frontendPublicationRuntimeListen, "frontend-publication-runtime-listen", "127.0.0.1:9334", "HTTP listen address for --frontend-publication-runtime-http") @@ -244,6 +242,9 @@ func run(f flags) int { return 1 } cfg.Auth, cfg.ServerOptions = authn, serverOpts + // The layout catalog is the master's one HEAD source (create, restore and + // the workspace reader all read through it). + var layoutCat *chunkstore.BCatalog if f.workspaceRPC { cat, client, err := chunkstore.DialBCatalog(context.Background(), chunkstore.SWFSConfig{ FilerGRPC: f.chunkFiler, Collection: f.chunkCollection, @@ -258,6 +259,7 @@ func run(f flags) int { cfg.LayoutReadVolume = layoutVolumeReader(cat) cfg.LayoutReadHead = layoutHeadReader(cat) cfg.LayoutCreateTarget = layoutTargetCreator(cat) + layoutCat = cat } if authn != nil { if days, until, err := certDaysLeft(f.auth.tlsCert, f.auth.tlsKey, time.Now()); err == nil { @@ -269,7 +271,7 @@ func run(f flags) int { // New starts no loops: bind h before Start permits any HEAD request. var h *master.Host if f.workspaceRPC { - reader, err := master.NewLayoutWorkspaceHEADReader(f.workspaceHEADBase, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) { + reader, err := master.NewLayoutWorkspaceHEADReader(layoutCat, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) { return h.WorkspaceLayoutVolume(ctx, name) }) if err != nil { diff --git a/seaweed-block/cmd/blockvolume/head_size_integration_test.go b/seaweed-block/cmd/blockvolume/head_size_integration_test.go index 64c56a107b..aaad2aa32a 100644 --- a/seaweed-block/cmd/blockvolume/head_size_integration_test.go +++ b/seaweed-block/cmd/blockvolume/head_size_integration_test.go @@ -235,7 +235,7 @@ func headSzStartCluster(t *testing.T, prefix string, vols []headSzVol) (*handoff mstate := filepath.Join(h.dir, "master") margs := []string{"--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"), "--cluster-spec", specPath, "--expected-slots-per-volume", "1", "--listen", h.masterAddr, - "--workspace-rpc", "--workspace-head-base-url", "http://" + env.cluster.filerHTTP + env.chunkPath} + "--workspace-rpc", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath} if testListenHost() != "127.0.0.1" { // a lab run spanning two hosts: blockmaster refuses a non-loopback listen without this margs = append(margs, "--insecure-external-bind") diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index 0b84820d0e..92f7b45550 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -284,7 +284,7 @@ func startHandoffEnvConfigured(t *testing.T, n int, targets []string, tlsNotAfte env.masterArgs = append([]string{ "--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"), "--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr, - "--workspace-rpc", "--workspace-head-base-url", "http://" + cluster.filerHTTP + chunkPath}, masterArgs...) + "--workspace-rpc"}, masterArgs...) env.masterArgs = append(env.masterArgs, "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath) master := h.start(t, "blockmaster", h.master, env.masterArgs...) env.masterProcess = master diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go index 1f7d66e966..09705b39e1 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_f1_integration_test.go @@ -111,20 +111,20 @@ type f1Sample struct { // f1Round is one volume's measurements in one round. type f1Round struct { - Volume string `json:"volume"` - Round int `json:"round"` - SnapshotMs float64 `json:"snapshot_request_to_commit_ms"` - CutTotalMs float64 `json:"cut_total_ms"` - BarrierPauseMs float64 `json:"cut_barrier_pause_ms"` - UploadedChunks int `json:"uploaded_chunks"` - UploadedBytes int64 `json:"uploaded_bytes"` - HostSlotWaits uint64 `json:"host_slot_waits"` - SlotRetries int `json:"snapshot_slot_refusals_retried"` - SlotWaitMs float64 `json:"snapshot_slot_wait_ms"` - RestoreMs float64 `json:"restore_ms"` + Volume string `json:"volume"` + Round int `json:"round"` + SnapshotMs float64 `json:"snapshot_request_to_commit_ms"` + CutTotalMs float64 `json:"cut_total_ms"` + BarrierPauseMs float64 `json:"cut_barrier_pause_ms"` + UploadedChunks int `json:"uploaded_chunks"` + UploadedBytes int64 `json:"uploaded_bytes"` + HostSlotWaits uint64 `json:"host_slot_waits"` + SlotRetries int `json:"snapshot_slot_refusals_retried"` + SlotWaitMs float64 `json:"snapshot_slot_wait_ms"` + RestoreMs float64 `json:"restore_ms"` // RestoreExact is true or false for a snapshot that ran, "not_run" for // one that was never admitted. - RestoreExact any `json:"restore_exact"` + RestoreExact any `json:"restore_exact"` LoadPrefix int `json:"load_prefix_blocks"` WritesIn int `json:"writes_in_window"` WritesOut int `json:"writes_outside_window"` @@ -140,15 +140,15 @@ type f1Round struct { } type f1Report struct { - Config f1Config `json:"config"` - Limiter string `json:"limiter"` - StartedAt time.Time `json:"started_at"` - Rounds []f1Round `json:"rounds"` + Config f1Config `json:"config"` + Limiter string `json:"limiter"` + StartedAt time.Time `json:"started_at"` + Rounds []f1Round `json:"rounds"` Health []f1Health `json:"heartbeat_health"` - CommitBound float64 `json:"commit_bound_ms"` - WriteErrors int `json:"write_errors"` - Verdict string `json:"verdict"` - Failures []string `json:"failures,omitempty"` + CommitBound float64 `json:"commit_bound_ms"` + WriteErrors int `json:"write_errors"` + Verdict string `json:"verdict"` + Failures []string `json:"failures,omitempty"` } func TestSnapshotLadderF1VolumesOneHost(t *testing.T) { @@ -236,7 +236,7 @@ func f1StartEnv(t *testing.T, cfg f1Config) (*handoffEnv, *daemon) { mstate := filepath.Join(h.dir, "master") env.masterArgs = []string{"--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"), "--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr, - "--workspace-rpc", "--workspace-head-base-url", "http://" + env.cluster.filerHTTP + env.chunkPath} + "--workspace-rpc", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath} master := h.start(t, "blockmaster", h.master, env.masterArgs...) master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=") env.masterProcess = master diff --git a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go index a9cce04ef7..3f3f7f0e7d 100644 --- a/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go +++ b/seaweed-block/cmd/blockvolume/startup_systemd_integration_test.go @@ -90,7 +90,7 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) { "--listen", masterListen, "--tls-cert", filepath.Join(tlsDir, "master.crt"), "--tls-key", filepath.Join(tlsDir, "master.key"), "--tls-client-ca", filepath.Join(tlsDir, "ca.crt"), "--role-file", filepath.Join(tlsDir, "roles"), "--audit-log", filepath.Join(tlsDir, "audit.log"), "--authority-store", filepath.Join(root, "auth"), "--lifecycle-store", filepath.Join(root, "life"), "--cluster-spec", spec, "--lifecycle-product-loop-interval", "200ms", "--expected-slots-per-volume", "1", - "--workspace-rpc", "--workspace-head-base-url", "http://"+cluster.filerHTTP+base, + "--workspace-rpc", // A workspace master writes the layout VOLUME and unclaimed HEAD itself. "--chunk-filer", cluster.filerGRPC, "--chunk-path", base) w4WaitTCP(t, masterAddr, 20*time.Second) diff --git a/seaweed-block/cmd/blockvolume/workspace_layout_move_integration_test.go b/seaweed-block/cmd/blockvolume/workspace_layout_move_integration_test.go index 4d591c600f..18bc5d3c11 100644 --- a/seaweed-block/cmd/blockvolume/workspace_layout_move_integration_test.go +++ b/seaweed-block/cmd/blockvolume/workspace_layout_move_integration_test.go @@ -146,8 +146,13 @@ func TestIntegrationWorkspaceLayoutMove(t *testing.T) { func layoutMove(t *testing.T, exe string, cluster *w4WeedCluster, kind string) { base := fmt.Sprintf("/workspace-move-%s-%d", kind, time.Now().UnixNano()) + cl := cluster.client(t, base) + headCat, err := chunkstore.NewBCatalog(cl, cl, base) + if err != nil { + t.Fatal(err) + } var h *master.Host - reader, err := master.NewLayoutWorkspaceHEADReader("http://"+cluster.filerHTTP+base, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) { + reader, err := master.NewLayoutWorkspaceHEADReader(headCat, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) { return h.WorkspaceLayoutVolume(ctx, name) }) if err != nil { diff --git a/seaweed-block/cmd/blockvolume/workspace_lease_binary_test.go b/seaweed-block/cmd/blockvolume/workspace_lease_binary_test.go index 7a8cd22f34..fd1fa67583 100644 --- a/seaweed-block/cmd/blockvolume/workspace_lease_binary_test.go +++ b/seaweed-block/cmd/blockvolume/workspace_lease_binary_test.go @@ -70,8 +70,13 @@ func TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown(t *testing.T) { for _, enabled := range []bool{false, true} { t.Run(fmt.Sprintf("workspace-rpc-%v", enabled), func(t *testing.T) { base := fmt.Sprintf("/workspace-lease-%d", time.Now().UnixNano()) + cl := cluster.client(t, base) + headCat, err := chunkstore.NewBCatalog(cl, cl, base) + if err != nil { + t.Fatal(err) + } var h *master.Host - reader, err := master.NewLayoutWorkspaceHEADReader("http://"+cluster.filerHTTP+base, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) { + reader, err := master.NewLayoutWorkspaceHEADReader(headCat, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) { return h.WorkspaceLayoutVolume(ctx, name) }) if err != nil { diff --git a/seaweed-block/core/frontend/chunkstore/catalog_b.go b/seaweed-block/core/frontend/chunkstore/catalog_b.go index 610738d7dd..c10d8e7462 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_b.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_b.go @@ -89,6 +89,16 @@ func (c *BCatalog) ReadHead(ctx context.Context, v VolumeRef) (layout.Head, bool return s.ReadHead(ctx) } +// ReadHeadObserved reads the volume's HEAD with its entry's modification +// time (LayoutStore.ReadHeadObserved): the master's one HEAD reader. +func (c *BCatalog) ReadHeadObserved(ctx context.Context, v VolumeRef) (layout.Head, int64, bool, error) { + s, err := c.Store(v) + if err != nil { + return layout.Head{}, 0, false, err + } + return s.ReadHeadObserved(ctx) +} + // DeleteSnapshot removes the named snapshot; refused while it has // dependents. func (c *BCatalog) DeleteSnapshot(ctx context.Context, v VolumeRef, name string) (layout.Head, error) { diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 89a39e53e7..a4cf3b8e48 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -19,38 +19,40 @@ import ( ) // headReaders is every function outside tests that reads a volume's HEAD -// (ReadHead, GetHead, GetHeadRoot, getHeadRoot, headExists, or a LookupEntry +// (ReadHead, ReadHeadObserved, GetHead, GetHeadRoot, getHeadRoot, headExists, or a LookupEntry // of HEAD), with what it does when HEAD is absent and the probe below that // pins it. "GAP" marks a reader that takes an absent HEAD for an empty // one; a change that treats an absent HEAD as unknown flips those probes. var headReaders = map[string]string{ - "core/frontend/durable/provider_seal_replay.go readLayoutSeal -> ReadHead": "absent, unreadable and foreign layout proof refuse without cached success (TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory)", - "core/frontend/durable/provider_layout.go settleLayoutStop -> ReadHead": "absent refuses unknown stop outcome, never resumes (probe TestLayoutStopAbortMustConfirmItsOutcome)", - "core/frontend/durable/provider_layout.go startLayoutRoot -> ReadHead": "the diagnostic re-read after Start refusal cannot turn an absent HEAD into a claim; Start already refused it (probe TestLayoutStoreMissingHEADRefusesStart)", - "cmd/blockvolume/workspace_lease.go workspaceLayoutDetachedGeneration -> ReadHead": "absent refuses ACK (probe TestWorkspaceLayoutDetachedProof)", - "cmd/blockvolume/chunk_remote.go chunkAttachCheck -> ReadHead": "absent refuses attach without creating VOLUME or HEAD (TestChunkAttachCheckAppliesVolumeRules)", - "core/frontend/chunkstore/layout_store.go ReadHead -> DecodeLayoutHeadEntry": "shared canonical entry decoder; no missing HEAD is invented (TestLayoutStoreMissingHEADRefusesStart)", - "core/host/master/workspace_layout_head.go NewLayoutWorkspaceHEADReader -> DecodeLayoutHeadEntry": "any missing/failed metadata refuses; identity comes from master intent (TestWorkspaceLayoutHEADRefusalsAndStates)", - "cmd/blockmaster/layout_create.go layoutHeadReader -> ReadHead": "absent refuses restore before target persistence (TestMasterLayoutHeadReaderRefusesAbsentHead)", - "core/host/volume/chunk_control.go ListSnapshots -> ReadHead": "refuses ErrHeadAbsent without creating HEAD (TestChunkControlUsesTheBoundLayoutIdentity)", - "core/frontend/chunkstore/layout_store.go ReadHead -> LookupEntry": "found=false; Start refuses without writing (probe TestLayoutStoreMissingHEADRefusesStart)", - "core/frontend/chunkstore/layout/delete.go OperatorReleaseDependent -> ReadHead": "reads the source's HEAD (absent: refuses ErrHeadAbsent) and the target's: a target without HEAD (never created, or a restore that died between its VOLUME and its HEAD) gets a deleted HEAD written exclusively before the release (probe LayoutOperatorRelease)", - "core/frontend/chunkstore/layout/start.go Start -> ReadHead": "refuses ErrHeadAbsent and creates nothing (probe LayoutStart)", - "core/frontend/chunkstore/layout/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and writes nothing to the objects (probe LayoutRemoval)", - "core/frontend/chunkstore/layout/snapshots.go RunAddDependent -> ReadHead": "refuses ErrHeadAbsent before reading any root and writes nothing (probe LayoutAddDependent)", - "core/frontend/chunkstore/catalog_b.go DeleteVolume -> ReadHead": "refuses ErrHeadAbsent before any write (probe BCatalog)", - "core/frontend/chunkstore/catalog_b.go ReadHead -> ReadHead": "found=false to the caller, which reports no HEAD (probe BCatalog)", - "core/frontend/chunkstore/retain_b.go Retain -> ReadHead": "refuses ErrHeadAbsent, deletes nothing (probe BCatalog)", - "core/frontend/chunkstore/retain_b.go SetRetention -> ReadHead": "refuses ErrHeadAbsent, writes no policy (probe BCatalog)", - "core/frontend/chunkstore/catalog_b.go Usage -> ReadHead": "refuses ErrHeadAbsent (probe BCatalog)", - "core/frontend/chunkstore/layout_remote.go AbortOpenSession -> ReadHead": "refuses ErrHeadAbsent, aborts nothing (probe LayoutRemote)", - "core/frontend/chunkstore/layout_remote.go CommitPendingSnapshot -> ReadHead": "refuses ErrHeadAbsent, commits nothing (probe LayoutRemote)", - "core/frontend/durable/provider_layout_snapshot.go SnapshotVolume -> ReadHead": "the layout remote's HEAD read: refuses ErrHeadAbsent, names nothing (probe LayoutRemote)", - "core/frontend/chunkstore/layout_remote.go CASHead -> ReadHead": "refuses ErrHeadAbsent, writes nothing (probe LayoutRemote)", - "core/frontend/chunkstore/layout_remote.go ReadHead -> ReadHead": "refuses ErrHeadAbsent (probe LayoutRemote)", - "core/frontend/chunkstore/layout_remote.go rollBackLocked -> ReadHead": "refuses ErrHeadAbsent before any Begin or upload (probe LayoutRemote)", - "core/frontend/chunkstore/layout/create.go createVolume -> ReadHead": "reads HEAD only after its exclusive create found one; absent then refuses ErrIdentity, writes nothing more (probe LayoutCreate)", - "core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)", + "core/frontend/durable/provider_seal_replay.go readLayoutSeal -> ReadHead": "absent, unreadable and foreign layout proof refuse without cached success (TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory)", + "core/frontend/durable/provider_layout.go settleLayoutStop -> ReadHead": "absent refuses unknown stop outcome, never resumes (probe TestLayoutStopAbortMustConfirmItsOutcome)", + "core/frontend/durable/provider_layout.go startLayoutRoot -> ReadHead": "the diagnostic re-read after Start refusal cannot turn an absent HEAD into a claim; Start already refused it (probe TestLayoutStoreMissingHEADRefusesStart)", + "cmd/blockvolume/workspace_lease.go workspaceLayoutDetachedGeneration -> ReadHead": "absent refuses ACK (probe TestWorkspaceLayoutDetachedProof)", + "cmd/blockvolume/chunk_remote.go chunkAttachCheck -> ReadHead": "absent refuses attach without creating VOLUME or HEAD (TestChunkAttachCheckAppliesVolumeRules)", + "core/frontend/chunkstore/layout_store.go ReadHead -> ReadHeadObserved": "found=false passes through; no missing HEAD is invented (TestLayoutStoreMissingHEADRefusesStart)", + "core/frontend/chunkstore/layout_store.go ReadHeadObserved -> LookupEntry": "found=false; Start refuses without writing (probe TestLayoutStoreMissingHEADRefusesStart)", + "core/frontend/chunkstore/layout_store.go ReadHeadObserved -> DecodeLayoutHeadEntry": "shared canonical entry decoder for every HEAD reader (TestLayoutStoreMissingHEADRefusesStart)", + "core/frontend/chunkstore/catalog_b.go ReadHeadObserved -> ReadHeadObserved": "found=false to the caller (probe BCatalog)", + "core/host/master/workspace_layout_head.go NewLayoutWorkspaceHEADReader -> ReadHeadObserved": "absent refuses ErrHeadAbsent, any failed read refuses; identity comes from master intent (TestWorkspaceLayoutHEADRefusalsAndStates)", + "cmd/blockmaster/layout_create.go layoutHeadReader -> ReadHead": "absent refuses restore before target persistence (TestMasterLayoutHeadReaderRefusesAbsentHead)", + "core/host/volume/chunk_control.go ListSnapshots -> ReadHead": "refuses ErrHeadAbsent without creating HEAD (TestChunkControlUsesTheBoundLayoutIdentity)", + "core/frontend/chunkstore/layout/delete.go OperatorReleaseDependent -> ReadHead": "reads the source's HEAD (absent: refuses ErrHeadAbsent) and the target's: a target without HEAD (never created, or a restore that died between its VOLUME and its HEAD) gets a deleted HEAD written exclusively before the release (probe LayoutOperatorRelease)", + "core/frontend/chunkstore/layout/start.go Start -> ReadHead": "refuses ErrHeadAbsent and creates nothing (probe LayoutStart)", + "core/frontend/chunkstore/layout/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and writes nothing to the objects (probe LayoutRemoval)", + "core/frontend/chunkstore/layout/snapshots.go RunAddDependent -> ReadHead": "refuses ErrHeadAbsent before reading any root and writes nothing (probe LayoutAddDependent)", + "core/frontend/chunkstore/catalog_b.go DeleteVolume -> ReadHead": "refuses ErrHeadAbsent before any write (probe BCatalog)", + "core/frontend/chunkstore/catalog_b.go ReadHead -> ReadHead": "found=false to the caller, which reports no HEAD (probe BCatalog)", + "core/frontend/chunkstore/retain_b.go Retain -> ReadHead": "refuses ErrHeadAbsent, deletes nothing (probe BCatalog)", + "core/frontend/chunkstore/retain_b.go SetRetention -> ReadHead": "refuses ErrHeadAbsent, writes no policy (probe BCatalog)", + "core/frontend/chunkstore/catalog_b.go Usage -> ReadHead": "refuses ErrHeadAbsent (probe BCatalog)", + "core/frontend/chunkstore/layout_remote.go AbortOpenSession -> ReadHead": "refuses ErrHeadAbsent, aborts nothing (probe LayoutRemote)", + "core/frontend/chunkstore/layout_remote.go CommitPendingSnapshot -> ReadHead": "refuses ErrHeadAbsent, commits nothing (probe LayoutRemote)", + "core/frontend/durable/provider_layout_snapshot.go SnapshotVolume -> ReadHead": "the layout remote's HEAD read: refuses ErrHeadAbsent, names nothing (probe LayoutRemote)", + "core/frontend/chunkstore/layout_remote.go CASHead -> ReadHead": "refuses ErrHeadAbsent, writes nothing (probe LayoutRemote)", + "core/frontend/chunkstore/layout_remote.go ReadHead -> ReadHead": "refuses ErrHeadAbsent (probe LayoutRemote)", + "core/frontend/chunkstore/layout_remote.go rollBackLocked -> ReadHead": "refuses ErrHeadAbsent before any Begin or upload (probe LayoutRemote)", + "core/frontend/chunkstore/layout/create.go createVolume -> ReadHead": "reads HEAD only after its exclusive create found one; absent then refuses ErrIdentity, writes nothing more (probe LayoutCreate)", + "core/frontend/chunkstore/layout/head.go runTransition -> ReadHead": "refuses ErrHeadAbsent and writes nothing; no layout transition creates a HEAD (probe LayoutTransition)", // above the chunk store: they read through the layout remote's GetHead, so an // absent HEAD reaches them as ErrHeadAbsent, never as a zero HEAD (probe LayoutRemote) "cmd/sw-block/chunk_b.go chunkShow -> ReadHead": "found=false: prints a null head (probe TestOpsChunk_AbsentVolume)", @@ -102,7 +104,7 @@ func TestHeadReaders_Enumeration(t *testing.T) { case *ast.Ident: name = x.Name } - hit := name == "ReadHead" || name == "GetHead" || name == "GetHeadRoot" || name == "getHeadRoot" || name == "headExists" || name == "DecodeLayoutHeadEntry" + hit := name == "ReadHead" || name == "ReadHeadObserved" || name == "GetHead" || name == "GetHeadRoot" || name == "getHeadRoot" || name == "headExists" || name == "DecodeLayoutHeadEntry" if name == "LookupEntry" { for _, a := range call.Args { if id, ok := a.(*ast.Ident); ok && id.Name == "headName" { diff --git a/seaweed-block/core/frontend/chunkstore/layout_store.go b/seaweed-block/core/frontend/chunkstore/layout_store.go index 49467bb4b6..b5c325dfa6 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_store.go +++ b/seaweed-block/core/frontend/chunkstore/layout_store.go @@ -45,20 +45,34 @@ var _ layout.HeadStore = (*LayoutStore)(nil) var _ layout.ObjectStore = (*LayoutStore)(nil) func (s *LayoutStore) ReadHead(ctx context.Context) (layout.Head, bool, error) { + h, _, found, err := s.ReadHeadObserved(ctx) + return h, found, err +} + +// ReadHeadObserved is ReadHead with the HEAD entry's modification time as +// the filer reports it on the same lookup (seconds resolution; the commit +// that wrote HEAD set it), in nanoseconds; 0 when the entry carries none. +func (s *LayoutStore) ReadHeadObserved(ctx context.Context) (h layout.Head, mtimeNS int64, found bool, err error) { e, err := s.f.LookupEntry(ctx, s.root, layout.HeadName) if errors.Is(err, ErrNotFound) { - return layout.Head{}, false, nil + return layout.Head{}, 0, false, nil } if err != nil { - return layout.Head{}, false, err + return layout.Head{}, 0, false, err } - h, err := DecodeLayoutHeadEntry(e, s.id) - return h, err == nil, err + h, err = DecodeLayoutHeadEntry(e, s.id) + if err != nil { + return layout.Head{}, 0, false, err + } + if sec := e.GetAttributes().GetMtime(); sec > 0 { + mtimeNS = sec * int64(1e9) + } + return h, mtimeNS, true, nil } // DecodeLayoutHeadEntry validates the inline entry as one observation: its // generation and volume attributes must describe the canonical HEAD content. -// Both filer RPC and HTTP metadata readers use this boundary. +// Every HEAD reader (the holder's and the master's) uses this boundary. func DecodeLayoutHeadEntry(e *filerpb.Entry, id layout.VolumeID) (layout.Head, error) { if e == nil || e.IsDirectory { return layout.Head{}, fmt.Errorf("%w: HEAD is not a file", layout.ErrCorrupt) diff --git a/seaweed-block/core/host/master/workspace_layout_head.go b/seaweed-block/core/host/master/workspace_layout_head.go index 3e6e8df66a..3cb700238f 100644 --- a/seaweed-block/core/host/master/workspace_layout_head.go +++ b/seaweed-block/core/host/master/workspace_layout_head.go @@ -2,30 +2,29 @@ package master import ( "context" - "encoding/json" + "errors" "fmt" - "io" - "net/http" - "net/url" - "os" - "strings" - "time" "github.com/seaweedfs/seaweed-block/core/authority" "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" ) -// NewLayoutWorkspaceHEADReader resolves the master's immutable identity before -// reading one ordinary filer metadata response. Content, generation and mtime -// come from that same entry; no legacy path or body decoder is a fallback. -func NewLayoutWorkspaceHEADReader(base string, resolve func(context.Context, string) (chunkstore.VolumeRef, error)) (func(context.Context, string) (authority.WorkspaceHead, error), error) { - u, err := url.Parse(base) - if err != nil || u == nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || resolve == nil { - return nil, fmt.Errorf("workspace HEAD needs an absolute HTTP directory and master volume resolver") +// LayoutHeadSource is the catalog as the master reads HEAD through it: the +// same filer RPC read the holder uses, with the entry's modification time +// (chunkstore.BCatalog.ReadHeadObserved). +type LayoutHeadSource interface { + ReadHeadObserved(ctx context.Context, v chunkstore.VolumeRef) (layout.Head, int64, bool, error) +} + +// NewLayoutWorkspaceHEADReader is the master's one HEAD reader: it resolves +// the volume's immutable identity from the master's own lifecycle record, +// then reads HEAD through the catalog. Content, generation and the head time +// come from that one entry; there is no second source. +func NewLayoutWorkspaceHEADReader(src LayoutHeadSource, resolve func(context.Context, string) (chunkstore.VolumeRef, error)) (func(context.Context, string) (authority.WorkspaceHead, error), error) { + if src == nil || resolve == nil { + return nil, errors.New("workspace HEAD needs the layout catalog and the master volume resolver") } - client := &http.Client{Timeout: 5 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} return func(ctx context.Context, name string) (authority.WorkspaceHead, error) { if err := ctx.Err(); err != nil { return authority.WorkspaceHead{}, err @@ -40,53 +39,12 @@ func NewLayoutWorkspaceHEADReader(base string, resolve func(context.Context, str if err := (layout.Volume{ID: v.ID, Name: v.Name, Format: layout.VolumeFormat}).CheckIdentity(); err != nil { return authority.WorkspaceHead{}, err } - endpoint := *u - endpoint.Path = strings.TrimRight(u.Path, "/") + "/" + v.Dir() + "/HEAD" - endpoint.RawPath = "" - endpoint.RawQuery = "metadata=true" - req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil) + h, mtime, found, err := src.ReadHeadObserved(ctx, v) if err != nil { return authority.WorkspaceHead{}, err } - res, err := client.Do(req) - if err != nil { - return authority.WorkspaceHead{}, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return authority.WorkspaceHead{}, fmt.Errorf("HEAD metadata read HTTP %d", res.StatusCode) - } - // HEAD is at most 64 KiB inline; allow its base64 envelope and ordinary - // filer attributes without accepting an unbounded metadata response. - const limit = 4 * layout.MaxHeadBytes - raw, err := io.ReadAll(io.LimitReader(res.Body, limit+1)) - if err != nil { - return authority.WorkspaceHead{}, err - } - if len(raw) > limit { - return authority.WorkspaceHead{}, fmt.Errorf("HEAD metadata too large") - } - var entry struct { - FullPath string - Content []byte - Extended map[string][]byte - Mtime time.Time - Mode uint32 - Chunks []*filerpb.FileChunk - } - if err := json.Unmarshal(raw, &entry); err != nil { - return authority.WorkspaceHead{}, err - } - if entry.FullPath != endpoint.Path { - return authority.WorkspaceHead{}, fmt.Errorf("HEAD metadata path mismatch") - } - h, err := chunkstore.DecodeLayoutHeadEntry(&filerpb.Entry{Name: "HEAD", IsDirectory: entry.Mode&uint32(os.ModeDir) != 0, Content: entry.Content, Extended: entry.Extended, Chunks: entry.Chunks}, v.ID) - if err != nil { - return authority.WorkspaceHead{}, err - } - mtime := int64(0) - if ns := entry.Mtime.UnixNano(); ns > 0 && time.Unix(0, ns).Equal(entry.Mtime) { - mtime = ns + if !found { + return authority.WorkspaceHead{}, layout.ErrHeadAbsent } proof := authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.Position, Detached: h.State == layout.StateDetached, FilerMtimeNS: mtime} if h.State == layout.StateDeleting || h.State == layout.StateDeleted { diff --git a/seaweed-block/core/host/master/workspace_layout_head_test.go b/seaweed-block/core/host/master/workspace_layout_head_test.go index f32c00b5fe..0bbd426508 100644 --- a/seaweed-block/core/host/master/workspace_layout_head_test.go +++ b/seaweed-block/core/host/master/workspace_layout_head_test.go @@ -3,13 +3,9 @@ package master import ( "bytes" "context" - "encoding/json" "errors" - "net/http" - "net/http/httptest" "sync/atomic" "testing" - "time" "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" @@ -26,45 +22,58 @@ func (workspaceHeadBlobs) Get(context.Context, string) ([]byte, error) { return nil, errors.New("HEAD reader must not hydrate") } +// headFiler counts HEAD lookups and can fail them (a filer that is down). +type headFiler struct { + *chunkstore.MemFiler + lookups atomic.Int32 + fail error +} + +func (f *headFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + f.lookups.Add(1) + if f.fail != nil { + return nil, f.fail + } + return f.MemFiler.LookupEntry(ctx, dir, name) +} + +func workspaceHeadCatalog(t *testing.T) (*chunkstore.BCatalog, *headFiler, chunkstore.VolumeRef) { + t.Helper() + id, _ := layout.ParseVolumeID("00112233445566778899aabbccddeeff") + f := &headFiler{MemFiler: chunkstore.NewMemFiler()} + cat, err := chunkstore.NewBCatalog(f, workspaceHeadBlobs{}, "/chunks") + if err != nil { + t.Fatal(err) + } + return cat, f, chunkstore.VolumeRef{Name: "v", ID: id} +} + +// The master's one HEAD reader reads through the catalog: identity from the +// master's own record, the proof and the head time from that one entry. func TestWorkspaceLayoutHEADUsesTheMasterIdentity(t *testing.T) { ctx := context.Background() - id, _ := layout.ParseVolumeID("00112233445566778899aabbccddeeff") - v := chunkstore.VolumeRef{Name: "v", ID: id} - f := chunkstore.NewMemFiler() - s, err := chunkstore.NewLayoutStore(f, workspaceHeadBlobs{}, "/chunks/"+v.Dir(), id) + cat, f, v := workspaceHeadCatalog(t) + s, err := cat.Store(v) if err != nil { t.Fatal(err) } rn := layout.RootName{Hash: layout.Sum([]byte("committed root"))} - h := layout.Head{VolumeID: id, Epoch: 3, Holder: "node/r", ClaimID: "claim", Activity: layout.Activity{Kind: layout.ActIdle}, Current: &rn, Position: 42, State: layout.StateDetached} - if err := s.CreateHead(ctx, layout.Unclaimed(id, nil)); err != nil { + h := layout.Head{VolumeID: v.ID, Epoch: 3, Holder: "node/r", ClaimID: "claim", Activity: layout.Activity{Kind: layout.ActIdle}, Current: &rn, Position: 42, State: layout.StateDetached} + if err := s.CreateHead(ctx, layout.Unclaimed(v.ID, nil)); err != nil { t.Fatal(err) } if err := s.UpdateHead(ctx, 1, h); err != nil { t.Fatal(err) } - e, err := f.LookupEntry(ctx, "/chunks/"+v.Dir(), "HEAD") + e, err := f.MemFiler.LookupEntry(ctx, "/chunks/"+v.Dir(), "HEAD") if err != nil { t.Fatal(err) } - mtime := time.Unix(100, 0).UTC() - var calls atomic.Int32 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - calls.Add(1) - w.Header().Set("Last-Modified", time.Unix(200, 0).UTC().Format(http.TimeFormat)) - if r.URL.Path != "/chunks/"+v.Dir()+"/HEAD" || r.URL.RawQuery != "metadata=true" { - t.Errorf("unbound HEAD path: %s", r.URL) - } - _ = json.NewEncoder(w).Encode(struct { - FullPath string - Content []byte - Extended map[string][]byte - Mtime time.Time - Chunks []*filerpb.FileChunk - }{r.URL.Path, e.Content, e.Extended, mtime, nil}) - })) - defer server.Close() - read, err := NewLayoutWorkspaceHEADReader(server.URL+"/chunks", func(_ context.Context, name string) (chunkstore.VolumeRef, error) { + e.Attributes = &filerpb.FuseAttributes{Mtime: 100} + if err := f.MemFiler.UpdateEntry(ctx, "/chunks/"+v.Dir(), e, nil); err != nil { + t.Fatal(err) + } + read, err := NewLayoutWorkspaceHEADReader(cat, func(_ context.Context, name string) (chunkstore.VolumeRef, error) { if name != "v" { return chunkstore.VolumeRef{}, errors.New("not registered") } @@ -73,70 +82,73 @@ func TestWorkspaceLayoutHEADUsesTheMasterIdentity(t *testing.T) { if err != nil { t.Fatal(err) } + f.lookups.Store(0) got, err := read(ctx, "v") - if err != nil || !got.Detached || got.Gen != 2 || got.Epoch != 3 || got.Holder != "node/r" || got.RemoteLSN != 42 || got.FilerMtimeNS != mtime.UnixNano() { + if err != nil || !got.Detached || got.Gen != 2 || got.Epoch != 3 || got.Holder != "node/r" || got.RemoteLSN != 42 || got.FilerMtimeNS != 100e9 { t.Fatalf("proof: %+v %v", got, err) } - if _, err := read(ctx, "other"); err == nil || calls.Load() != 1 { - t.Fatalf("resolver failure contacted filer: %d %v", calls.Load(), err) + if _, err := read(ctx, "other"); err == nil || f.lookups.Load() != 1 { + t.Fatalf("resolver failure contacted the filer: %d lookups, %v", f.lookups.Load(), err) } - if _, err := NewLayoutWorkspaceHEADReader(server.URL, nil); err == nil { + if _, err := NewLayoutWorkspaceHEADReader(cat, nil); err == nil { t.Fatal("nil identity resolver accepted") } + if _, err := NewLayoutWorkspaceHEADReader(nil, func(context.Context, string) (chunkstore.VolumeRef, error) { return v, nil }); err == nil { + t.Fatal("nil catalog accepted") + } + renamed, _ := NewLayoutWorkspaceHEADReader(cat, func(context.Context, string) (chunkstore.VolumeRef, error) { + return chunkstore.VolumeRef{Name: "w", ID: v.ID}, nil + }) + if _, err := renamed(ctx, "v"); !errors.Is(err, layout.ErrIdentity) { + t.Fatalf("a resolver naming another volume: %v; want ErrIdentity", err) + } } +// Every HEAD entry the shared decoder refuses is refused by the master too; +// the states map onto the proof (deleting, unclaimed, detached or live) and +// an entry without a modification time reports the head time unknown. func TestWorkspaceLayoutHEADRefusalsAndStates(t *testing.T) { id, _ := layout.ParseVolumeID("00112233445566778899aabbccddeeff") - v := chunkstore.VolumeRef{Name: "v", ID: id} rn := layout.RootName{Hash: layout.Sum([]byte("root"))} base := layout.Head{VolumeID: id, Epoch: 3, Holder: "node/r", ClaimID: "claim", Activity: layout.Activity{Kind: layout.ActIdle}, Current: &rn, Position: 42, State: layout.StateDetached} - type response struct { - FullPath string - Content []byte - Extended map[string][]byte - Mtime time.Time - Mode uint32 - Chunks []*filerpb.FileChunk - } for _, tc := range []struct { name string state string - alter func(*response) - status int - raw string + alter func(*filerpb.Entry) + absent bool + down bool valid bool sentinel error }{ {name: "detached", valid: true}, {name: "live", state: "live", valid: true}, - {name: "unknown mtime", valid: true, alter: func(e *response) { e.Mtime = time.Date(9999, 1, 1, 0, 0, 0, 0, time.UTC) }}, + {name: "unknown mtime", valid: true, alter: func(e *filerpb.Entry) { e.Attributes = nil }}, {name: "unclaimed", state: "unclaimed", sentinel: authority.ErrWorkspaceHeadUnclaimed}, {name: "deleted", state: layout.StateDeleted, sentinel: authority.ErrWorkspaceHeadDeleting}, - {name: "missing generation", alter: func(e *response) { delete(e.Extended, "swb.layout.gen") }}, - {name: "zero generation", alter: func(e *response) { e.Extended["swb.layout.gen"] = []byte("0") }}, - {name: "noncanonical generation", alter: func(e *response) { e.Extended["swb.layout.gen"] = []byte("09") }}, - {name: "wrong volume attribute", alter: func(e *response) { e.Extended["swb.layout.volume"] = []byte("ffffffffffffffffffffffffffffffff") }}, - {name: "wrong body volume", alter: func(e *response) { + {name: "missing generation", alter: func(e *filerpb.Entry) { delete(e.Extended, "swb.layout.gen") }}, + {name: "zero generation", alter: func(e *filerpb.Entry) { e.Extended["swb.layout.gen"] = []byte("0") }}, + {name: "noncanonical generation", alter: func(e *filerpb.Entry) { e.Extended["swb.layout.gen"] = []byte("09") }}, + {name: "wrong volume attribute", alter: func(e *filerpb.Entry) { e.Extended["swb.layout.volume"] = []byte("ffffffffffffffffffffffffffffffff") }}, + {name: "wrong body volume", alter: func(e *filerpb.Entry) { e.Content = bytes.ReplaceAll(e.Content, []byte(id.String()), []byte("ffffffffffffffffffffffffffffffff")) }}, - {name: "missing kind", alter: func(e *response) { delete(e.Extended, "swb.layout.kind") }}, - {name: "missing claim", alter: func(e *response) { e.Content = bytes.ReplaceAll(e.Content, []byte(`,"claim_id":"claim"`), nil) }}, - {name: "detached activity", alter: func(e *response) { + {name: "missing kind", alter: func(e *filerpb.Entry) { delete(e.Extended, "swb.layout.kind") }}, + {name: "missing claim", alter: func(e *filerpb.Entry) { e.Content = bytes.ReplaceAll(e.Content, []byte(`,"claim_id":"claim"`), nil) }}, + {name: "detached activity", alter: func(e *filerpb.Entry) { e.Content = bytes.ReplaceAll(e.Content, []byte(`"kind":"idle"`), []byte(`"kind":"snap","session":"s"`)) }}, - {name: "chunked HEAD", alter: func(e *response) { e.Chunks = []*filerpb.FileChunk{{FileId: "x"}} }}, - {name: "directory HEAD", alter: func(e *response) { e.Mode = 1 << 31 }}, - {name: "wrong path", alter: func(e *response) { e.FullPath = "/chunks/other/HEAD" }}, - {name: "legacy content", alter: func(e *response) { + {name: "chunked HEAD", alter: func(e *filerpb.Entry) { e.Chunks = []*filerpb.FileChunk{{FileId: "x"}} }}, + {name: "directory HEAD", alter: func(e *filerpb.Entry) { e.IsDirectory = true }}, + {name: "legacy content", alter: func(e *filerpb.Entry) { e.Content = []byte(`{"format":1,"gen":9,"epoch":3,"holder":"node/r","remote_lsn":42}`) }}, - {name: "oversized inline HEAD", alter: func(e *response) { e.Content = bytes.Repeat([]byte("x"), layout.MaxHeadBytes+1) }, sentinel: layout.ErrHeadTooLarge}, - {name: "not found", status: http.StatusNotFound}, - {name: "unavailable", status: http.StatusServiceUnavailable}, - {name: "malformed envelope", raw: "not JSON"}, - {name: "oversized envelope", raw: string(bytes.Repeat([]byte("x"), 4*layout.MaxHeadBytes+1))}, + {name: "oversized inline HEAD", alter: func(e *filerpb.Entry) { e.Content = bytes.Repeat([]byte("x"), layout.MaxHeadBytes+1) }, sentinel: layout.ErrHeadTooLarge}, + {name: "not found", absent: true, sentinel: layout.ErrHeadAbsent}, + {name: "unavailable", down: true}, } { t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + cat, f, v := workspaceHeadCatalog(t) h := base switch tc.state { case "live": @@ -151,55 +163,40 @@ func TestWorkspaceLayoutHEADRefusalsAndStates(t *testing.T) { if err != nil { t.Fatal(err) } - e := response{FullPath: "/chunks/" + v.Dir() + "/HEAD", Content: raw, Extended: map[string][]byte{"swb.layout.gen": []byte("9"), "swb.layout.kind": []byte("head"), "swb.layout.volume": []byte(id.String())}} + e := &filerpb.Entry{Name: "HEAD", Content: raw, Attributes: &filerpb.FuseAttributes{Mtime: 100}, + Extended: map[string][]byte{"swb.layout.gen": []byte("9"), "swb.layout.kind": []byte("head"), "swb.layout.volume": []byte(id.String())}} if tc.alter != nil { - tc.alter(&e) + tc.alter(e) } - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if tc.status != 0 { - w.WriteHeader(tc.status) - return + if !tc.absent { + if err := f.MemFiler.CreateEntry(ctx, "/chunks/"+v.Dir(), e, true); err != nil { + t.Fatal(err) } - if tc.raw != "" { - _, _ = w.Write([]byte(tc.raw)) - return - } - _ = json.NewEncoder(w).Encode(e) - })) - defer server.Close() - read, err := NewLayoutWorkspaceHEADReader(server.URL+"/chunks", func(context.Context, string) (chunkstore.VolumeRef, error) { return v, nil }) + } + if tc.down { + f.fail = errors.New("filer unavailable") + } + read, err := NewLayoutWorkspaceHEADReader(cat, func(context.Context, string) (chunkstore.VolumeRef, error) { return v, nil }) if err != nil { t.Fatal(err) } - got, err := read(context.Background(), "v") - if tc.valid { - if err != nil || got.Gen != 9 || got.Detached != (tc.state != "live") || got.FilerMtimeNS != 0 { + got, err := read(ctx, "v") + wantTime := int64(100e9) + if tc.name == "unknown mtime" { + wantTime = 0 + } + switch { + case tc.valid: + if err != nil || got.Gen != 9 || got.Detached != (tc.state != "live") || got.FilerMtimeNS != wantTime { t.Fatalf("valid proof: %+v %v", got, err) } - } else if tc.sentinel != nil { + case tc.sentinel != nil: if !errors.Is(err, tc.sentinel) { t.Fatalf("sentinel: %+v %v", got, err) } - } else if err == nil { + case err == nil: t.Fatalf("invalid proof accepted: %+v", got) } }) } } - -func TestWorkspaceLayoutHEADNeverFollowsRedirects(t *testing.T) { - var followed atomic.Int32 - target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { followed.Add(1) })) - defer target.Close() - source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, target.URL, http.StatusFound) })) - defer source.Close() - read, err := NewLayoutWorkspaceHEADReader(source.URL, func(context.Context, string) (chunkstore.VolumeRef, error) { - return chunkstore.VolumeRef{Name: "v", ID: layout.VolumeID{1}}, nil - }) - if err != nil { - t.Fatal(err) - } - if _, err := read(context.Background(), "v"); err == nil || followed.Load() != 0 { - t.Fatalf("redirect followed: %d %v", followed.Load(), err) - } -} diff --git a/seaweed-block/core/host/master/workspace_protocol.md b/seaweed-block/core/host/master/workspace_protocol.md index 69ef315fef..c6dd07eadb 100644 --- a/seaweed-block/core/host/master/workspace_protocol.md +++ b/seaweed-block/core/host/master/workspace_protocol.md @@ -1,7 +1,7 @@ # RF=1 workspace moves The opt-in master surface is `WorkspaceService` in `workspace.proto`. Enable it -with `blockmaster --workspace-rpc --workspace-head-base-url ` +with `blockmaster --workspace-rpc --chunk-filer ` and a lifecycle store. Other volumes continue using the existing assignment protocol. Workspace operations require an existing RF=1 volume. The target node must be registered; explicit volumes use their prepared per-volume endpoints, diff --git a/seaweed-block/deploy/config/blockmaster.env b/seaweed-block/deploy/config/blockmaster.env index 8e853aee88..822471926e 100644 --- a/seaweed-block/deploy/config/blockmaster.env +++ b/seaweed-block/deploy/config/blockmaster.env @@ -31,11 +31,10 @@ SWB_MASTER_FRESHNESS_WINDOW=30s # reported as unsupported. SWB_MASTER_PENDING_GRACE=1s # --workspace-rpc (default false). Enable the workspace lease, revocation and -# move RPCs (agent workspace disks, proof of concept). +# move RPCs (agent workspace disks, proof of concept). blockmaster then reads +# HEAD through the layout catalog: set --chunk-filer (and --chunk-path when +# it is not the default) in SWB_MASTER_EXTRA_ARGS. SWB_MASTER_WORKSPACE_RPC=false -# --workspace-head-base-url (default empty; required with --workspace-rpc). -# Filer HTTP directory that holds the per-volume HEAD files. -SWB_MASTER_WORKSPACE_HEAD_BASE_URL= # --workspace-max-clock-skew (default 20s; must be >10.1s and <60s). Host leases # shorten by half of it; forced moves wait the full bound. SWB_MASTER_WORKSPACE_MAX_CLOCK_SKEW=20s diff --git a/seaweed-block/deploy/systemd/sw-blockmaster.service b/seaweed-block/deploy/systemd/sw-blockmaster.service index 3687515b49..3342b8b865 100644 --- a/seaweed-block/deploy/systemd/sw-blockmaster.service +++ b/seaweed-block/deploy/systemd/sw-blockmaster.service @@ -24,7 +24,6 @@ ExecStart=/usr/local/bin/blockmaster \ --freshness-window=${SWB_MASTER_FRESHNESS_WINDOW} \ --pending-grace=${SWB_MASTER_PENDING_GRACE} \ --workspace-rpc=${SWB_MASTER_WORKSPACE_RPC} \ - --workspace-head-base-url=${SWB_MASTER_WORKSPACE_HEAD_BASE_URL} \ --workspace-max-clock-skew=${SWB_MASTER_WORKSPACE_MAX_CLOCK_SKEW} \ $SWB_MASTER_EXTRA_ARGS # blockmaster stops on SIGTERM. diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 67bba67690..02c55445e0 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -126,7 +126,7 @@ flowchart LR Data[Named snapshot data path] --> Commit[Commit snapshot name in HEAD] ``` -Blockmaster resolves that identity from its published lifecycle record and reads the filer's conventional `?metadata=true` endpoint once. The shared inline-HEAD decoder binds the entry generation and volume attributes to canonical content, including the claim-bearing detached image. The existing clean-move check still requires the expected epoch/holder and the recorded ACK of that generation. Failed or missing metadata refuses the move; there is no old-directory or old-codec fallback. Entry mtime comes from that same response and is diagnostic evidence, never authority. Do not edit, restore or remove HEAD outside the kernel; its single-entry generation is the proof version. +Blockmaster resolves that identity from its published lifecycle record and reads HEAD once through the layout catalog (the same filer gRPC read the holder uses); there is no second HEAD source. The shared inline-HEAD decoder binds the entry generation and volume attributes to canonical content, including the claim-bearing detached image. The existing clean-move check still requires the expected epoch/holder and the recorded ACK of that generation. Failed or missing metadata refuses the move; there is no old-directory or old-codec fallback. Entry mtime comes from that same entry and is diagnostic evidence, never authority. Do not edit, restore or remove HEAD outside the kernel; its single-entry generation is the proof version. Listings carry each snapshot's root and dependents. Usage reports snapshot/dependent counts and own/foreign current chunks; it does not synthesize byte accounting. Retention policy is read separately through the catalog. Snapshot entries carry their creation time, class, expiry and bounded labels, sampled once for a named capture and supplied as `CommitRequest.Meta`. A replay keeps the facts already in HEAD. Attach creates the identified VOLUME and unclaimed HEAD idempotently and never creates the legacy name-only directory. Snapshot creation belongs to the data path's HEAD commit, rather than a post-cut catalog write. The runtime cutover remains incomplete while scheduled snapshots, geometry checks and cleaning still reference the old catalog; those references must be removed before that catalog is deleted or this branch ships. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index c9e744005a..3d102d3595 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -777,7 +777,7 @@ Notes: | `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | | `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A same-host move issues a higher epoch: a clean move needs the current holder's sealed HEAD and its recorded epoch/holder/position ACK, and the successor reads that sealed image; a forced move needs the normal lease barrier and a durable lost-range record. | M2 Acked or Expired → Moved; M9 detached → higher-epoch idle | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/frontend/chunkstore/layout/start.go` `Start`, `core/frontend/chunkstore/layout/claim.go` `Claim` | `TestWorkspaceSameHostForcedMoveRecordsLostRange` (`core/authority/workspace_same_host_forced_test.go`); `TestWorkspaceRPCSameHostForcedRecoveryRecordsLoss` (`core/host/master/workspace_same_host_forced_test.go`); `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestLayoutSameHostCleanSuccessorReadsSealedImage` (`core/frontend/durable/provider_layout_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed`; `INV-SNAPK-DETACHED-001`. The B provider test performs a real plain detach, same-host higher-epoch fresh-root Start, and reads the sealed bytes. | ACTIVE | | `INV-WS-DELETE-NO-LIVE-HOLDER-001` | A workspace volume is marked deleting only with no live holder (`TERM-LIVE-HOLDER-001`): no line, a clean revocation ACK for the line, or HEAD below the line's epoch. A sealed HEAD without an ACK, a live or unreadable one is refused; the HEAD compare-and-swap to deleting fences a later claim. | M2 none/Granted/Revoking/Expired → Deleting | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence` | `TestWorkspaceHolderState` (`core/authority/workspace_holder_state_test.go`); `TestDeleteAdmitsANeverStartedLine` (`core/host/master/workspace_delete_never_started_test.go`); `TestDeleteAdmissionVerdicts` (`core/authority/workspace_delete_admission_test.go`); `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`) | NeverStarted r2 `DeleteNeverStrandsALiveHolder`, `NoServedWriteLost`, re-run can finish, re-run can settle (exhaustive, 21 of 21 configurations as expected). Not modelled: two delete processes at the same instant; the gap between HEAD deleted and the volume marked deleted | ACTIVE | -| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a revocation ACK matching its epoch, holder and published position; generation is readout only. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation`; `core/host/master/workspace_layout_head.go` `NewLayoutWorkspaceHEADReader` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`); `TestWorkspaceLayoutHEADUsesTheMasterIdentity`, `TestWorkspaceLayoutHEADRefusalsAndStates`, `TestWorkspaceLayoutHEADNeverFollowsRedirects`; `TestWorkspaceLayoutHEADReaderWiring` | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a revocation ACK matching its epoch, holder and published position; generation is readout only. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation`; `core/host/master/workspace_layout_head.go` `NewLayoutWorkspaceHEADReader` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`); `TestWorkspaceLayoutHEADUsesTheMasterIdentity`, `TestWorkspaceLayoutHEADRefusalsAndStates`, `TestWorkspaceLayoutHEADReaderWiring` | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-FORCED-MOVE-001` | A forced move is admitted only after the persisted lease horizon and the granted or restart deadline, each plus the clock-skew bound, have passed for the lease the last move issue started (never a predecessor's): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`); `TestProcedureMasterUnreachableFencesBeforeForcedMove` (`cmd/blockvolume/master_loss_integration_test.go`, tags `subprocess chunkstore_integration`) | — | ACTIVE | | `INV-WS-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry, never the persisted horizon. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE | | `INV-WS-FORCED-MOVE-HALF-SKEW-001` | The validity the master gives a host with a lease ends half the clock-skew bound before the reported lease expiry. | M2 Granted → Granted (reply); M4 NoLease, Valid → Valid | `core/authority/workspace_lease_view.go` `WorkspaceLeaseValidity`, `workspaceLeaseValidityAt`; `core/host/master/workspace_service.go` `leaseFact`; `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/volume/workspace_lease.go` `Refresh` | `TestWorkspaceLeaseFactUsesPublisherClockAndSkew` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceAckUsesGrantedHalfSkewBoundary` (`core/authority/workspace_validity_test.go`); `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index e28e754682..fe88d55bc4 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -168,8 +168,8 @@ listener before it has an assignment. Without one, the status shows | blockmaster logs `authority: rejected ask ...: workspace publication: no lifecycle VolumeRecord for v1; register it (CreateVolume) before publishing` | blockmaster runs with `--lifecycle-store`: a topology slot is then not enough, the volume also needs a volume record (below) | **Workspace lease volumes (`--workspace-lease`).** Besides the steps above, -blockmaster needs `--workspace-rpc`, `--workspace-head-base-url` and -`--lifecycle-store`, and the volume needs a single-replica volume record in +blockmaster needs `--workspace-rpc`, `--chunk-filer` (and blockvolume's +`--chunk-path`, when not the default) and `--lifecycle-store`, and the volume needs a single-replica volume record in that store. This release has no `sw-block` command that creates that record. Check with `sw-block ops workspace show --master 127.0.0.1:9180 --volume v1`; it names the first missing piece: `workspace RPC disabled`, `lifecycle store unavailable`, or `workspace move requires an existing RF1 @@ -186,8 +186,7 @@ with `move target node "s2" is not registered`. | `SWB_MASTER_EXPECTED_SLOTS` | `--expected-slots-per-volume` | `3` | Replica slots per volume; `1` for a single replica | | `SWB_MASTER_FRESHNESS_WINDOW` | `--freshness-window` | `30s` | How long a heartbeat stays fresh | | `SWB_MASTER_PENDING_GRACE` | `--pending-grace` | `1s` | Startup grace before a missing observation is unsupported | -| `SWB_MASTER_WORKSPACE_RPC` | `--workspace-rpc` | `false` | Workspace lease, revocation and move RPCs | -| `SWB_MASTER_WORKSPACE_HEAD_BASE_URL` | `--workspace-head-base-url` | empty | Filer HTTP directory of HEAD files; required with `--workspace-rpc` | +| `SWB_MASTER_WORKSPACE_RPC` | `--workspace-rpc` | `false` | Workspace lease, revocation and move RPCs; HEAD is read through the layout catalog (`--chunk-filer`, `--chunk-path` in `SWB_MASTER_EXTRA_ARGS`) | | `SWB_MASTER_WORKSPACE_MAX_CLOCK_SKEW` | `--workspace-max-clock-skew` | `20s` | Clock-skew bound for workspace leases and forced moves; must be >10.1s and <60s so half-skew exceeds the configured fence-exit budget, assuming normal scheduling | | `SWB_MASTER_EXTRA_ARGS` | any | empty | Other flags; the Kubernetes `--launcher-*` and `--lifecycle-*` flags are set by the Helm chart | diff --git a/seaweed-block/docs/volume-lifecycle.md b/seaweed-block/docs/volume-lifecycle.md index 03ba329007..7166736875 100644 --- a/seaweed-block/docs/volume-lifecycle.md +++ b/seaweed-block/docs/volume-lifecycle.md @@ -83,20 +83,20 @@ connects from (not loopback) in the cluster spec`. The loopback addresses above fit only when blockmaster and blockvolume run on the same machine. **3. blockmaster flags.** `--cluster-spec` replaces `--topology` (setting both -stops blockmaster). `--workspace-head-base-url` is the filer HTTP address plus -blockvolume's `--chunk-path`: +stops blockmaster). blockmaster reads HEAD through the layout catalog: `--chunk-filer` +is the filer gRPC address and `--chunk-path` is blockvolume's: ```bash blockmaster --authority-store /var/lib/sw-block-master/authority \ --lifecycle-store /var/lib/sw-block-master/lifecycle \ --cluster-spec /etc/sw-block/cluster-spec.yaml --expected-slots-per-volume 1 \ --listen 127.0.0.1:9180 --workspace-rpc \ - --workspace-head-base-url http://FILER_HTTP/swblock/chunks + --chunk-filer FILER_GRPC --chunk-path /swblock/chunks ``` With the example units: `SWB_MASTER_TOPOLOGY=` (empty), `SWB_MASTER_EXPECTED_SLOTS=1`, -`SWB_MASTER_WORKSPACE_RPC=true`, `SWB_MASTER_WORKSPACE_HEAD_BASE_URL=...`, and -`--lifecycle-store` and `--cluster-spec` in `SWB_MASTER_EXTRA_ARGS`. blockmaster +`SWB_MASTER_WORKSPACE_RPC=true`, and `--lifecycle-store`, `--cluster-spec`, +`--chunk-filer` and `--chunk-path` in `SWB_MASTER_EXTRA_ARGS`. blockmaster reads the file only at start. blockvolume runs with its identity from the spec (`--server-id s1 --volume-id v1