diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 80cc5f67ad..9b604371f0 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -44,7 +44,7 @@ var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) { func runOpsChunk(args []string, stdout, stderr io.Writer) int { if len(args) == 0 { - return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|volume-delete", false) + return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|volume-delete|restore", false) } switch args[0] { case "gc": @@ -69,6 +69,8 @@ func runOpsChunk(args []string, stdout, stderr io.Writer) int { return chunkRetain(args[1:], stdout, stderr) case "volume-delete": return chunkVolumeDelete(args[1:], stdout, stderr) + case "restore": + return chunkRestore(args[1:], stdout, stderr) default: return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, fmt.Sprintf("unknown subcommand %q", args[0]), false) } diff --git a/seaweed-block/cmd/sw-block/chunk_restore.go b/seaweed-block/cmd/sw-block/chunk_restore.go new file mode 100644 index 0000000000..4a94e2f456 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_restore.go @@ -0,0 +1,30 @@ +package main + +import ( + "io" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// chunkRestore starts (or joins) the independent-restore driver of a volume +// restored from a snapshot and prints its status; with --status it only +// prints the status. The driver runs in blockvolume and outlives this call. +func chunkRestore(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("restore", stderr) + var ( + volumeID, statusAddr string + statusOnly bool + ) + fs.StringVar(&volumeID, "volume", "", "restored volume id") + fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") + fs.BoolVar(&statusOnly, "status", false, "print the restore status without starting a run") + if err := fs.Parse(args); err != nil { + return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + if volumeID == "" || statusAddr == "" { + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false) + } + body := map[string]any{"volumeID": volumeID, "statusOnly": statusOnly} + return chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr) +} diff --git a/seaweed-block/cmd/sw-block/chunk_restore_test.go b/seaweed-block/cmd/sw-block/chunk_restore_test.go new file mode 100644 index 0000000000..2c9c32f1c2 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_restore_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestOpsChunk_RestoreStartsAndReportsStatus(t *testing.T) { + var got []map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/chunk/restore" || r.Method != http.MethodPost { + http.Error(w, "unexpected "+r.Method+" "+r.URL.Path, http.StatusNotFound) + return + } + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + got = append(got, body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"volumeID":"v2","phase":"owning","running":true,"foreign":3}`)) + })) + defer srv.Close() + for _, args := range [][]string{{"restore", "--volume", "v2", "--status-addr", srv.URL}, {"restore", "--volume", "v2", "--status-addr", srv.URL, "--status"}} { + var out, errb bytes.Buffer + if code := runOpsChunk(args, &out, &errb); code != 0 || !strings.Contains(out.String(), `"phase":"owning"`) { + t.Fatalf("%v: exit %d out %q err %q", args, code, out.String(), errb.String()) + } + } + if len(got) != 2 || got[0]["volumeID"] != "v2" || got[0]["statusOnly"] != false || got[1]["statusOnly"] != true { + t.Fatalf("requests %v: want a start, then a status-only call", got) + } + var out, errb bytes.Buffer + if code := runOpsChunk([]string{"restore", "--status-addr", srv.URL}, &out, &errb); code == 0 { + t.Fatal("restore without --volume must be refused") + } +} diff --git a/seaweed-block/core/frontend/durable/provider_restore.go b/seaweed-block/core/frontend/durable/provider_restore.go new file mode 100644 index 0000000000..fde0c680aa --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_restore.go @@ -0,0 +1,51 @@ +package durable + +import ( + "context" + "fmt" + + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// chunkRestorer is the chunk layer's independent-restore surface. +type chunkRestorer interface { + HydrateAllAt(ctx context.Context, bytesPerSecond int64) (storage.HydrateProgress, error) + OwnBatch(ctx context.Context, n int, foreign func(key string) bool) (storage.OwnProgress, error) +} + +func (p *DurableProvider) restorer(volumeID string) (chunkRestorer, error) { + _, layer, err := p.chunkHandle(volumeID) + if err != nil { + return nil, err + } + r, ok := layer.(chunkRestorer) + if !ok { + return nil, fmt.Errorf("durable: volume %s: chunk layer has no restore surface: %w", volumeID, ErrNotChunkVolume) + } + return r, nil +} + +// HydrateVolume makes every HEAD-named absent chunk of volumeID local +// (M6.Restore.Restoring>Hydrating), paced to bytesPerSecond, under the +// host limiter's BackgroundFill class. +func (p *DurableProvider) HydrateVolume(ctx context.Context, volumeID string, bytesPerSecond int64) (storage.HydrateProgress, error) { + r, err := p.restorer(volumeID) + if err != nil { + return storage.HydrateProgress{}, err + } + return r.HydrateAllAt(hostlimit.WithClass(ctx, hostlimit.BackgroundFill), bytesPerSecond) +} + +// OwnVolumeBatch runs one bounded cut of volumeID that re-uploads up to n +// local chunks with foreign HEAD keys under own keys +// (M6.Restore.Owning>Owning). +func (p *DurableProvider) OwnVolumeBatch(ctx context.Context, volumeID string, n int, foreign func(string) bool) (storage.OwnProgress, error) { + r, err := p.restorer(volumeID) + if err != nil { + return storage.OwnProgress{}, err + } + ctx, cancel := p.chunkCutContext(ctx) + defer cancel() + return r.OwnBatch(ctx, n, foreign) +} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index c1e4029609..ab9dfb6499 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -231,6 +231,7 @@ func (s *StatusServer) chunkMux() http.Handler { mux.HandleFunc("/chunk/snapshots", s.handleChunkSnapshots) mux.HandleFunc("/chunk/snapshot/delete", s.handleChunkSnapshotDelete) mux.HandleFunc("/chunk/detach", s.handleChunkDetach) + mux.HandleFunc("/chunk/restore", s.handleChunkRestore) // Any other /chunk path: a typed JSON 404, like every other /chunk // error, not net/http's plain-text page. mux.HandleFunc("/chunk/", func(w http.ResponseWriter, r *http.Request) { @@ -589,8 +590,9 @@ type ChunkProvider interface { var errFrozenDetachUnsupported = errors.New("frozen detach unsupported by provider") type chunkControl struct { - p ChunkProvider - cat *chunkstore.Catalog + p ChunkProvider + cat *chunkstore.Catalog + restores restoreRuns } // NewChunkControl serves the routes from a durable provider (cut, detach) diff --git a/seaweed-block/core/host/volume/chunk_restore.go b/seaweed-block/core/host/volume/chunk_restore.go new file mode 100644 index 0000000000..eb334788df --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_restore.go @@ -0,0 +1,234 @@ +package volume + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "sync" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Independent restore driver (M6.Restore). A restored volume serves at once; +// the driver then makes every chunk local (Restoring>Hydrating), re-uploads +// the chunks whose HEAD keys name another volume under the volume's own keys +// in bounded batch cuts (Hydrating>Owning, Owning>Owning; the walker and the +// batches may overlap), and writes the independence marker once HEAD holds +// no foreign ref (Owning>Independent). Every decision is read from the +// target's own facts (its VOLUME, HEAD and marker), never from the source, so +// a rerun after a crash resumes where the remote state is, and a deleted +// source snapshot or volume is a normal state. + +// Restore quantities (invariants.md Part E). +const ( + DefaultRestoreBatchChunks = 64 + DefaultRestoreBytesPerSecond = 64 << 20 +) + +// RestoreProvider is the chunk layer's restore surface for an attached volume. +type RestoreProvider interface { + HydrateVolume(ctx context.Context, volumeID string, bytesPerSecond int64) (storage.HydrateProgress, error) + OwnVolumeBatch(ctx context.Context, volumeID string, n int, foreign func(string) bool) (storage.OwnProgress, error) +} + +// RestoreConfig bounds one restore run; zero fields take the defaults. +type RestoreConfig struct { + BatchChunks int + BytesPerSecond int64 +} + +// Restore phases. +const ( + RestoreHydrating = "hydrating" + RestoreOwning = "owning" + RestoreIndependent = "independent" + RestoreFailed = "failed" +) + +// RestoreStatus is the body of /chunk/restore. +type RestoreStatus struct { + VolumeID string `json:"volumeID"` + Phase string `json:"phase"` + Running bool `json:"running"` + Filled int `json:"filled"` // chunks the walker made local + Owned int `json:"owned"` // chunks re-uploaded under own keys + Foreign int `json:"foreign"` // HEAD chunks still naming another volume + NotLocal int `json:"notLocal"` // of those, not local yet + Batches int `json:"batches"` // batch cuts run + MarkedGen uint64 `json:"markedGen"` // HEAD gen the marker names (independent) + ErrorCode string `json:"errorCode,omitempty"` + ErrorText string `json:"error,omitempty"` +} + +// foreignKey reports whether key names another volume's object: an +// owner-qualified key whose owner is not vol. +func foreignKey(vol string) func(string) bool { + own := "@" + vol + "/" + return func(key string) bool { return strings.HasPrefix(key, "@") && !strings.HasPrefix(key, own) } +} + +var ( + errRestoreStuck = errors.New("restore: foreign chunks remain but none is local and the walker fills none") + errNotRestore = errors.New("restore: not a restore") +) + +// runRestore drives one restore of vol to independence, reporting progress. +func runRestore(ctx context.Context, cat *chunkstore.Catalog, p RestoreProvider, vol string, cfg RestoreConfig, report func(RestoreStatus)) (RestoreStatus, error) { + if cfg.BatchChunks <= 0 { + cfg.BatchChunks = DefaultRestoreBatchChunks + } + if cfg.BytesPerSecond <= 0 { + cfg.BytesPerSecond = DefaultRestoreBytesPerSecond + } + st := RestoreStatus{VolumeID: vol, Phase: RestoreHydrating, Running: true} + if m, ok, err := cat.ReadIndependence(ctx, vol); err != nil { + return st, err + } else if ok { + st.Phase, st.MarkedGen = RestoreIndependent, m.HeadGen + return st, nil + } + v, ok, err := cat.ReadVolume(ctx, vol) + if err != nil { + return st, err + } + if !ok || v.Origin != chunkstore.OriginRestore { + return st, fmt.Errorf("volume %s was not made by restore: %w", vol, errNotRestore) + } + foreign := foreignKey(vol) + for stalls := 0; ; { + h, err := p.HydrateVolume(ctx, vol, cfg.BytesPerSecond) + st.Filled += h.Filled + report(st) + if err != nil { + return st, err + } + st.Phase = RestoreOwning + progressed := h.Filled > 0 + for { + o, err := p.OwnVolumeBatch(ctx, vol, cfg.BatchChunks, foreign) + st.Owned, st.Foreign, st.NotLocal = st.Owned+o.Owned, o.Remaining, o.NotLocal + if o.Owned > 0 { + st.Batches++ + progressed = true + } + report(st) + if err != nil { + return st, err + } + if o.Remaining == 0 { + m, err := cat.MarkIndependent(ctx, vol) + if err != nil { + return st, err + } + st.Phase, st.MarkedGen, st.Running = RestoreIndependent, m.HeadGen, false + report(st) + return st, nil + } + if o.Owned == 0 { + break // what is left is not local: walk again + } + } + if !progressed { + if stalls++; stalls > 2 { + return st, errRestoreStuck + } + } else { + stalls = 0 + } + } +} + +// restoreRuns holds at most one running restore per volume and the last +// status of each. +type restoreRuns struct { + mu sync.Mutex + runs map[string]*RestoreStatus +} + +// Restore reports vol's restore status and, with start, starts a run unless +// one is running (POST /chunk/restore). A run outlives the request; it ends +// independent, or failed with the error (a later start resumes from the +// target's remote facts). +func (c *chunkControl) Restore(ctx context.Context, vol string, start bool) (RestoreStatus, error) { + p, ok := c.p.(RestoreProvider) + if !ok { + return RestoreStatus{}, fmt.Errorf("restore: provider has no restore surface: %w", errNotRestore) + } + c.restores.mu.Lock() + defer c.restores.mu.Unlock() + if c.restores.runs == nil { + c.restores.runs = map[string]*RestoreStatus{} + } + cur := c.restores.runs[vol] + if cur != nil && (cur.Running || !start) { + return *cur, nil + } + if !start { + return RestoreStatus{VolumeID: vol}, nil + } + st := &RestoreStatus{VolumeID: vol, Phase: RestoreHydrating, Running: true} + c.restores.runs[vol] = st + report := func(s RestoreStatus) { + c.restores.mu.Lock() + *st = s + c.restores.mu.Unlock() + } + go func() { + final, err := runRestore(context.Background(), c.cat, p, vol, RestoreConfig{}, report) + final.Running = false + if err != nil { + _, code, _ := chunkErrorCode(err) + final.Phase, final.ErrorCode, final.ErrorText = RestoreFailed, code, err.Error() + } + report(final) + }() + return *st, nil +} + +// handleChunkRestore serves GET /chunk/restore?volume=V (status) and +// POST /chunk/restore {"volumeID": V} (start or join a run; with +// "statusOnly": true, status only). Both answer 200 with the status. +func (s *StatusServer) handleChunkRestore(w http.ResponseWriter, r *http.Request) { + method := http.MethodGet + if r.Method == http.MethodPost { + method = http.MethodPost + } + if !s.chunkAdmit(w, r, method) { + return + } + vol := r.URL.Query().Get("volume") + if method == http.MethodPost { + var req struct { + VolumeID string `json:"volumeID"` + StatusOnly bool `json:"statusOnly"` + TimeoutMs int64 `json:"timeoutMs"` + } + if !decodeChunkBody(w, r, &req) { + return + } + vol = req.VolumeID + if req.StatusOnly { + method = http.MethodGet + } + } + ctl := s.chunkTarget(w, vol) + if ctl == nil { + return + } + rc, ok := ctl.(interface { + Restore(context.Context, string, bool) (RestoreStatus, error) + }) + if !ok { + writeChunkErr(w, http.StatusNotFound, codeNotFound, false, "restore is not served here") + return + } + st, err := rc.Restore(r.Context(), vol, method == http.MethodPost) + if err != nil { + writeChunkFailure(w, err) + return + } + writeChunkJSON(w, http.StatusOK, st) +} diff --git a/seaweed-block/core/host/volume/chunk_restore_test.go b/seaweed-block/core/host/volume/chunk_restore_test.go new file mode 100644 index 0000000000..b4eebd880c --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_restore_test.go @@ -0,0 +1,287 @@ +package volume + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "path" + "sort" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const restoreBase = "/swblock/chunks" + +var restoreGeo = chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} + +// sourceReadGuard fails every catalog read of the source volume's own +// entries (VOLUME, HEAD, snapshots) once armed; chunk bindings stay readable +// (hydration reads the source's chunks through T's qualified refs). +type sourceReadGuard struct { + *adapterManifestFiler + armed bool + reads []string +} + +func (g *sourceReadGuard) denied(dir string) bool { + src := path.Join(restoreBase, "v1") + return g.armed && (dir == src || strings.HasPrefix(dir, src+"/snap")) +} + +func (g *sourceReadGuard) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if g.denied(dir) { + g.reads = append(g.reads, path.Join(dir, name)) + return nil, errors.New("test: the restore driver read the source") + } + return g.adapterManifestFiler.LookupEntry(ctx, dir, name) +} + +func (g *sourceReadGuard) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { + if g.denied(dir) { + g.reads = append(g.reads, dir) + return nil, errors.New("test: the restore driver listed the source") + } + return g.adapterManifestFiler.ListEntries(ctx, dir, prefix, after, limit) +} + +// fakeRestoreProvider stands in for the chunk layer: the walk makes every +// chunk local, and a batch is one HEAD CAS replacing up to n foreign keys. +type fakeRestoreProvider struct { + r *chunkstore.ChunkRemote + local bool + hydrations int + batches int + failAtBatch int // a batch with this 1-based number fails (0: never) +} + +func (p *fakeRestoreProvider) HydrateVolume(ctx context.Context, vol string, bps int64) (storage.HydrateProgress, error) { + p.hydrations++ + if bps != DefaultRestoreBytesPerSecond { + return storage.HydrateProgress{}, fmt.Errorf("walker pace %d, want the default %d", bps, DefaultRestoreBytesPerSecond) + } + if p.local { + return storage.HydrateProgress{}, nil + } + h, err := p.r.GetHead(ctx) + if err != nil { + return storage.HydrateProgress{}, err + } + p.local = true + return storage.HydrateProgress{Filled: len(h.Chunks)}, nil +} + +func (p *fakeRestoreProvider) OwnVolumeBatch(ctx context.Context, vol string, n int, foreign func(string) bool) (storage.OwnProgress, error) { + h, err := p.r.GetHead(ctx) + if err != nil { + return storage.OwnProgress{}, err + } + var todo []uint64 + for idx, ref := range h.Chunks { + if foreign(ref.Key) { + todo = append(todo, idx) + } + } + sort.Slice(todo, func(i, j int) bool { return todo[i] < todo[j] }) + if !p.local || len(todo) == 0 { + nl := 0 + if !p.local { + nl = len(todo) + } + return storage.OwnProgress{Remaining: len(todo), NotLocal: nl}, nil + } + p.batches++ + if p.batches == p.failAtBatch { + return storage.OwnProgress{Remaining: len(todo)}, errors.New("test: batch cut failed") + } + next := storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}} + for idx, ref := range h.Chunks { + next.Chunks[idx] = ref + } + owned := 0 + for _, idx := range todo { + if owned == n { + break + } + data, err := p.r.Get(ctx, h.Chunks[idx].Key) + if err != nil { + return storage.OwnProgress{}, err + } + key := fmt.Sprintf("chunks/e3/c%d/b%d", idx, p.batches) + if err := p.r.Put(ctx, key, data); err != nil { + return storage.OwnProgress{}, err + } + next.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + owned++ + } + next, intents, err := p.r.PrepareManifest(ctx, h, next, uint64(restoreGeo.BlockSize)*uint64(restoreGeo.ChunkBlocks)) + if err != nil { + return storage.OwnProgress{}, err + } + if _, err := p.r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next); err != nil { + return storage.OwnProgress{}, err + } + for _, id := range intents { + _ = p.r.DeleteIntent(ctx, id) + } + return storage.OwnProgress{Owned: owned, Remaining: len(todo) - owned}, nil +} + +// restoreFixtureHost publishes source v1 (chunks), snapshots it and restores +// it into v2; it returns the guard filer, the catalog and v2's provider. +func restoreFixtureHost(t *testing.T, chunks int) (*sourceReadGuard, *chunkstore.Catalog, *fakeRestoreProvider) { + t.Helper() + ctx := context.Background() + f := &sourceReadGuard{adapterManifestFiler: &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}}} + cat, err := chunkstore.NewCatalog(f, restoreBase) + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(ctx, "v1", restoreGeo); err != nil { + t.Fatal(err) + } + r1, err := chunkstore.NewChunkRemote(f, f, path.Join(restoreBase, "v1")) + if err != nil { + t.Fatal(err) + } + cur, err := r1.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}} + for idx := 0; idx < chunks; idx++ { + data := make([]byte, int(restoreGeo.BlockSize)*int(restoreGeo.ChunkBlocks)) + data[0] = byte(0x60 + idx) + key := fmt.Sprintf("chunks/e1/c%d/k", idx) + if err := r1.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + h.Chunks[uint64(idx)] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + h, intents, err := r1.PrepareManifest(ctx, cur, h, uint64(restoreGeo.BlockSize)*uint64(restoreGeo.ChunkBlocks)) + if err != nil { + t.Fatal(err) + } + if h.Gen, err = r1.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil { + t.Fatal(err) + } + for _, id := range intents { + _ = r1.DeleteIntent(ctx, id) + } + if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if _, err := cat.Restore(ctx, chunkstore.ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs"}); err != nil { + t.Fatal(err) + } + r2, err := chunkstore.NewChunkRemote(f, f, path.Join(restoreBase, "v2")) + if err != nil { + t.Fatal(err) + } + return f, cat, &fakeRestoreProvider{r: r2} +} + +func noReport(RestoreStatus) {} + +// The driver walks, cuts bounded batches until no foreign ref is left and +// writes the marker, reading only the target's facts (Restoring>Hydrating> +// Owning>Owning>Independent). +func TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly(t *testing.T) { + f, cat, p := restoreFixtureHost(t, 5) + f.armed = true // from here, any read of the source's catalog entries fails + ctx := context.Background() + st, err := runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err != nil { + t.Fatalf("restore: %+v %v (source reads %v)", st, err, f.reads) + } + if len(f.reads) != 0 { + t.Fatalf("the driver read the source: %v", f.reads) + } + if st.Phase != RestoreIndependent || st.Owned != 5 || st.Foreign != 0 || st.Batches != 3 || st.Filled != 5 { + t.Fatalf("status %+v, want independent after 3 batches of at most 2", st) + } + m, ok, err := cat.ReadIndependence(ctx, "v2") + if err != nil || !ok || m.HeadGen != st.MarkedGen { + t.Fatalf("marker: %+v ok=%v %v", m, ok, err) + } + again, err := runRestore(ctx, cat, p, "v2", RestoreConfig{}, noReport) + if err != nil || again.Phase != RestoreIndependent || p.batches != 3 { + t.Fatalf("a rerun of an independent restore must do nothing: %+v %v", again, err) + } +} + +// A failed batch leaves HEAD as it was; the next run resumes from the +// target's HEAD and finishes. +func TestRestoreDriver_ResumesAfterAFailedBatch(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 5) + ctx := context.Background() + p.failAtBatch = 2 + st, err := runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err == nil || st.Owned != 2 || st.Foreign != 3 { + t.Fatalf("first run: %+v %v, want the failure after 2 owned", st, err) + } + if _, ok, _ := cat.ReadIndependence(ctx, "v2"); ok { + t.Fatal("marker written with foreign refs left") + } + p.failAtBatch = 0 + st, err = runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err != nil || st.Phase != RestoreIndependent || st.Owned != 3 { + t.Fatalf("resumed run: %+v %v, want the 3 left owned and the marker", st, err) + } +} + +// Only a restore volume is driven. +func TestRestoreDriver_RefusesAVolumeNotMadeByRestore(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 1) + if _, err := runRestore(context.Background(), cat, p, "v1", RestoreConfig{}, noReport); !errors.Is(err, errNotRestore) { + t.Fatalf("driving the source volume: %v, want not a restore", err) + } +} + +// POST /chunk/restore starts one background run; GET reports it. +func TestRestoreDriver_ChunkControlStartsOneRunAndReportsIt(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 3) + ctl := &chunkControl{p: restoreOnlyProvider{p}, cat: cat} + ctx := context.Background() + if st, err := ctl.Restore(ctx, "v2", false); err != nil || st.Phase != "" { + t.Fatalf("status before any run: %+v %v", st, err) + } + if _, err := ctl.Restore(ctx, "v2", true); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(5 * time.Second) + for { + st, err := ctl.Restore(ctx, "v2", false) + if err != nil { + t.Fatal(err) + } + if !st.Running { + if st.Phase != RestoreIndependent || st.Owned != 3 { + t.Fatalf("final status %+v", st) + } + break + } + if time.Now().After(deadline) { + t.Fatalf("restore still running: %+v", st) + } + time.Sleep(time.Millisecond) + } +} + +// restoreOnlyProvider is a ChunkProvider whose cut and detach are unused. +type restoreOnlyProvider struct{ *fakeRestoreProvider } + +func (restoreOnlyProvider) CutVolume(context.Context, string, uint64) (storage.ChunkCutResult, error) { + return storage.ChunkCutResult{}, errors.New("unused") +} +func (restoreOnlyProvider) DetachVolume(context.Context, string) (storage.ChunkCutResult, uint64, error) { + return storage.ChunkCutResult{}, 0, errors.New("unused") +} + +var _ RestoreProvider = (*durable.DurableProvider)(nil) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 480573c503..c537e968ec 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -243,13 +243,15 @@ stateDiagram-v2 [*] --> Claimed: claim parent snapshot, write VOLUME (origin restore) Claimed --> Restoring: first HEAD (parent's refs, owner-qualified); claim dropped Claimed --> Aborted: GC tombstones the HEAD (parent kept as fork_parent) - Restoring --> Restoring: walker fills; batch cut replaces foreign refs with own keys - Restoring --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created + Restoring --> Hydrating: driver starts the paced walker + Hydrating --> Owning: batch cuts start (the walker may still run) + Owning --> Owning: one bounded batch cut replaces up to N foreign refs with own keys + Owning --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created Independent --> [*] Aborted --> [*]: target deleted ``` -Snapshots of the target are refused in `Claimed` and `Restoring`. +Snapshots of the target are refused until `Independent`. The driver (`core/host/volume/chunk_restore.go`) runs these steps from the target's own facts; `POST /chunk/restore` starts it and `sw-block ops chunk restore` calls it. ### Attached-volume scheduling diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ba83dc3ba6..e94549d468 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -293,7 +293,10 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001` | | published | restore | the fork steps with `VOLUME` origin `restore`: the claim is live until the target has a HEAD (the fork's semantics); after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-RESTORE-PARENT-HOLD-001` | -| restore | independent | the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs` | `INV-RESTORE-INDEPENDENT-001` | +| restore (Restoring) | Hydrating | M6.Restore.Restoring>Hydrating: the driver starts the walker, paced at a byte rate under the BackgroundFill class | `core/host/volume/chunk_restore.go` `runRestore`; `core/frontend/durable/provider_restore.go` `HydrateVolume`; `core/storage/chunk_hydrate_all.go` `HydrateAllAt` | `INV-RESTORE-HYDRATE-001`, `INV-RESTORE-DRIVER-001` | +| restore (Hydrating) | Owning | M6.Restore.Hydrating>Owning: batch cuts start once chunks are local; the walker and the batches may overlap | `core/host/volume/chunk_restore.go` `runRestore` | `INV-RESTORE-DRIVER-001` | +| restore (Owning) | Owning | M6.Restore.Owning>Owning: one bounded batch cut re-uploads at most N local chunks with foreign keys under own keys (one intent, one HEAD CAS); absent chunks wait for the walker | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `INV-RESTORE-OWN-BATCH-001` | +| restore (Owning) | Independent | M6.Restore.Owning>Independent: the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs`; `core/host/volume/chunk_restore.go` `runRestore` | `INV-RESTORE-INDEPENDENT-001`, `INV-RESTORE-DRIVER-001` | | restore (not independent) | name held | refused: `CreateSnapshot` on a restore volume needs the marker, and the supplied image itself must hold no foreign ref; a refused request leaves no name or attempt | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-RESTORE-SNAPSHOT-001` | **Intents and key bindings.** @@ -382,7 +385,7 @@ with a separate scope/config-bound mark. Incomplete marks carry no coverage. ## Part B. Invariant ledger -135 rows: 116 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 120 new. +137 rows: 118 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 122 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -576,11 +579,14 @@ Notes: | `INV-RESTORE-INDEPENDENT-001` | `RESTORE-INDEPENDENT` is written once, only for a restore volume with a live HEAD whose resolved image holds no ref owned by another volume; a restore without a live HEAD (absent or aborted) never attaches and is never marked. | M6 snapshot: restore → independent | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestRestore_MarkIndependentOnlyWithoutQualifiedRefs`, `TestRestore_WithoutLiveHeadNeverAttaches`, `TestRestore_SourceGoneIsNormal` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent`, `NoForeignList` | ACTIVE | | `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`red_snap_during_restore`) | ACTIVE | | `INV-RESTORE-PARENT-HOLD-001` | A restore target with an aborted first HEAD no longer has a live fork claim (any HEAD ends the claim), but retention still keeps the parent snapshot as `fork_parent` (the fork-record scan treats an aborted HEAD as no HEAD) until the target volume is deleted. | M6 snapshot: published (parent of an aborted restore) | `core/frontend/chunkstore/retention.go` `liveClaims`, `forkParentsNeeded` | `TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted` (`core/frontend/chunkstore/restore_test.go`) | — (Go only: the model's `ClaimUntilHead` does not cover retention of an aborted target) | ACTIVE | -| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | +| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `HydrateAllAt`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld`, `TestHydrateAll_PacedByByteRate` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | +| `INV-RESTORE-OWN-BATCH-001` | A batch cut re-uploads at most N local chunks whose HEAD keys name another volume under new own keys, even when their bytes equal HEAD's, in one ordinary cut (one intent, one HEAD CAS); it never fetches an absent chunk. | M6.Restore.Owning>Owning | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`, `TestOwnBatch_SkipsChunksNotLocal`, `TestOwnBatch_CarriesGuestWrites` (`core/storage/chunk_own_test.go`) | `RestoreIndependence` `NoGap` | ACTIVE | +| `INV-RESTORE-DRIVER-001` | The restore driver decides only from the target's VOLUME, HEAD and marker (never the source), writes the marker only after a batch leaves no foreign ref, and a rerun resumes from the target's remote state. | M6.Restore (all transitions) | `core/host/volume/chunk_restore.go` `runRestore`, `chunkControl.Restore` | `TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly`, `TestRestoreDriver_ResumesAfterAFailedBatch`, `TestRestoreDriver_RefusesAVolumeNotMadeByRestore` (`core/host/volume/chunk_restore_test.go`) | `RestoreIndependence` `Independent`, `StateRemote` | ACTIVE | | `INV-CAT-INTENT-DROP-BOUNDED-001` | Dropping an operation's intent outlives the caller's cancellation (cleanup after a refused or cancelled request) but is bounded by `dropIntentTimeout`; a failed or timed-out delete leaves the intent, which only over-protects. | M6 intent: Live → Removed | `core/frontend/chunkstore/catalog.go` `dropIntent` | `TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled` (`core/frontend/chunkstore/restore_test.go`) | — | ACTIVE | Notes: +- Restore quantities: batch size N = `DefaultRestoreBatchChunks` (64 chunks per batch cut) and the walker pace = `DefaultRestoreBytesPerSecond` (64 MiB/s, plus the host limiter's BackgroundFill class), both in `core/host/volume/chunk_restore.go`. They move to the quantity table when it exists. ### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing