diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index 8a969f1aa6..98b86e56d9 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -227,6 +227,10 @@ func run(f flags) int { fmt.Fprintln(os.Stderr, "blockmaster:", err) return 2 } + if err := requireProductLoop(f.lifecycleLoop, f.expectedSlotsPerVol, clusterImport); err != nil { + fmt.Fprintln(os.Stderr, "blockmaster:", err) + return 2 + } if len(topo.Volumes) == 0 && len(clusterImport.Nodes) == 0 { // Without a topology the observation host classifies every // volume UnknownReplicaClaim; controller can never mint. diff --git a/seaweed-block/cmd/blockmaster/product_loop_guard.go b/seaweed-block/cmd/blockmaster/product_loop_guard.go new file mode 100644 index 0000000000..cac699e81d --- /dev/null +++ b/seaweed-block/cmd/blockmaster/product_loop_guard.go @@ -0,0 +1,42 @@ +package main + +import ( + "fmt" + "time" +) + +// requireProductLoop refuses a start whose cluster spec holds a replicated +// volume (replication factor above 1) that the master could never decide: +// - one whose replication factor differs from --expected-slots-per-volume: +// the controller validates every replicated volume against that one +// count and refuses the whole decision when one differs, so it would +// stop every replicated volume's assignment and failover; +// - any, while the lifecycle product loop is off: on the cluster-spec path +// that loop alone binds a replicated volume's placement, mints its line +// and runs its promotion gate, so with the loop off it never gets a line. +// +// A static --topology (whose observation controller mints) and +// single-replica volumes are untouched. +func requireProductLoop(interval time.Duration, expectedSlots int, spec clusterSpecImport) error { + // Every cluster-spec volume has a placement intent (a placement-only + // entry, without size_bytes, has no volume spec), so the placements are + // what is read. + for _, p := range spec.Placements { + if p.DesiredRF > 1 && p.DesiredRF != expectedSlots { + return fmt.Errorf("cluster spec volume %s has replication factor %d but --expected-slots-per-volume is %d: "+ + "the master decides replicated volumes of one slot count only (one replicated factor per cluster)", + p.VolumeID, p.DesiredRF, expectedSlots) + } + } + if interval > 0 { + return nil + } + for _, p := range spec.Placements { + if p.DesiredRF > 1 { + return fmt.Errorf("cluster spec volume %s has replication factor %d but --lifecycle-product-loop-interval is 0 (off): "+ + "with --cluster-spec a replicated volume is bound and promoted only by that loop; set --lifecycle-product-loop-interval (for example 100ms)", + p.VolumeID, p.DesiredRF) + } + } + return nil +} diff --git a/seaweed-block/cmd/blockmaster/product_loop_guard_test.go b/seaweed-block/cmd/blockmaster/product_loop_guard_test.go new file mode 100644 index 0000000000..3d201b78c4 --- /dev/null +++ b/seaweed-block/cmd/blockmaster/product_loop_guard_test.go @@ -0,0 +1,164 @@ +package main + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// clusterSpecWithRF writes a cluster spec of three nodes and one volume v1 +// with the given replication factor (placements on the first rf nodes). +func clusterSpecWithRF(t *testing.T, rf int) string { return clusterSpecText(t, rf, true) } + +// clusterSpecText is clusterSpecWithRF with or without size_bytes (without: +// a placement-only entry, which has a placement intent and no volume spec). +func clusterSpecText(t *testing.T, rf int, sized bool) string { + t.Helper() + var b strings.Builder + b.WriteString("nodes:\n") + for i := 1; i <= 3; i++ { + b.WriteString(" - server_id: s" + string(rune('0'+i)) + "\n data_addr: 127.0.0.1:1" + string(rune('0'+i)) + "601\n ctrl_addr: 127.0.0.1:1" + string(rune('0'+i)) + "602\n") + } + b.WriteString("volumes:\n - id: v1\n") + if sized { + b.WriteString(" size_bytes: 268435456\n") + } + b.WriteString(" replication_factor: " + string(rune('0'+rf)) + "\n placements:\n") + for i := 1; i <= rf; i++ { + b.WriteString(" - server_id: s" + string(rune('0'+i)) + "\n replica_id: r" + string(rune('0'+i)) + "\n") + } + p := filepath.Join(t.TempDir(), "cluster-spec.yaml") + if err := os.WriteFile(p, []byte(b.String()), 0o600); err != nil { + t.Fatal(err) + } + return p +} + +// guardHelperEnv carries a blockmaster command line (fields separated by +// guardHelperSep) to the helper process below. +const ( + guardHelperEnv = "SWB_BLOCKMASTER_GUARD_HELPER_ARGS" + guardHelperSep = "\x1f" +) + +// TestGuardHelperProcess is not a test on its own: re-executed by +// TestReplicatedClusterSpecWithTheProductLoopOffIsRefused, it runs +// blockmaster's run with the given arguments and exits with its code. +func TestGuardHelperProcess(t *testing.T) { + args := os.Getenv(guardHelperEnv) + if args == "" { + t.Skip("helper process only") + } + f, err := parseFlags(strings.Split(args, guardHelperSep)) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(64) + } + os.Exit(run(f)) +} + +// A replicated cluster-spec volume with the product loop off is refused at +// start, naming the flag, before anything is opened (exit 2). blockmaster +// runs as a bounded child: without the guard it would start and serve, so +// the child is killed at the deadline and joined (exec closes its pipes). +func TestReplicatedClusterSpecWithTheProductLoopOffIsRefused(t *testing.T) { + args := []string{ + "--authority-store", filepath.Join(t.TempDir(), "authority"), + "--lifecycle-store", filepath.Join(t.TempDir(), "lifecycle"), + "--cluster-spec", clusterSpecWithRF(t, 3), + "--expected-slots-per-volume", "3", + "--listen", "127.0.0.1:0", + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + t.Cleanup(cancel) + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestGuardHelperProcess$") + cmd.Env = append(os.Environ(), guardHelperEnv+"="+strings.Join(args, guardHelperSep)) + cmd.WaitDelay = 5 * time.Second + out, err := cmd.CombinedOutput() // returns once the child exited (or was killed) and its pipes closed + if ctx.Err() != nil { + t.Fatalf("blockmaster started with a replicated cluster spec and the product loop off (killed at the deadline):\n%s", out) + } + var exit *exec.ExitError + if !errors.As(err, &exit) || exit.ExitCode() != 2 || !strings.Contains(string(out), "--lifecycle-product-loop-interval") || !strings.Contains(string(out), "v1") { + t.Fatalf("exit %v, output %q; want exit 2 and the flag named", err, out) + } +} + +// The same spec with the loop on, a single-replica spec with the loop off, +// and no cluster spec (a static topology) all pass the guard. +func TestTheProductLoopGuardPassesWhatItShould(t *testing.T) { + for name, c := range map[string]struct { + rf int + interval time.Duration + }{ + "rf3 with the loop on": {3, 100 * time.Millisecond}, + "rf1 with the loop off": {1, 0}, + } { + spec, err := loadClusterSpec(clusterSpecWithRF(t, c.rf)) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if err := requireProductLoop(c.interval, c.rf, spec); err != nil { + t.Fatalf("%s: refused: %v", name, err) + } + } + if err := requireProductLoop(0, 3, clusterSpecImport{}); err != nil { + t.Fatalf("no cluster spec (static topology): refused: %v", err) + } + spec, err := loadClusterSpec(clusterSpecWithRF(t, 2)) + if err != nil { + t.Fatal(err) + } + if err := requireProductLoop(0, 2, spec); err == nil { + t.Fatal("rf2 with the loop off passed") + } +} + +// A replicated cluster-spec volume whose replication factor differs from +// --expected-slots-per-volume is refused at start, naming the volume and +// both counts, also with the loop on; a matching one passes. +func TestAClusterSpecVolumeOfAnotherReplicationFactorIsRefused(t *testing.T) { + spec, err := loadClusterSpec(clusterSpecWithRF(t, 2)) + if err != nil { + t.Fatal(err) + } + err = requireProductLoop(100*time.Millisecond, 3, spec) + if err == nil || !strings.Contains(err.Error(), "v1") || !strings.Contains(err.Error(), "--expected-slots-per-volume is 3") { + t.Fatalf("an RF2 volume on an expected-3 master: %v; want a refusal naming v1 and both counts", err) + } + if err := requireProductLoop(100*time.Millisecond, 2, spec); err != nil { + t.Fatalf("an RF2 volume on an expected-2 master: refused: %v", err) + } +} + +// A placement-only replicated entry (no size_bytes: no volume spec, only a +// placement intent) is checked the same way: RF2 on an expected-3 master is +// refused, and RF3 with the loop off is refused. +func TestAPlacementOnlyClusterSpecVolumeIsChecked(t *testing.T) { + for _, c := range []struct { + name string + rf int + interval time.Duration + want string + }{ + {"rf2 on expected 3", 2, 100 * time.Millisecond, "--expected-slots-per-volume is 3"}, + {"rf3 with the loop off", 3, 0, "--lifecycle-product-loop-interval is 0"}, + } { + spec, err := loadClusterSpec(clusterSpecText(t, c.rf, false)) + if err != nil { + t.Fatalf("%s: %v", c.name, err) + } + if len(spec.Volumes) != 0 || len(spec.Placements) != 1 { + t.Fatalf("%s: fixture: %d volume specs, %d placements; want a placement-only entry", c.name, len(spec.Volumes), len(spec.Placements)) + } + if err := requireProductLoop(c.interval, 3, spec); err == nil || !strings.Contains(err.Error(), c.want) { + t.Fatalf("%s: %v; want a refusal with %q", c.name, err, c.want) + } + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 21be9fb9c5..5740fb270d 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -717,6 +717,7 @@ Notes: | `INV-AUTH-HOLDER-IDENTITY-001` | A primary holder is the pair (server id, replica id): every site that decides holdership (adopting a fact, lease first grant, renew, re-grant, HEAD claim, superseded exit) compares both; a missing server id is refused, never guessed. | AUTHORITY: PRIMARY holdership (supporting replicas are not holders) | `core/host/volume/host.go` `applyFact`, `IsSuperseded`, `recordOtherLine`; `assignment_holder.go` `assignmentNamesSelf`, `observeForeignHolder`, `refusePrimaryAssignment`; `host.go` `IsSuperseded`; `core/host/master/services.go` `SubscribeAssignments`; `workspace_service.go` `holderMatches`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`; `cmd/blockvolume/chunk_remote.go` `chunkHolder`; `core/frontend/chunkstore/layout/start.go` `Start`, `core/frontend/chunkstore/layout/claim.go` `Claim`; superseded exit covered by #409; `core/host/master/workspace_binding.go` `workspaceLineOwner`, `workspaceSourceHost`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/server_host_identity.go` `refuseServerIDFromOtherHost` (from `ReportHeartbeat`), `refuseWorkspaceHolderHost` (from `holderMatches` and, for a workspace volume, `SubscribeAssignments`), `holderSlotFact` (from `QueryVolumeStatus` and `observationVolume`/`observationReplicas`); `core/csi/master_backend.go` `primaryOwnedFrontends` (a CSI target only from a usable primary frontend); `core/authority/snapshot_builder.go` `expectOwnerForLine` (a moved line's replica facts and endpoint refreshes only from its owner, #425) | `TestAssignmentHolderIdentityRestartedOldProcess`, `TestAssignmentHolderIdentityMatchingServerStillAdopts`, `TestAssignmentHolderIdentityFencesPreviouslyHealthySameReplica`, `TestAssignmentHolderIdentityAdoptsAndWarnsCarriedEndpointMismatch`, `TestAssignmentHolderIdentityForeignStreamOrdering`, `TestAssignmentHolderIdentityForcedMoveRefusesEveryDeliveredVersion`, `TestAssignmentHolderIdentitySameEpochCannotChangeServer` (`core/host/volume/assignment_holder_test.go`); `TestWorkspaceLeaseGuardCarriesHolderServerIdentity` (`core/host/volume/workspace_holder_identity_test.go`); `TestWorkspaceLeaseRequiresHolderServerForGrantRenewAndRegrant`, `TestWorkspaceRevocationACKRequiresHolderServer` (`core/host/master/workspace_holder_identity_test.go`); `TestWorkspaceRPCCleanMovePreservesReplicaIdentity` (`core/host/master/workspace_service_test.go`); HEAD claim: `TestChunkHolderIsServerAndReplica` (`cmd/blockvolume/chunk_remote_test.go`), `TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced` (`core/frontend/durable/provider_chunk_holder_test.go`); superseded exit: covered by #409 (server-id/replica-id pair, never replica alone); supporting replicas are not holders; descriptor identity not in this row; `TestWorkspaceLineOwnerIssuedAndHistorical` (`core/host/master/workspace_line_owner_test.go`), `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestAssignmentFactKeepsCapturedMoveOwnerWithoutReadableJournal` (`core/host/master/assignment_fact_owner_test.go`), `TestAssignmentOwnerReservedAndIssuedCapture` (`core/authority/assignment_owner_test.go`), `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestServerIDRefusedFromAHostOtherThanItsRegisteredOne`, `TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream`, `TestPortalAndPrimaryComeFromTheLineServerNotTheFreshestHeartbeat`, `TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot`, `TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing`, `TestCSIPublishesNoTargetWhenThePrimaryFrontendIsMissingOrRejected`, `TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck` (`core/host/master/server_host_identity_test.go`); `TestPublishTargetIsPrimaryOwned` (`core/csi/primary_owned_frontend_test.go`). Host scope: registered advertised-host consistency, not process uniqueness; a workspace holder's server id must be registered (no first-seen binding: host addresses change); non-workspace heartbeats from an unregistered id are not checked. Limits: with mutual TLS on, a node may act only for the server id bound to its certificate (`TERM-CALLER-001`; `auth.RequireNode` in `ReportHeartbeat`, `SubscribeAssignments`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`, `QueryVolumeStatus`; `TestNodeActsOnlyForItsOwnServerID`, `core/host/master/auth_red_test.go`), and the registered-host check stays beside it (no NAT or proxy between volume and master in OSS); in development mode (plaintext on loopback, no role file) there is no authentication; `TestBuildSnapshotTakesTheMovedLinesReplicaFromItsOwner` (`core/authority/line_owner_snapshot_test.go`); `TestProcedureForcedMoveWithTheOldHostReturning` (`cmd/blockvolume/procedure_gate_integration_test.go`, tags subprocess chunkstore_integration: every forced-epoch line carries the new owner's endpoints) | `WorkspaceRegrant` `NoForeignAdoption`, `TargetNotFencedByOwnLine` (round 4 pinned simulations only; exhaustive combo10 pending) | ACTIVE | | `INV-AUTH-CALLER-ROLE-001` | With mutual TLS on, every blockmaster gRPC call (unary, and before every stream send) is decided by the caller's certificate and the current role file: an unknown caller is refused UNAUTHENTICATED, a role its method's rule does not admit PERMISSION_DENIED, a method without a rule always. | AUTHORITY: control API callers (people, tools, nodes) | `core/auth/identity.go` `Authenticator.PeerIdentity`, `Authenticator.Reload`; `core/auth/authorize.go` `Rule.Allows`, `UnaryInterceptor`, `StreamInterceptor`, `RequireNode`, `RequireRole`; `core/host/master/authz.go` `masterRules`, `serverAuth`; `core/rpc/link/tls.go` `ServerCredentials`, `ClientCredentials`; `cmd/blockmaster/auth.go` `authFlags.validate`, `authFlags.build` | `TestPeerIdentity`, `TestRoleFileReload` (`core/auth/identity_test.go`); `TestRuleAllows`, `TestRequireNodeAndRole`, `TestUnaryInterceptor`, `TestStreamEndsAtTheReloadThatRevokesItsCaller` (`core/auth/authorize_test.go`); `TestMasterAuthorizationTableCoversEveryMethod` (`core/host/master/authz_test.go`); `TestForcedMoveNeedsAnAdmin`, `TestNodeActsOnlyForItsOwnServerID` (`core/host/master/auth_red_test.go`); `TestMasterLinkMutualTLS` (`core/rpc/link/tls_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`); `TestMasterTLSFlags` (`cmd/blockvolume/master_tls_test.go`). Also: a mutating operator or admin method writes its audit attempt before it runs or is refused as audit unavailable (`Rule.Strict`; `TestMasterOperatorMethodsAreStrict` (inverted: a new operator or admin method fails unless strict or named with its reason), `core/host/master/authz_test.go`; `TestStrictCallsNeedTheirAttemptLine`, `core/auth/strict_audit_test.go`), node calls never wait on the audit log; a reload that removes a caller, or changes its role so the method's rule no longer admits it, ends its open streams at the reload; a forced move needs an admin; plaintext listens only on loopback without a role file (development mode). Limits: the audit log records outcomes and decides nothing; the volume process's own HTTP routes stay loopback-only and unauthenticated. | `AuthLease` (exhaustive run pending) | ACTIVE | | `INV-AUTH-ONE-REPLICATED-FACTOR-001` | CreateVolume admits a replicated volume only if the master can decide it: its replication factor equals the master's one slot count (--expected-slots-per-volume) and the lifecycle product loop runs (only that loop binds, mints and promotes it). | M2 none → Bound (a created replicated volume's first line) | `core/host/master/services.go` `CreateVolume`; `core/host/master/host.go` `Config.LifecycleProductLoop`; `core/authority/controller.go` `ExpectedSlotsPerVolume`, `validateVolumeTopology` | `TestAnRF2CreateOnAnRF3MasterIsRefusedAndFailoverContinues`, `TestAReplicatedCreateWithTheProductLoopOffIsRefused` (`core/host/master/create_rf_mismatch_test.go`) | — (an admission check). Limits: single-replica volumes are admitted at any slot count (they never reach the check); a static --topology file with a mismatched volume is not checked at start (a cluster spec is: `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001`) | ACTIVE | +| `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001` | blockmaster refuses to start when its cluster spec holds a replicated volume it could never decide: one whose replication factor differs from --expected-slots-per-volume, or any while the lifecycle product loop is off (only that loop binds, mints and promotes it). | M2 none → Bound (a replicated cluster-spec volume's first line) | `cmd/blockmaster/product_loop_guard.go` `requireProductLoop`; `cmd/blockmaster/main.go` `run` | `TestReplicatedClusterSpecWithTheProductLoopOffIsRefused`, `TestTheProductLoopGuardPassesWhatItShould`, `TestAClusterSpecVolumeOfAnotherReplicationFactorIsRefused`, `TestAPlacementOnlyClusterSpecVolumeIsChecked` (`cmd/blockmaster/product_loop_guard_test.go`) | — (a startup configuration check). Limits: static `--topology` is not refused (its observation controller mints), and has no automatic failover in v1 | ACTIVE | | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestLayoutGrantedEpochIssuerSites`, `TestLayoutEpochEnumerationRejectsANewIssuer`, `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-RESTART-REISSUE-001` | A line records the primary process it was issued for (durable); a current primary reporting another process is re-issued its line at a new endpoint version, and a primary adopts no line issued for another process, so a restarted process never reuses the dead one's sessions. | M2 authority (RefreshEndpoint); M3 primary adoption | `core/authority/authority.go` `applyWithWorkspaceMove` (records the ask's or the source's incarnation); `core/authority/controller.go` `endpointStale`, `sameAsk`; `core/authority/workspace.go` `persistWorkspaceTimedLocked`; `core/authority/observation_store.go` `SlotFactAt`; `core/host/master/host.go` (the source); `core/host/volume/host.go` `applyFact` | `TestPublisher_RestartedPrimaryGetsANewEndpointVersion`, `TestPublisher_AskWithoutAProcessIsIssuedForTheReportedOne`, `TestTopologyController_RestartedPrimaryAtTheSameAddressIsReissued`, `TestTopologyController_QueuedRefreshIsReplacedForANewerProcess`, `TestTopologyController_UnnamedLineIsReissuedOnceForTheReportingProcess`, `TestWorkspaceLeaseWriteKeepsTheLinesIncarnationAcrossReload`, `TestObservationStore_SlotFactAtIsTheProcessAtThoseEndpoints` (`core/authority/restart_endpoint_version_test.go`); `TestLinesNameTheirPrimarysProcess`, `TestLineForTheTargetsEndpointsNamesTheTargetsProcess` (`core/host/master/line_incarnation_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted`, `TestHost_ApplyFact_UnnamedLineIsNotAdoptedWhereLinesNameTheirProcess` (`core/host/volume/line_incarnation_test.go`); `TestHostConfigAdoptsOnlyLinesNamingThisProcess` (`cmd/blockvolume/lines_name_their_process_test.go`); `TestRestartedPrimaryAtTheSameEpochIsAdmitted` (`core/replication/primary_restart_session_test.go`) | — | ACTIVE | | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, a failed write does not publish it, and an unknown outcome (directory fsync after the rename failed) fail-stops blockmaster: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/authority_store_file.go` `Put` (`failStopDurabilityUnknown` after a failed directory open or fsync behind the rename, every record; a close error after a good fsync is reported written; Windows keeps its previous behaviour) | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`); `TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename`, `TestPutReportsWrittenWhenOnlyTheDirectoryCloseFails` (`core/authority/authority_store_dir_fsync_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE |