Merge G9G blockmaster product loop

This commit is contained in:
pingqiu committed 2026-05-03 06:59:27 -07:00
commit d142015633
6 files changed
+424 -13

No files matched your search

+68 -7
View File
@@ -16,16 +16,19 @@ import (
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/host/master"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
type flags struct {
authorityStore string
lifecycleStore string
listen string
topology string
expectedSlotsPerVol int
freshnessWindow time.Duration
pendingGrace time.Duration
authorityStore string
lifecycleStore string
lifecyclePlacementSeed string
listen string
topology string
expectedSlotsPerVol int
freshnessWindow time.Duration
pendingGrace time.Duration
lifecycleLoop time.Duration
// printReadyLine: test-only flag that emits a single
// structured JSON line to stdout after the gRPC listener is
// bound, so L2 subprocess tests can parse the ready event.
@@ -38,11 +41,13 @@ func parseFlags(args []string) (flags, error) {
fs := flag.NewFlagSet("blockmaster", flag.ContinueOnError)
fs.StringVar(&f.authorityStore, "authority-store", "", "durable authority store directory (required)")
fs.StringVar(&f.lifecycleStore, "lifecycle-store", "", "optional G9D product lifecycle registration store directory (desired volumes, node inventory, placement intents); read-only with respect to assignment publication")
fs.StringVar(&f.lifecyclePlacementSeed, "lifecycle-placement-seed", "", "optional G9G seed JSON file containing placement intents to import into --lifecycle-store before the product loop starts")
fs.StringVar(&f.listen, "listen", "127.0.0.1:0", "gRPC listen address (e.g. 127.0.0.1:9180)")
fs.StringVar(&f.topology, "topology", "", "path to accepted-topology YAML (required for assignment to mint)")
fs.IntVar(&f.expectedSlotsPerVol, "expected-slots-per-volume", 3, "RF/expected slot count per volume; the controller rejects observation snapshots whose slot count differs (default 3, set to 2 for 2-node smoke clusters)")
fs.DurationVar(&f.freshnessWindow, "freshness-window", 30*time.Second, "observation freshness window before a server's heartbeat expires")
fs.DurationVar(&f.pendingGrace, "pending-grace", 1*time.Second, "bootstrap/missing-observation grace before supportability reports unsupported")
fs.DurationVar(&f.lifecycleLoop, "lifecycle-product-loop-interval", 0, "optional G9G product-loop interval; disabled when 0")
fs.BoolVar(&f.printReadyLine, "t0-print-ready", false, "internal test-only: emit one structured JSON line on stdout after listener bound")
fs.SetOutput(os.Stderr)
if err := fs.Parse(args); err != nil {
@@ -95,6 +100,13 @@ func run(f flags) int {
fmt.Fprintln(os.Stderr, "blockmaster:", err)
return 1
}
if f.lifecyclePlacementSeed != "" {
if err := importLifecyclePlacementSeed(h, f.lifecyclePlacementSeed); err != nil {
fmt.Fprintln(os.Stderr, "blockmaster:", err)
_ = h.Close(context.Background())
return 1
}
}
if f.printReadyLine {
_ = json.NewEncoder(os.Stdout).Encode(readyLine{
@@ -105,6 +117,9 @@ func run(f flags) int {
}
h.Start()
if f.lifecycleLoop > 0 {
go runLifecycleProductLoop(h, f.lifecycleLoop)
}
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
@@ -118,3 +133,49 @@ func run(f flags) int {
}
return 0
}
func importLifecyclePlacementSeed(h *master.Host, path string) error {
stores := h.Lifecycle()
if stores == nil {
return fmt.Errorf("--lifecycle-placement-seed requires --lifecycle-store")
}
raw, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("read lifecycle placement seed %q: %w", path, err)
}
var intents []lifecycle.PlacementIntent
if err := json.Unmarshal(raw, &intents); err != nil {
return fmt.Errorf("parse lifecycle placement seed %q: %w", path, err)
}
for _, intent := range intents {
plan := lifecycle.PlacementPlan{
VolumeID: intent.VolumeID,
DesiredRF: intent.DesiredRF,
Candidates: make([]lifecycle.PlacementCandidate, 0, len(intent.Slots)),
}
for _, slot := range intent.Slots {
plan.Candidates = append(plan.Candidates, lifecycle.PlacementCandidate{
VolumeID: intent.VolumeID,
ServerID: slot.ServerID,
PoolID: slot.PoolID,
ReplicaID: slot.ReplicaID,
Source: slot.Source,
})
}
if _, err := stores.Placements.ApplyPlan(plan); err != nil {
return fmt.Errorf("apply lifecycle placement seed %s: %w", intent.VolumeID, err)
}
}
return nil
}
func runLifecycleProductLoop(h *master.Host, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
if _, err := h.RunLifecycleProductTick(); err != nil {
fmt.Fprintln(os.Stderr, "blockmaster: lifecycle product loop:", err)
}
<-ticker.C
}
}
@@ -14,3 +14,17 @@ func TestParseFlags_LifecycleStoreOptional(t *testing.T) {
t.Fatalf("lifecycleStore=%q want lifecycle-dir", f.lifecycleStore)
}
}
func TestParseFlags_LifecyclePlacementSeedOptional(t *testing.T) {
f, err := parseFlags([]string{
"--authority-store", "authority-dir",
"--lifecycle-store", "lifecycle-dir",
"--lifecycle-placement-seed", "seed.json",
})
if err != nil {
t.Fatalf("parseFlags: %v", err)
}
if f.lifecyclePlacementSeed != "seed.json" {
t.Fatalf("lifecyclePlacementSeed=%q want seed.json", f.lifecyclePlacementSeed)
}
}
@@ -0,0 +1,126 @@
package main_test
import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
func TestG9G_L2ProductLoopPublishesAssignmentToBlockvolume(t *testing.T) {
if testing.Short() {
t.Skip("L2 subprocess product-loop test; -short skip")
}
bins := buildG54Binaries(t)
art := t.TempDir()
lifecycleDir := filepath.Join(art, "lifecycle")
seedPath := writeG9GPlacementSeed(t, art)
_, masterAddr := startG9GMaster(t, bins, art, lifecycleDir, seedPath)
r2Data, r2Status := pickAddr(t), pickAddr(t)
r2Ctrl := pickAddr(t)
_ = startG54Volume(t, bins, art, volOpts{
masterAddr: masterAddr,
serverID: "s2", replicaID: "r2",
dataAddr: r2Data, ctrlAddr: r2Ctrl,
statusAddr: r2Status,
durableRoot: filepath.Join(art, "g9g-r2-store"),
logTag: "g9g-r2",
})
r2Ready := pollStatus(t, r2Status, 10*time.Second, func(b map[string]any) bool {
h, _ := b["Healthy"].(bool)
rid, _ := b["ReplicaID"].(string)
epoch, _ := b["Epoch"].(float64)
return h && rid == "r2" && epoch >= 1
})
if r2Ready == nil {
t.Fatal("r2: no status response after product-loop assignment")
}
if h, _ := r2Ready["Healthy"].(bool); !h {
t.Fatalf("r2 did not become Healthy from product-loop assignment; status=%v", r2Ready)
}
}
func writeG9GPlacementSeed(t *testing.T, art string) string {
t.Helper()
seedPath := filepath.Join(art, "g9g-placement-seed.json")
raw, err := json.MarshalIndent([]lifecycle.PlacementIntent{{
VolumeID: "v1",
DesiredRF: 1,
Slots: []lifecycle.PlacementSlotIntent{{
ServerID: "s2",
ReplicaID: "r2",
Source: lifecycle.PlacementSourceExistingReplica,
}},
}}, "", " ")
if err != nil {
t.Fatalf("marshal seed: %v", err)
}
if err := os.WriteFile(seedPath, raw, 0o644); err != nil {
t.Fatalf("write seed: %v", err)
}
return seedPath
}
func startG9GMaster(t *testing.T, bins l2bins, art, lifecycleDir, seedPath string) (*proc, string) {
t.Helper()
storeDir := filepath.Join(art, "master-store")
_ = os.MkdirAll(storeDir, 0o755)
topo := write2SlotTopology(t, art)
logPath := filepath.Join(art, "master-g9g.log")
lf, err := os.Create(logPath)
if err != nil {
t.Fatalf("master log: %v", err)
}
cmd := exec.Command(bins.master,
"--authority-store", storeDir,
"--lifecycle-store", lifecycleDir,
"--lifecycle-placement-seed", seedPath,
"--lifecycle-product-loop-interval", "100ms",
"--listen", "127.0.0.1:0",
"--topology", topo,
"--expected-slots-per-volume", "2",
"--freshness-window", "800ms",
"--pending-grace", "100ms",
"--t0-print-ready",
)
stdout, err := cmd.StdoutPipe()
if err != nil {
lf.Close()
t.Fatalf("master stdout pipe: %v", err)
}
cmd.Stderr = lf
if err := cmd.Start(); err != nil {
lf.Close()
t.Fatalf("master start: %v", err)
}
p := &proc{cmd: cmd, logPath: logPath}
t.Cleanup(func() { p.stop(t); lf.Close() })
buf := make([]byte, 512)
n, _ := stdout.Read(buf)
go func() {
for {
b := make([]byte, 1024)
if _, err := stdout.Read(b); err != nil {
return
}
}
}()
var rl struct {
Component, Phase, Addr string
}
if err := json.Unmarshal(buf[:n], &rl); err != nil {
t.Fatalf("parse master ready %q: %v", buf[:n], err)
}
if rl.Addr == "" {
t.Fatalf("master ready: empty addr (line=%q)", buf[:n])
}
return p, rl.Addr
}
+20 -6
View File
@@ -25,11 +25,11 @@ type TopologyController struct {
reader AuthorityBasisReader
queue *assignmentQueue
mu sync.Mutex
desired map[string]DesiredAssignment
unsupported map[string]UnsupportedEvidence
convergenceStuck map[string]*ConvergenceStuckEvidence
now func() time.Time
mu sync.Mutex
desired map[string]DesiredAssignment
unsupported map[string]UnsupportedEvidence
convergenceStuck map[string]*ConvergenceStuckEvidence
now func() time.Time
}
func NewTopologyController(config TopologyControllerConfig, reader AuthorityBasisReader) *TopologyController {
@@ -312,6 +312,17 @@ func (c *TopologyController) Next(ctx context.Context) (AssignmentAsk, error) {
return c.queue.next(ctx)
}
// SubmitAssignmentAsk appends a controller-verified ask to the publisher
// directive queue. It is intentionally still an ask-level seam: Publisher
// remains the only epoch / endpoint-version author.
func (c *TopologyController) SubmitAssignmentAsk(ask AssignmentAsk) error {
if err := validateAsk(ask); err != nil {
return err
}
c.queue.enqueue(ask)
return nil
}
// LastUnsupported returns the most recent unsupported evidence for
// one volume, if any.
func (c *TopologyController) LastUnsupported(volumeID string) (UnsupportedEvidence, bool) {
@@ -352,8 +363,11 @@ func (c *TopologyController) DesiredFor(volumeID string) (DesiredAssignment, boo
}
func (c *TopologyController) clearDesiredLocked(volumeID string) {
_, hadDesired := c.desired[volumeID]
delete(c.desired, volumeID)
c.queue.discard(volumeID)
if hadDesired {
c.queue.discard(volumeID)
}
// §10 clearing rule 1 / 2 / 3: whenever the desired clears
// (confirmed, superseded, supportability-driven), the stuck
// evidence clears with it. Supportability regaining does NOT
@@ -0,0 +1,58 @@
package master
// LifecycleProductTickResult summarizes one explicit product-loop tick.
type LifecycleProductTickResult struct {
VerifiedPlacements int
PublishedAsks int
SkippedCurrent int
SkippedUnverified int
}
// RunLifecycleProductTick drives the first G9G product loop:
// lifecycle facts -> verified placement -> AssignmentAsk -> controller
// directive queue. It never calls Publisher.apply; Publisher remains the only
// authority minter through its normal Run loop.
func (h *Host) RunLifecycleProductTick() (LifecycleProductTickResult, error) {
stores := h.Lifecycle()
if stores == nil {
return LifecycleProductTickResult{}, nil
}
nodes := stores.Nodes.ListNodes()
placements := stores.Placements.ListPlacements()
verified := h.verifyPlacements(placements, nodes)
result := LifecycleProductTickResult{
VerifiedPlacements: len(verified),
}
for _, placement := range verified {
if !placement.Verified {
result.SkippedUnverified++
continue
}
asks, err := assignmentRequestsFromVerifiedPlacement(placement)
if err != nil {
return result, err
}
for _, ask := range asks {
if h.assignmentAskAlreadyCurrent(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr) {
result.SkippedCurrent++
continue
}
if err := h.ctrl.SubmitAssignmentAsk(ask); err != nil {
return result, err
}
result.PublishedAsks++
}
}
return result, nil
}
func (h *Host) assignmentAskAlreadyCurrent(volumeID, replicaID, dataAddr, ctrlAddr string) bool {
line, ok := h.Publisher().VolumeAuthorityLine(volumeID)
if !ok {
return false
}
return line.Assigned &&
line.ReplicaID == replicaID &&
line.DataAddr == dataAddr &&
line.CtrlAddr == ctrlAddr
}
@@ -0,0 +1,138 @@
package master
import (
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
func TestG9G_ProductLoopPublishesVerifiedExistingReplica(t *testing.T) {
h := newTestMaster(t, t.TempDir())
defer closeTestMaster(t, h)
seedVerifiedExistingReplicaPlacement(t, h)
result, err := h.RunLifecycleProductTick()
if err != nil {
t.Fatalf("product tick: %v", err)
}
if result.PublishedAsks != 1 {
t.Fatalf("result=%+v want one published ask", result)
}
line := waitAuthorityLine(t, h.Publisher(), "vol-a")
if line.ReplicaID != "r2" || line.Epoch != 1 || line.EndpointVersion != 1 {
t.Fatalf("line=%+v want publisher-minted bind for r2", line)
}
}
func TestG9G_ProductLoopDoesNotPublishUnverifiedPlacement(t *testing.T) {
h := newTestMaster(t, t.TempDir())
defer closeTestMaster(t, h)
stores := h.Lifecycle()
if _, err := stores.Placements.ApplyPlan(lifecycle.PlacementPlan{
VolumeID: "vol-a",
DesiredRF: 1,
Candidates: []lifecycle.PlacementCandidate{{
VolumeID: "vol-a",
ServerID: "node-a",
ReplicaID: "r2",
Source: lifecycle.PlacementSourceExistingReplica,
}},
}); err != nil {
t.Fatalf("apply placement: %v", err)
}
result, err := h.RunLifecycleProductTick()
if err != nil {
t.Fatalf("product tick: %v", err)
}
if result.PublishedAsks != 0 {
t.Fatalf("result=%+v want no published ask", result)
}
if _, ok := h.Publisher().VolumeAuthorityLine("vol-a"); ok {
t.Fatal("unverified placement must not publish authority")
}
}
func TestG9G_ProductLoopIsIdempotentForSameAuthorityLine(t *testing.T) {
h := newTestMaster(t, t.TempDir())
defer closeTestMaster(t, h)
seedVerifiedExistingReplicaPlacement(t, h)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatalf("first product tick: %v", err)
}
first := waitAuthorityLine(t, h.Publisher(), "vol-a")
result, err := h.RunLifecycleProductTick()
if err != nil {
t.Fatalf("second product tick: %v", err)
}
if result.PublishedAsks != 0 {
t.Fatalf("second tick result=%+v want no duplicate ask", result)
}
second, ok := h.Publisher().VolumeAuthorityLine("vol-a")
if !ok {
t.Fatal("authority line disappeared")
}
if second.ReplicaID != first.ReplicaID || second.Epoch != first.Epoch || second.EndpointVersion != first.EndpointVersion {
t.Fatalf("line changed first=%+v second=%+v", first, second)
}
}
func TestG9G_BlockvolumeSubscriptionReceivesProductLoopAssignment(t *testing.T) {
h := newTestMaster(t, t.TempDir())
defer closeTestMaster(t, h)
seedVerifiedExistingReplicaPlacement(t, h)
ch, cancel := h.Publisher().Subscribe("vol-a", "r2")
defer cancel()
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatalf("product tick: %v", err)
}
got := recvAssignmentInfo(t, ch)
if got.VolumeID != "vol-a" || got.ReplicaID != "r2" || got.Epoch != 1 || got.EndpointVersion != 1 {
t.Fatalf("assignment=%+v want product-loop publisher bind", got)
}
}
func seedVerifiedExistingReplicaPlacement(t *testing.T, h *Host) {
t.Helper()
stores := h.Lifecycle()
if _, err := stores.Placements.ApplyPlan(lifecycle.PlacementPlan{
VolumeID: "vol-a",
DesiredRF: 1,
Candidates: []lifecycle.PlacementCandidate{{
VolumeID: "vol-a",
ServerID: "node-a",
ReplicaID: "r2",
Source: lifecycle.PlacementSourceExistingReplica,
}},
}); err != nil {
t.Fatalf("apply placement: %v", err)
}
if err := h.ObservationHost().Ingest(authority.Observation{
ServerID: "node-a",
ObservedAt: time.Now().UTC(),
Slots: []authority.SlotFact{{
VolumeID: "vol-a",
ReplicaID: "r2",
DataAddr: "127.0.0.1:9202",
CtrlAddr: "127.0.0.1:9102",
}},
}); err != nil {
t.Fatalf("ingest observation: %v", err)
}
}
func recvAssignmentInfo(t *testing.T, ch <-chan adapter.AssignmentInfo) adapter.AssignmentInfo {
t.Helper()
select {
case got := <-ch:
return got
case <-time.After(2 * time.Second):
t.Fatal("timeout waiting for assignment")
return adapter.AssignmentInfo{}
}
}