diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go new file mode 100644 index 0000000000..ecd491f0c0 --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -0,0 +1,499 @@ +package volume + +// /chunk/*: the walstore-chunk control routes on the status listener +// (B9 W2 spec §2.1-§2.2, §3.1-§3.4, §3.6). They are off by default +// (EnableChunkControlEndpoint, flag --chunk-control-endpoint), share the +// listener's loopback rule, take JSON request bodies (POST) or a +// ?volume= query (GET), and answer failures with a typed JSON body +// {"code","message","retryable"}. + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strconv" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// ChunkControl is what the /chunk/* routes call for the served volume. +type ChunkControl interface { + // Cut takes one quiesced cut; with minLSN > 0 it fails unless the cut + // reaches minLSN (MakeRemoteDurable's contract). + Cut(ctx context.Context, volumeID string, minLSN uint64) (ChunkCutResponse, error) + Snapshot(ctx context.Context, volumeID string, req ChunkSnapshotRequest) (chunkstore.SnapshotInfo, error) + ListSnapshots(ctx context.Context, volumeID string, opts chunkstore.ListOptions) ([]chunkstore.SnapshotInfo, string, error) + DeleteSnapshot(ctx context.Context, volumeID, name string) (string, error) + Detach(ctx context.Context, volumeID string) (ChunkDetachResponse, error) +} + +// ChunkCutResponse is the body of a successful POST /chunk/cut (§3.1). +type ChunkCutResponse struct { + VolumeID string `json:"volumeID"` + CutLSN uint64 `json:"cutLSN"` + HeadGen uint64 `json:"headGen"` + HeadEpoch uint64 `json:"headEpoch"` + Holder string `json:"holder"` + Noop bool `json:"noop"` + FullHash bool `json:"fullHash"` + CandidateChunks int `json:"candidateChunks"` + UploadedChunks int `json:"uploadedChunks"` + UploadedBytes int64 `json:"uploadedBytes"` + ZeroedChunks int `json:"zeroedChunks"` + BarrierPauseNs int64 `json:"barrierPauseNs"` + UploadNs int64 `json:"uploadNs"` + CasNs int64 `json:"casNs"` + TotalNs int64 `json:"totalNs"` +} + +// ChunkSnapshotRequest is POST /chunk/snapshot's request (§3.2), without +// the volume and the timeout. +type ChunkSnapshotRequest struct { + Name string + RequestID string + Labels map[string]string + Consistency string + ExpiresAtNs int64 +} + +// ChunkDetachResponse is the body of a successful POST /chunk/detach (§3.6). +type ChunkDetachResponse struct { + VolumeID string `json:"volumeID"` + CutLSN uint64 `json:"cutLSN"` + HeadGen uint64 `json:"headGen"` + HeadEpoch uint64 `json:"headEpoch"` + LastWrittenLSN uint64 `json:"lastWrittenLSN"` +} + +// snapshotBody is POST /chunk/snapshot's success body, exactly §3.2's fields. +type snapshotBody struct { + VolumeID string `json:"volumeID"` + Name string `json:"name"` + HeadGen uint64 `json:"headGen"` + HeadEpoch uint64 `json:"headEpoch"` + CutLSN uint64 `json:"cutLSN"` + CreatedNs int64 `json:"createdNs"` + ChunkCount int `json:"chunkCount"` + ManifestBytes int `json:"manifestBytes"` + Consistency string `json:"consistency"` + Labels map[string]string `json:"labels"` + Replayed bool `json:"replayed"` +} + +// snapshotItem is one entry of GET /chunk/snapshots, exactly §3.3's fields. +type snapshotItem struct { + Name string `json:"name"` + HeadGen uint64 `json:"headGen"` + HeadEpoch uint64 `json:"headEpoch"` + CutLSN uint64 `json:"cutLSN"` + CreatedNs int64 `json:"createdNs"` + State string `json:"state"` + ChunkCount int `json:"chunkCount"` + Labels map[string]string `json:"labels"` + Consistency string `json:"consistency"` + Parent *chunkstore.Parent `json:"parent"` +} + +type snapshotsBody struct { + VolumeID string `json:"volumeID"` + Snapshots []snapshotItem `json:"snapshots"` + Next string `json:"next"` +} + +type snapshotDeleteBody struct { + VolumeID string `json:"volumeID"` + Name string `json:"name"` + State string `json:"state"` +} + +type chunkErrorBody struct { + Code string `json:"code"` + Message string `json:"message"` + Retryable bool `json:"retryable"` +} + +// The codes the routes add to the catalog's (B9 §2.2 plus the 2026-11-15 +// rulings: awaiting_assignment, internal). +const ( + codeVolumeNotServed = "volume_not_served" + codeNotPrimary = "not_primary" + codeAwaitingAssignment = "awaiting_assignment" + codeEpochStale = "epoch_stale" + codeBaseInstalling = "base_installing" + codeFenced = "fenced" + codeHeadConflict = "head_conflict" + codeClosing = "closing" + codeInternal = "internal" +) + +const chunkBodyLimit = 64 << 10 + +// EnableChunkControlEndpoint mounts the /chunk/* routes. Must be called +// BEFORE Start; the routes answer not_chunk_volume until SetChunkControl. +func (s *StatusServer) EnableChunkControlEndpoint() { + s.mu.Lock() + defer s.mu.Unlock() + s.chunkEnabled = true +} + +// SetChunkControl wires the routes to the volume's chunk control. It may be +// called before or after Start (blockvolume binds the listener before the +// durable provider exists). +func (s *StatusServer) SetChunkControl(c ChunkControl) { + s.mu.Lock() + defer s.mu.Unlock() + s.chunkControl = c +} + +func (s *StatusServer) chunkMux() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("/chunk/cut", s.handleChunkCut) + mux.HandleFunc("/chunk/snapshot", s.handleChunkSnapshot) + mux.HandleFunc("/chunk/snapshots", s.handleChunkSnapshots) + mux.HandleFunc("/chunk/snapshot/delete", s.handleChunkSnapshotDelete) + mux.HandleFunc("/chunk/detach", s.handleChunkDetach) + return mux +} + +func writeChunkJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} + +func writeChunkErr(w http.ResponseWriter, status int, code string, retryable bool, format string, a ...any) { + writeChunkJSON(w, status, chunkErrorBody{Code: code, Message: fmt.Sprintf(format, a...), Retryable: retryable}) +} + +// writeChunkFailure answers err with its B9 code and HTTP status. +func writeChunkFailure(w http.ResponseWriter, err error) { + status, code, retryable := chunkErrorCode(err) + writeChunkJSON(w, status, chunkErrorBody{Code: code, Message: err.Error(), Retryable: retryable}) +} + +// chunkErrorCode maps an operation's error to (HTTP status, code, +// retryable). The most specific cause wins: a refused capture reports why +// it was refused, an unresolved CAS reports outcome_unknown even when the +// re-read failed on the remote. +func chunkErrorCode(err error) (int, string, bool) { + var ce *chunkstore.CatalogError + switch { + case errors.As(err, &ce): + return catalogStatus(ce.Code), ce.Code, ce.Retryable + case errors.Is(err, storage.ErrChunkLayerFenced): + return http.StatusConflict, codeFenced, false + case errors.Is(err, durable.ErrChunkAwaitingAuthority): + return http.StatusConflict, codeAwaitingAssignment, true + case errors.Is(err, durable.ErrChunkNotPrimary): + return http.StatusConflict, codeNotPrimary, false + case errors.Is(err, durable.ErrChunkEpochStale): + return http.StatusConflict, codeEpochStale, false + case errors.Is(err, storage.ErrChunkBaseInstalling): + return http.StatusConflict, codeBaseInstalling, true + case errors.Is(err, storage.ErrChunkCASOutcomeUnknown): + return http.StatusServiceUnavailable, chunkstore.CodeOutcomeUnknown, true + case errors.Is(err, storage.ErrChunkHeadPrecondition): + return http.StatusConflict, codeHeadConflict, true + case errors.Is(err, storage.ErrChunkRemoteUnavailable): + return http.StatusServiceUnavailable, chunkstore.CodeRemoteUnavailable, true + case errors.Is(err, storage.ErrChunkLayerClosed), errors.Is(err, storage.ErrChunkLayerDetached): + return http.StatusServiceUnavailable, codeClosing, false + case errors.Is(err, durable.ErrNotChunkVolume), errors.Is(err, durable.ErrVolumeNotOpen): + return http.StatusConflict, chunkstore.CodeNotChunkVolume, false + case errors.Is(err, context.DeadlineExceeded): + return http.StatusServiceUnavailable, chunkstore.CodeDeadlineExceeded, true + default: + return http.StatusInternalServerError, codeInternal, false + } +} + +func catalogStatus(code string) int { + switch code { + case chunkstore.CodeInvalidName: + return http.StatusBadRequest + case chunkstore.CodeSnapshotNotFound: + return http.StatusNotFound + case chunkstore.CodeDeadlineExceeded, chunkstore.CodeRemoteUnavailable, chunkstore.CodeOutcomeUnknown: + return http.StatusServiceUnavailable + default: // snapshot_exists, snapshot_deleting, target_exists, geometry_mismatch, fork_incomplete, not_chunk_volume + return http.StatusConflict + } +} + +// chunkAdmit runs the transport checks every route shares: method, then +// client. Like a malformed request, these are answered in plain text as +// on the rest of the listener; the typed JSON body is for the operation's +// own outcome (B9 §2.2 has no codes for them). +func (s *StatusServer) chunkAdmit(w http.ResponseWriter, r *http.Request, method string) bool { + if r.Method != method { + w.Header().Set("Allow", method) + http.Error(w, r.URL.Path+" requires "+method, http.StatusMethodNotAllowed) + return false + } + if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) { + http.Error(w, "chunk control restricted to loopback", http.StatusForbidden) + return false + } + return true +} + +// chunkTarget resolves the control for volumeID, or answers +// volume_not_served / not_chunk_volume. +func (s *StatusServer) chunkTarget(w http.ResponseWriter, volumeID string) ChunkControl { + if p := s.statusProjection(); volumeID == "" || volumeID != p.VolumeID { + writeChunkErr(w, http.StatusNotFound, codeVolumeNotServed, false, "volume %q not served by this host (serves %q)", volumeID, p.VolumeID) + return nil + } + s.mu.Lock() + ctl := s.chunkControl + s.mu.Unlock() + if ctl == nil { + writeChunkErr(w, http.StatusConflict, chunkstore.CodeNotChunkVolume, false, "volume %q has no chunk layer here", volumeID) + return nil + } + return ctl +} + +func decodeChunkBody(w http.ResponseWriter, r *http.Request, v any) bool { + dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, chunkBodyLimit)) + dec.DisallowUnknownFields() + if err := dec.Decode(v); err != nil { + http.Error(w, "decode "+r.URL.Path+" request: "+err.Error(), http.StatusBadRequest) + return false + } + return true +} + +// chunkContext bounds a long operation by min(timeoutMs, OpDeadline). +func chunkContext(r *http.Request, timeoutMs int64) (context.Context, context.CancelFunc) { + d := chunkstore.DefaultOpDeadline + if t := time.Duration(timeoutMs) * time.Millisecond; timeoutMs > 0 && t < d { + d = t + } + return context.WithTimeout(r.Context(), d) +} + +func (s *StatusServer) handleChunkCut(w http.ResponseWriter, r *http.Request) { + if !s.chunkAdmit(w, r, http.MethodPost) { + return + } + var req struct { + VolumeID string `json:"volumeID"` + MinLSN uint64 `json:"minLSN"` + TimeoutMs int64 `json:"timeoutMs"` + } + if !decodeChunkBody(w, r, &req) { + return + } + ctl := s.chunkTarget(w, req.VolumeID) + if ctl == nil { + return + } + ctx, cancel := chunkContext(r, req.TimeoutMs) + defer cancel() + res, err := ctl.Cut(ctx, req.VolumeID, req.MinLSN) + if err != nil { + writeChunkFailure(w, err) + return + } + writeChunkJSON(w, http.StatusOK, res) +} + +func (s *StatusServer) handleChunkSnapshot(w http.ResponseWriter, r *http.Request) { + if !s.chunkAdmit(w, r, http.MethodPost) { + return + } + var req struct { + VolumeID string `json:"volumeID"` + Name string `json:"name"` + RequestID string `json:"requestID"` + Labels map[string]string `json:"labels"` + Consistency string `json:"consistency"` + ExpiresAtNs int64 `json:"expiresAtNs"` + TimeoutMs int64 `json:"timeoutMs"` + } + if !decodeChunkBody(w, r, &req) { + return + } + ctl := s.chunkTarget(w, req.VolumeID) + if ctl == nil { + return + } + ctx, cancel := chunkContext(r, req.TimeoutMs) + defer cancel() + info, err := ctl.Snapshot(ctx, req.VolumeID, ChunkSnapshotRequest{Name: req.Name, RequestID: req.RequestID, + Labels: req.Labels, Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs}) + if err != nil { + writeChunkFailure(w, err) + return + } + writeChunkJSON(w, http.StatusOK, snapshotBody{VolumeID: info.VolumeID, Name: info.Name, HeadGen: info.HeadGen, + HeadEpoch: info.HeadEpoch, CutLSN: info.CutLSN, CreatedNs: info.CreatedNs, ChunkCount: info.ChunkCount, + ManifestBytes: info.ManifestBytes, Consistency: info.Consistency, Labels: info.Labels, Replayed: info.Replayed}) +} + +func (s *StatusServer) handleChunkSnapshots(w http.ResponseWriter, r *http.Request) { + if !s.chunkAdmit(w, r, http.MethodGet) { + return + } + q := r.URL.Query() + opts := chunkstore.ListOptions{Prefix: q.Get("prefix"), StartAfter: q.Get("startAfter")} + if v := q.Get("limit"); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 0 { + http.Error(w, fmt.Sprintf("limit=%q: a non-negative integer", v), http.StatusBadRequest) + return + } + opts.Limit = n + } + if v := q.Get("includeDeleting"); v != "" { + b, err := strconv.ParseBool(v) + if err != nil { + http.Error(w, fmt.Sprintf("includeDeleting=%q: true or false", v), http.StatusBadRequest) + return + } + opts.IncludeDeleting = b + } + vol := q.Get("volume") + ctl := s.chunkTarget(w, vol) + if ctl == nil { + return + } + list, next, err := ctl.ListSnapshots(r.Context(), vol, opts) + if err != nil { + writeChunkFailure(w, err) + return + } + body := snapshotsBody{VolumeID: vol, Snapshots: make([]snapshotItem, 0, len(list)), Next: next} + for _, s := range list { + body.Snapshots = append(body.Snapshots, snapshotItem{Name: s.Name, HeadGen: s.HeadGen, HeadEpoch: s.HeadEpoch, + CutLSN: s.CutLSN, CreatedNs: s.CreatedNs, State: s.State, ChunkCount: s.ChunkCount, Labels: s.Labels, + Consistency: s.Consistency, Parent: s.Parent}) + } + writeChunkJSON(w, http.StatusOK, body) +} + +func (s *StatusServer) handleChunkSnapshotDelete(w http.ResponseWriter, r *http.Request) { + if !s.chunkAdmit(w, r, http.MethodPost) { + return + } + var req struct { + VolumeID string `json:"volumeID"` + Name string `json:"name"` + } + if !decodeChunkBody(w, r, &req) { + return + } + ctl := s.chunkTarget(w, req.VolumeID) + if ctl == nil { + return + } + state, err := ctl.DeleteSnapshot(r.Context(), req.VolumeID, req.Name) + if err != nil { + writeChunkFailure(w, err) + return + } + writeChunkJSON(w, http.StatusOK, snapshotDeleteBody{VolumeID: req.VolumeID, Name: req.Name, State: state}) +} + +func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) { + if !s.chunkAdmit(w, r, http.MethodPost) { + return + } + var req struct { + VolumeID string `json:"volumeID"` + TimeoutMs int64 `json:"timeoutMs"` + } + if !decodeChunkBody(w, r, &req) { + return + } + ctl := s.chunkTarget(w, req.VolumeID) + if ctl == nil { + return + } + ctx, cancel := chunkContext(r, req.TimeoutMs) + defer cancel() + res, err := ctl.Detach(ctx, req.VolumeID) + if err != nil { + writeChunkFailure(w, err) + return + } + writeChunkJSON(w, http.StatusOK, res) +} + +// ---- the control over a durable provider and a catalog ---- + +// ChunkProvider is the durable provider's chunk surface the control uses. +type ChunkProvider interface { + // CutVolume takes one quiesced cut and returns what it installed. + CutVolume(ctx context.Context, volumeID string) (storage.ChunkCutResult, error) + // DetachVolume stops the volume's I/O and periodic cuts and publishes + // the detached final cut; it also returns the last written LSN. + DetachVolume(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) +} + +type chunkControl struct { + p ChunkProvider + cat *chunkstore.Catalog +} + +// NewChunkControl serves the routes from a durable provider (cut, detach) +// and the catalog under the provider's chunk base (snapshots). +func NewChunkControl(p ChunkProvider, cat *chunkstore.Catalog) ChunkControl { + return &chunkControl{p: p, cat: cat} +} + +func (c *chunkControl) Cut(ctx context.Context, volumeID string, minLSN uint64) (ChunkCutResponse, error) { + r, err := c.p.CutVolume(ctx, volumeID) + if err != nil { + return ChunkCutResponse{}, err + } + if r.H < minLSN { + return ChunkCutResponse{}, fmt.Errorf("chunk cut of %s reached LSN %d, below minLSN %d (never written)", volumeID, r.H, minLSN) + } + st := r.Stats + return ChunkCutResponse{VolumeID: volumeID, CutLSN: r.H, HeadGen: r.Head.Gen, HeadEpoch: r.Head.Epoch, Holder: r.Head.Holder, + Noop: r.Noop, FullHash: r.FullHash, CandidateChunks: st.CandidateChunks, UploadedChunks: st.UploadedChunks, + UploadedBytes: st.UploadedBytes, ZeroedChunks: st.ZeroedChunks, BarrierPauseNs: st.BarrierPauseNs, + UploadNs: st.UploadNs, CasNs: st.CASNs, TotalNs: st.TotalNs}, nil +} + +// Snapshot validates the request, cuts, and stores the HEAD that cut +// installed (§3.2). A retry with the same request id returns the first +// snapshot even though it cut again. +func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkSnapshotRequest) (chunkstore.SnapshotInfo, error) { + if err := chunkstore.CheckSnapshotName(req.Name); err != nil { + return chunkstore.SnapshotInfo{}, err + } + if req.RequestID == "" { + return chunkstore.SnapshotInfo{}, &chunkstore.CatalogError{Code: chunkstore.CodeInvalidName, Message: "a request id is required"} + } + r, err := c.p.CutVolume(ctx, volumeID) + if err != nil { + return chunkstore.SnapshotInfo{}, err + } + return c.cat.CreateSnapshot(ctx, volumeID, chunkstore.SnapshotRequest{Name: req.Name, RequestID: req.RequestID, + Labels: req.Labels, Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, CreatedBy: "blockvolume", + SourceReadAt: time.Now()}, r.Head) +} + +func (c *chunkControl) ListSnapshots(ctx context.Context, volumeID string, opts chunkstore.ListOptions) ([]chunkstore.SnapshotInfo, string, error) { + return c.cat.ListSnapshots(ctx, volumeID, opts) +} + +func (c *chunkControl) DeleteSnapshot(ctx context.Context, volumeID, name string) (string, error) { + return c.cat.DeleteSnapshot(ctx, volumeID, name) +} + +func (c *chunkControl) Detach(ctx context.Context, volumeID string) (ChunkDetachResponse, error) { + r, last, err := c.p.DetachVolume(ctx, volumeID) + if err != nil { + return ChunkDetachResponse{}, err + } + return ChunkDetachResponse{VolumeID: volumeID, CutLSN: r.H, HeadGen: r.Head.Gen, HeadEpoch: r.Head.Epoch, LastWrittenLSN: last}, nil +} diff --git a/seaweed-block/core/host/volume/chunk_control_adapter_test.go b/seaweed-block/core/host/volume/chunk_control_adapter_test.go new file mode 100644 index 0000000000..6ed0d1596b --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_control_adapter_test.go @@ -0,0 +1,188 @@ +package volume + +import ( + "context" + "path" + "sort" + "strings" + "sync" + "testing" + + "google.golang.org/protobuf/proto" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// memFiler is an in-memory chunkstore.Filer: exclusive create, conditional +// update and delete on extended attributes, and name-ordered listing. +type memFiler struct { + mu sync.Mutex + e map[string]*filerpb.Entry +} + +func newMemFiler() *memFiler { return &memFiler{e: map[string]*filerpb.Entry{}} } + +func (m *memFiler) LookupEntry(_ context.Context, dir, name string) (*filerpb.Entry, error) { + m.mu.Lock() + defer m.mu.Unlock() + e, ok := m.e[path.Join(dir, name)] + if !ok { + return nil, chunkstore.ErrNotFound + } + return proto.Clone(e).(*filerpb.Entry), nil +} + +func (m *memFiler) CreateEntry(_ context.Context, dir string, e *filerpb.Entry, oExcl bool) error { + m.mu.Lock() + defer m.mu.Unlock() + p := path.Join(dir, e.GetName()) + if _, ok := m.e[p]; ok && oExcl { + return chunkstore.ErrExists + } + m.e[p] = proto.Clone(e).(*filerpb.Entry) + return nil +} + +func matches(e *filerpb.Entry, expected map[string][]byte) bool { + for k, v := range expected { + if string(e.GetExtended()[k]) != string(v) { + return false + } + } + return true +} + +func (m *memFiler) UpdateEntry(_ context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error { + m.mu.Lock() + defer m.mu.Unlock() + p := path.Join(dir, e.GetName()) + cur, ok := m.e[p] + if !ok { + return chunkstore.ErrNotFound + } + if !matches(cur, expected) { + return chunkstore.ErrPrecondition + } + m.e[p] = proto.Clone(e).(*filerpb.Entry) + return nil +} + +func (m *memFiler) ListEntries(_ context.Context, dir, prefix, startAfter string, limit uint32) ([]*filerpb.Entry, error) { + m.mu.Lock() + defer m.mu.Unlock() + var names []string + for p := range m.e { + if name := path.Base(p); path.Dir(p) == dir && strings.HasPrefix(name, prefix) && name > startAfter { + names = append(names, name) + } + } + sort.Strings(names) + if limit > 0 && uint32(len(names)) > limit { + names = names[:limit] + } + out := make([]*filerpb.Entry, 0, len(names)) + for _, n := range names { + out = append(out, proto.Clone(m.e[path.Join(dir, n)]).(*filerpb.Entry)) + } + return out, nil +} + +func (m *memFiler) DeleteEntry(_ context.Context, dir, name string, expected map[string][]byte) error { + m.mu.Lock() + defer m.mu.Unlock() + p := path.Join(dir, name) + cur, ok := m.e[p] + if !ok { + return chunkstore.ErrNotFound + } + if !matches(cur, expected) { + return chunkstore.ErrPrecondition + } + delete(m.e, p) + return nil +} + +type fakeChunkProvider struct { + cut storage.ChunkCutResult + detach storage.ChunkCutResult + last uint64 + cuts int +} + +func (f *fakeChunkProvider) CutVolume(context.Context, string) (storage.ChunkCutResult, error) { + f.cuts++ + return f.cut, nil +} + +func (f *fakeChunkProvider) DetachVolume(context.Context, string) (storage.ChunkCutResult, uint64, error) { + return f.detach, f.last, nil +} + +func adapterFixture(t *testing.T) (*fakeChunkProvider, ChunkControl) { + t.Helper() + head := storage.ChunkHead{Gen: 3, Epoch: 2, Holder: "r1", RemoteLSN: 9, State: storage.ChunkHeadActive, + Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e2/c0/k1"}, 5: {Key: "chunks/e2/c5/k2"}}} + fp := &fakeChunkProvider{cut: storage.ChunkCutResult{H: 9, Head: head}} + cat, err := chunkstore.NewCatalog(newMemFiler(), "/swblock/chunks") + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(context.Background(), "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { + t.Fatal(err) + } + return fp, NewChunkControl(fp, cat) +} + +// Snapshot validates before it cuts, then stores the HEAD its cut +// installed (§3.2); list and delete go to the catalog. +func TestChunkControl_SnapshotStoresTheCutHead(t *testing.T) { + ctx := context.Background() + fp, ctl := adapterFixture(t) + for _, bad := range []ChunkSnapshotRequest{{Name: "a/b", RequestID: "r"}, {Name: "s1"}} { + if _, err := ctl.Snapshot(ctx, "v1", bad); chunkstore.CodeOf(err) != chunkstore.CodeInvalidName { + t.Fatalf("snapshot %+v: %v, want invalid_name", bad, err) + } + } + if fp.cuts != 0 { + t.Fatalf("an invalid snapshot request cut %d times", fp.cuts) + } + info, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r", Labels: map[string]string{"agent.step": "x"}, Consistency: "app"}) + if err != nil || fp.cuts != 1 || info.HeadGen != 3 || info.HeadEpoch != 2 || info.CutLSN != 9 || info.ChunkCount != 2 || + info.Labels["agent.step"] != "x" || info.Consistency != "app" || info.Replayed { + t.Fatalf("snapshot: %+v %v (cuts %d)", info, err, fp.cuts) + } + again, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"}) + if err != nil || !again.Replayed || again.HeadGen != 3 { + t.Fatalf("snapshot retry: %+v %v", again, err) + } + if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "other"}); chunkstore.CodeOf(err) != chunkstore.CodeSnapshotExists { + t.Fatalf("snapshot with another request id: %v, want snapshot_exists", err) + } + list, _, err := ctl.ListSnapshots(ctx, "v1", chunkstore.ListOptions{}) + if err != nil || len(list) != 1 || list[0].Name != "s1" { + t.Fatalf("list: %+v %v", list, err) + } + if st, err := ctl.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != chunkstore.SnapDeleting { + t.Fatalf("delete: %q %v", st, err) + } +} + +func TestChunkControl_CutMinLSNAndDetach(t *testing.T) { + ctx := context.Background() + fp, ctl := adapterFixture(t) + if _, err := ctl.Cut(ctx, "v1", 10); err == nil { + t.Fatal("a cut that reached LSN 9 satisfied minLSN 10") + } + r, err := ctl.Cut(ctx, "v1", 9) + if err != nil || r != (ChunkCutResponse{VolumeID: "v1", CutLSN: 9, HeadGen: 3, HeadEpoch: 2, Holder: "r1"}) { + t.Fatalf("cut: %+v %v", r, err) + } + fp.detach = storage.ChunkCutResult{H: 12, Head: storage.ChunkHead{Gen: 4, Epoch: 2, State: storage.ChunkHeadDetached}} + fp.last = 12 + d, err := ctl.Detach(ctx, "v1") + if err != nil || d != (ChunkDetachResponse{VolumeID: "v1", CutLSN: 12, HeadGen: 4, HeadEpoch: 2, LastWrittenLSN: 12}) { + t.Fatalf("detach: %+v %v", d, err) + } +} diff --git a/seaweed-block/core/host/volume/chunk_control_test.go b/seaweed-block/core/host/volume/chunk_control_test.go new file mode 100644 index 0000000000..bd0ddab252 --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_control_test.go @@ -0,0 +1,255 @@ +package volume + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "sort" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/engine" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type fakeChunkControl struct { + err error + cut ChunkCutResponse + snap chunkstore.SnapshotInfo + list []chunkstore.SnapshotInfo + next string + state string + detach ChunkDetachResponse + lastOpts chunkstore.ListOptions + lastSnap ChunkSnapshotRequest + lastMin uint64 + deadline time.Duration +} + +func (f *fakeChunkControl) remember(ctx context.Context) { + if d, ok := ctx.Deadline(); ok { + f.deadline = time.Until(d) + } +} + +func (f *fakeChunkControl) Cut(ctx context.Context, vol string, minLSN uint64) (ChunkCutResponse, error) { + f.remember(ctx) + f.lastMin = minLSN + return f.cut, f.err +} +func (f *fakeChunkControl) Snapshot(ctx context.Context, vol string, req ChunkSnapshotRequest) (chunkstore.SnapshotInfo, error) { + f.remember(ctx) + f.lastSnap = req + return f.snap, f.err +} +func (f *fakeChunkControl) ListSnapshots(ctx context.Context, vol string, opts chunkstore.ListOptions) ([]chunkstore.SnapshotInfo, string, error) { + f.lastOpts = opts + return f.list, f.next, f.err +} +func (f *fakeChunkControl) DeleteSnapshot(ctx context.Context, vol, name string) (string, error) { + return f.state, f.err +} +func (f *fakeChunkControl) Detach(ctx context.Context, vol string) (ChunkDetachResponse, error) { + f.remember(ctx) + return f.detach, f.err +} + +func chunkServer(t *testing.T, ctl ChunkControl, enable bool) *StatusServer { + t.Helper() + p := stubProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 5, EndpointVersion: 3}} + s := NewStatusServer(NewAdapterProjectionView(p, "v1", "r1", nil)) + if enable { + s.EnableChunkControlEndpoint() + } + if ctl != nil { + s.SetChunkControl(ctl) + } + return s +} + +func serve(t *testing.T, s *StatusServer, method, target, body, remote string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(method, target, bytes.NewBufferString(body)) + if remote == "" { + remote = "127.0.0.1:5555" + } + req.RemoteAddr = remote + w := httptest.NewRecorder() + s.chunkMux().ServeHTTP(w, req) + return w +} + +func jsonKeys(t *testing.T, body []byte) []string { + t.Helper() + var m map[string]any + if err := json.Unmarshal(body, &m); err != nil { + t.Fatalf("response is not a JSON object: %v: %s", err, body) + } + var keys []string + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +func wantKeys(t *testing.T, what string, got []string, want ...string) { + t.Helper() + sort.Strings(want) + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("%s JSON fields\n got %v\n want %v", what, got, want) + } +} + +func TestStatusServer_ChunkRoutesOffByDefault(t *testing.T) { + s := chunkServer(t, &fakeChunkControl{}, false) + addr, err := s.Start("127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer func() { _ = s.Close(context.Background()) }() + resp, err := http.Post("http://"+addr+"/chunk/cut", "application/json", strings.NewReader(`{"volumeID":"v1"}`)) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("/chunk/cut without --chunk-control-endpoint: %d, want 404", resp.StatusCode) + } +} + +// The success bodies carry exactly B9's field names (spec §3.1-§3.6). +func TestStatusServer_ChunkSuccessBodiesUseSpecFields(t *testing.T) { + ctl := &fakeChunkControl{ + cut: ChunkCutResponse{VolumeID: "v1", CutLSN: 12, HeadGen: 3, HeadEpoch: 5, Holder: "r1"}, + snap: chunkstore.SnapshotInfo{VolumeID: "v1", Name: "s1", HeadGen: 3, State: "active"}, + list: []chunkstore.SnapshotInfo{{VolumeID: "v1", Name: "s1"}}, + next: "s1", + state: chunkstore.SnapDeleting, + detach: ChunkDetachResponse{VolumeID: "v1", CutLSN: 12, HeadGen: 4, HeadEpoch: 5, LastWrittenLSN: 12}, + } + s := chunkServer(t, ctl, true) + + w := serve(t, s, http.MethodPost, "/chunk/cut", `{"volumeID":"v1","minLSN":7,"timeoutMs":1000}`, "") + if w.Code != 200 || ctl.lastMin != 7 || ctl.deadline <= 0 || ctl.deadline > time.Second { + t.Fatalf("cut: %d %s (minLSN %d, deadline %v)", w.Code, w.Body, ctl.lastMin, ctl.deadline) + } + wantKeys(t, "cut", jsonKeys(t, w.Body.Bytes()), "volumeID", "cutLSN", "headGen", "headEpoch", "holder", "noop", "fullHash", + "candidateChunks", "uploadedChunks", "uploadedBytes", "zeroedChunks", "barrierPauseNs", "uploadNs", "casNs", "totalNs") + + w = serve(t, s, http.MethodPost, "/chunk/snapshot", `{"volumeID":"v1","name":"s1","requestID":"r","labels":{"agent.step":"x"},"consistency":"app","expiresAtNs":9}`, "") + if w.Code != 200 || ctl.lastSnap.Name != "s1" || ctl.lastSnap.RequestID != "r" || ctl.lastSnap.Consistency != "app" || ctl.lastSnap.Labels["agent.step"] != "x" || ctl.lastSnap.ExpiresAtNs != 9 { + t.Fatalf("snapshot: %d %s %+v", w.Code, w.Body, ctl.lastSnap) + } + wantKeys(t, "snapshot", jsonKeys(t, w.Body.Bytes()), "volumeID", "name", "headGen", "headEpoch", "cutLSN", "createdNs", "chunkCount", + "manifestBytes", "consistency", "labels", "replayed") + + w = serve(t, s, http.MethodGet, "/chunk/snapshots?volume=v1&prefix=a&startAfter=b&limit=7&includeDeleting=true", "", "") + if w.Code != 200 || ctl.lastOpts != (chunkstore.ListOptions{Prefix: "a", StartAfter: "b", Limit: 7, IncludeDeleting: true}) { + t.Fatalf("snapshots: %d %s %+v", w.Code, w.Body, ctl.lastOpts) + } + wantKeys(t, "snapshots", jsonKeys(t, w.Body.Bytes()), "volumeID", "snapshots", "next") + var list struct { + Snapshots []json.RawMessage `json:"snapshots"` + } + if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil || len(list.Snapshots) != 1 { + t.Fatalf("snapshots body: %v %s", err, w.Body) + } + wantKeys(t, "snapshots[0]", jsonKeys(t, list.Snapshots[0]), "name", "headGen", "headEpoch", "cutLSN", "createdNs", "state", + "chunkCount", "labels", "consistency", "parent") + + w = serve(t, s, http.MethodPost, "/chunk/snapshot/delete", `{"volumeID":"v1","name":"s1"}`, "") + if w.Code != 200 { + t.Fatalf("delete: %d %s", w.Code, w.Body) + } + wantKeys(t, "snapshot/delete", jsonKeys(t, w.Body.Bytes()), "volumeID", "name", "state") + + w = serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","timeoutMs":120000}`, "") + if w.Code != 200 { + t.Fatalf("detach: %d %s", w.Code, w.Body) + } + wantKeys(t, "detach", jsonKeys(t, w.Body.Bytes()), "volumeID", "cutLSN", "headGen", "headEpoch", "lastWrittenLSN") +} + +// Failures come back as {"code","message","retryable"} with the spec's code +// and HTTP status (spec §2.2). +func TestStatusServer_ChunkErrorBodyIsTyped(t *testing.T) { + cases := []struct { + err error + code string + status int + retryable bool + }{ + {fmt.Errorf("x: %w", storage.ErrChunkLayerFenced), "fenced", 409, false}, + {fmt.Errorf("%w: %w", storage.ErrChunkCaptureRefused, durable.ErrChunkNotPrimary), "not_primary", 409, false}, + {fmt.Errorf("x: %w", durable.ErrChunkAwaitingAuthority), "awaiting_assignment", 409, true}, + {fmt.Errorf("x: %w", durable.ErrVolumeNotOpen), "not_chunk_volume", 409, false}, + {fmt.Errorf("%w: %w", storage.ErrChunkCASOutcomeUnknown, storage.ErrChunkRemoteUnavailable), "outcome_unknown", 503, true}, + {&chunkstore.CatalogError{Code: chunkstore.CodeSnapshotDeleting, Message: "m"}, "snapshot_deleting", 409, false}, + {&chunkstore.CatalogError{Code: chunkstore.CodeOutcomeUnknown, Message: "m", Retryable: true}, "outcome_unknown", 503, true}, + {fmt.Errorf("%w: %w", storage.ErrChunkCaptureRefused, durable.ErrChunkEpochStale), "epoch_stale", 409, false}, + {fmt.Errorf("%w: %w", storage.ErrChunkCaptureRefused, storage.ErrChunkBaseInstalling), "base_installing", 409, true}, + {fmt.Errorf("x: %w", storage.ErrChunkCASOutcomeUnknown), "outcome_unknown", 503, true}, + {fmt.Errorf("x: %w", storage.ErrChunkHeadPrecondition), "head_conflict", 409, true}, + {fmt.Errorf("x: %w", storage.ErrChunkRemoteUnavailable), "remote_unavailable", 503, true}, + {fmt.Errorf("x: %w", storage.ErrChunkLayerClosed), "closing", 503, false}, + {fmt.Errorf("x: %w", storage.ErrChunkLayerDetached), "closing", 503, false}, + {fmt.Errorf("x: %w", durable.ErrNotChunkVolume), "not_chunk_volume", 409, false}, + {&chunkstore.CatalogError{Code: chunkstore.CodeSnapshotExists, Message: "m"}, "snapshot_exists", 409, false}, + {&chunkstore.CatalogError{Code: chunkstore.CodeSnapshotNotFound, Message: "m"}, "snapshot_not_found", 404, false}, + {&chunkstore.CatalogError{Code: chunkstore.CodeInvalidName, Message: "m"}, "invalid_name", 400, false}, + {&chunkstore.CatalogError{Code: chunkstore.CodeDeadlineExceeded, Message: "m", Retryable: true}, "deadline_exceeded", 503, true}, + {context.DeadlineExceeded, "deadline_exceeded", 503, true}, + {errors.New("something else"), "internal", 500, false}, + } + for _, c := range cases { + ctl := &fakeChunkControl{err: c.err} + s := chunkServer(t, ctl, true) + w := serve(t, s, http.MethodPost, "/chunk/cut", `{"volumeID":"v1"}`, "") + var body struct { + Code string `json:"code"` + Message string `json:"message"` + Retryable bool `json:"retryable"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("%v: body is not JSON: %s", c.err, w.Body) + } + if w.Code != c.status || body.Code != c.code || body.Retryable != c.retryable || body.Message == "" { + t.Errorf("%v: got %d %+v, want %d %q retryable=%v", c.err, w.Code, body, c.status, c.code, c.retryable) + } + } +} + +func TestStatusServer_ChunkRequestGuards(t *testing.T) { + s := chunkServer(t, &fakeChunkControl{}, true) + code := func(w *httptest.ResponseRecorder) string { + var b struct { + Code string `json:"code"` + } + _ = json.Unmarshal(w.Body.Bytes(), &b) + return b.Code + } + if w := serve(t, s, http.MethodPost, "/chunk/cut", `{"volumeID":"v9"}`, ""); w.Code != 404 || code(w) != "volume_not_served" { + t.Fatalf("other volume: %d %s", w.Code, w.Body) + } + if w := serve(t, s, http.MethodGet, "/chunk/cut", "", ""); w.Code != http.StatusMethodNotAllowed { + t.Fatalf("GET on a POST route: %d", w.Code) + } + if w := serve(t, s, http.MethodPost, "/chunk/cut", `{"volumeID":"v1"}`, "10.0.0.9:4000"); w.Code != http.StatusForbidden { + t.Fatalf("non-loopback client: %d", w.Code) + } + if w := serve(t, s, http.MethodPost, "/chunk/cut", `{not json`, ""); w.Code != 400 { + t.Fatalf("bad body: %d", w.Code) + } + unwired := chunkServer(t, nil, true) + if w := serve(t, unwired, http.MethodPost, "/chunk/cut", `{"volumeID":"v1"}`, ""); w.Code != 409 || code(w) != "not_chunk_volume" { + t.Fatalf("no chunk control wired: %d %s", w.Code, w.Body) + } +} diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index a9f5f81ce6..2f9df2b7db 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -62,6 +62,8 @@ type StatusServer struct { nvmeSource nvmeStatusSource runtimeSource runtimeRecoverySource frontendCaps []FrontendTransportCapability + chunkEnabled bool // gates /chunk/*; off by default + chunkControl ChunkControl // nil until SetChunkControl } type peerStatusSource interface { @@ -285,6 +287,9 @@ func (s *StatusServer) Start(addr string) (string, error) { if s.runtimeEnabled { mux.HandleFunc("/runtime/rebuild", s.handleRuntimeRebuild) } + if s.chunkEnabled { + mux.Handle("/chunk/", s.chunkMux()) + } s.srv = &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second} go func() { _ = s.srv.Serve(ln) }()