mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
feat(cli): expose read-only chunk GC preview and explicit apply with persisted marks
This commit is contained in:
1 parent
6a449a1447
commit
e17b350c7d
5 files changed
+314
-13
No files matched your search
@@ -44,9 +44,11 @@ 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", false)
|
||||
return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc", false)
|
||||
}
|
||||
switch args[0] {
|
||||
case "gc":
|
||||
return chunkGC(args[1:], stdout, stderr)
|
||||
case "cut":
|
||||
return chunkCut(args[1:], stdout, stderr)
|
||||
case "snapshot":
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// Same clock seam as GCConfig; production always uses wall time. Tests can
|
||||
// advance grace without sleeping while using actual master/store services.
|
||||
var chunkGCNow = time.Now
|
||||
|
||||
func chunkGC(args []string, stdout, stderr io.Writer) int {
|
||||
fs := chunkFlagSet("gc", stderr)
|
||||
var filer, base, master string
|
||||
var apply bool
|
||||
var grace, ttl, timeout time.Duration
|
||||
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address")
|
||||
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "chunk catalog namespace")
|
||||
fs.StringVar(&master, "master", "", "authoritative blockmaster gRPC address")
|
||||
fs.BoolVar(&apply, "apply", false, "settle intents, save completed marks and reclaim eligible chunks; default is read-only")
|
||||
fs.DurationVar(&grace, "grace", time.Hour, "two-mark interval and minimum upload age (must exceed the operation deadline plus mark time)")
|
||||
fs.DurationVar(&ttl, "intent-ttl", time.Hour, "minimum capture-intent age before authoritative epoch expiry")
|
||||
fs.DurationVar(&timeout, "timeout", time.Minute, "bound for this pass, including master/filer/blob calls")
|
||||
if e := fs.Parse(args); e != nil {
|
||||
return chunkFail("gc", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, e.Error(), false)
|
||||
}
|
||||
if fs.NArg() != 0 || filer == "" || master == "" || timeout <= 0 || ttl <= 0 || grace <= chunkstore.DefaultOpDeadline {
|
||||
return chunkFail("gc", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer and --master are required; durations must be positive and grace must exceed the operation deadline", false)
|
||||
}
|
||||
f, closeFn, e := dialChunkFiler(filer)
|
||||
if e != nil {
|
||||
return chunkResult("gc", nil, e, stdout, stderr)
|
||||
}
|
||||
defer closeFn()
|
||||
blobs, ok := f.(chunkstore.BlobDeleter)
|
||||
if !ok {
|
||||
return chunkFail("gc", stdout, stderr, chunkExitFailed, codeInternalCLI, "chunk store cannot delete immutable blobs", false)
|
||||
}
|
||||
cat, e := chunkstore.NewCatalog(f, base)
|
||||
if e != nil {
|
||||
return chunkFail("gc", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, e.Error(), false)
|
||||
}
|
||||
conn, e := grpc.NewClient(master, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if e != nil {
|
||||
return chunkResult("gc", nil, e, stdout, stderr)
|
||||
}
|
||||
defer conn.Close()
|
||||
evidence := control.NewEvidenceServiceClient(conn)
|
||||
issuedEpoch := func(ctx context.Context, vol string) (uint64, error) {
|
||||
reply, e := evidence.QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: vol})
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
if reply.GetVolumeId() != vol || !reply.GetAssigned() || reply.GetEpoch() == 0 {
|
||||
return 0, fmt.Errorf("blockmaster has no issued authority for %s", vol)
|
||||
}
|
||||
return reply.Epoch, nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
out, e := cat.ExecuteGC(ctx, blobs, chunkstore.GCConfig{Grace: grace, IntentTTL: ttl, Now: chunkGCNow, IssuedEpoch: issuedEpoch}, apply)
|
||||
return chunkResult("gc", out, e, stdout, stderr)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -33,7 +34,23 @@ type GCConfig struct {
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
type GCRoot struct {
|
||||
Kind string `json:"kind"`
|
||||
Volume string `json:"volume"`
|
||||
ID string `json:"id"`
|
||||
Keys []string `json:"keys"`
|
||||
Epoch uint64 `json:"epoch,omitempty"`
|
||||
Holder string `json:"holder,omitempty"`
|
||||
}
|
||||
type GCObject struct {
|
||||
Volume string `json:"volume"`
|
||||
Key string `json:"key"`
|
||||
FID string `json:"fid"`
|
||||
}
|
||||
type GCResult struct {
|
||||
Roots []GCRoot `json:"roots"`
|
||||
WouldDelete []GCObject `json:"would_delete"`
|
||||
WouldExpireIntents []string `json:"would_expire_intents"`
|
||||
Volumes, Intents, ExpiredIntents, Candidates, Reclaimed int
|
||||
// Pre-binding needles cannot be enumerated by this API. They are retained;
|
||||
// UnknownUnbound is true rather than inventing a report-only count.
|
||||
@@ -82,12 +99,21 @@ func NewCollector(cat *Catalog, blobs BlobDeleter, cfg GCConfig) (*Collector, er
|
||||
// previous candidates. Roots include active and deleting snapshots until
|
||||
// the catalog has actually removed them; this collector never infers their
|
||||
// absence from an age or a retention label.
|
||||
func (g *Collector) Run(ctx context.Context) (result GCResult, err error) {
|
||||
func (g *Collector) Run(ctx context.Context) (GCResult, error) { return g.run(ctx, true) }
|
||||
|
||||
// Preview performs the same mark and admission as Run, with no metadata,
|
||||
// blob, intent or candidate-state mutations.
|
||||
func (g *Collector) Preview(ctx context.Context) (GCResult, error) { return g.run(ctx, false) }
|
||||
|
||||
func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err error) {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
result.UnknownUnbound = true
|
||||
result.Roots = []GCRoot{}
|
||||
result.WouldDelete = []GCObject{}
|
||||
result.WouldExpireIntents = []string{}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
if err != nil && apply {
|
||||
g.candidates = map[string]gcCandidate{}
|
||||
}
|
||||
}()
|
||||
@@ -112,7 +138,13 @@ func (g *Collector) Run(ctx context.Context) (result GCResult, err error) {
|
||||
if e != nil {
|
||||
return result, e
|
||||
}
|
||||
addHead := func(head storage.ChunkHead) error {
|
||||
addHead := func(kind, id string, head storage.ChunkHead) error {
|
||||
keys := make([]string, 0, len(head.Chunks))
|
||||
for _, ref := range head.Chunks {
|
||||
keys = append(keys, ref.Key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
result.Roots = append(result.Roots, GCRoot{Kind: kind, Volume: vol, ID: id, Keys: keys, Epoch: head.Epoch, Holder: head.Holder})
|
||||
for _, ref := range head.Chunks {
|
||||
dir, name, e := r.keyLocation(ref.Key)
|
||||
if e != nil {
|
||||
@@ -122,7 +154,7 @@ func (g *Collector) Run(ctx context.Context) (result GCResult, err error) {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if e = addHead(h); e != nil {
|
||||
if e = addHead("HEAD", headName, h); e != nil {
|
||||
return result, e
|
||||
}
|
||||
after := ""
|
||||
@@ -132,7 +164,7 @@ func (g *Collector) Run(ctx context.Context) (result GCResult, err error) {
|
||||
return result, e
|
||||
}
|
||||
for _, snap := range snaps {
|
||||
if e = addHead(snap.Head()); e != nil {
|
||||
if e = addHead("snapshot", snap.Name, snap.Head()); e != nil {
|
||||
return result, e
|
||||
}
|
||||
}
|
||||
@@ -148,8 +180,8 @@ func (g *Collector) Run(ctx context.Context) (result GCResult, err error) {
|
||||
if e != nil {
|
||||
return result, e
|
||||
}
|
||||
for _, head := range attempts {
|
||||
if e = addHead(head); e != nil {
|
||||
for _, attempt := range attempts {
|
||||
if e = addHead("snapshot_attempt", attempt.Name, attempt.Head); e != nil {
|
||||
return result, e
|
||||
}
|
||||
}
|
||||
@@ -174,7 +206,13 @@ func (g *Collector) Run(ctx context.Context) (result GCResult, err error) {
|
||||
}
|
||||
if expire {
|
||||
expired = append(expired, gcIntent{r, in})
|
||||
result.WouldExpireIntents = append(result.WouldExpireIntents, path.Join(vol, in.ID))
|
||||
} else {
|
||||
kind := "capture_intent"
|
||||
if strings.HasPrefix(in.Holder, "snapshot:") || strings.HasPrefix(in.Holder, "fork:") {
|
||||
kind = "retained_copy_intent"
|
||||
}
|
||||
result.Roots = append(result.Roots, GCRoot{Kind: kind, Volume: vol, ID: in.ID, Keys: append([]string{}, in.Keys...), Epoch: in.Epoch, Holder: in.Holder})
|
||||
for _, key := range in.Keys {
|
||||
dir, name, e := r.keyLocation(key)
|
||||
if e != nil {
|
||||
@@ -219,6 +257,9 @@ func (g *Collector) Run(ctx context.Context) (result GCResult, err error) {
|
||||
}
|
||||
// An intent is retired only after the complete mark and confirmed fencing.
|
||||
for _, x := range expired {
|
||||
if !apply {
|
||||
continue
|
||||
}
|
||||
if err = x.remote.DeleteIntent(ctx, x.intent.ID); err != nil {
|
||||
return result, err
|
||||
}
|
||||
@@ -249,6 +290,13 @@ func (g *Collector) Run(ctx context.Context) (result GCResult, err error) {
|
||||
nextCandidates[p] = candidate
|
||||
continue
|
||||
}
|
||||
result.WouldDelete = append(result.WouldDelete, GCObject{Volume: b.volume, Key: mustUnescapeGCKey(b.entry.Name), FID: string(b.entry.Extended[extFid])})
|
||||
if !apply {
|
||||
continue
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return result, err
|
||||
}
|
||||
// Preserve the immutable binding forever: removing it would allow Put
|
||||
// to rebind a key that once existed. The tombstone also permits retry
|
||||
// after a failed physical delete without losing the fid.
|
||||
@@ -270,8 +318,10 @@ func (g *Collector) Run(ctx context.Context) (result GCResult, err error) {
|
||||
}
|
||||
result.Reclaimed++
|
||||
}
|
||||
g.candidates = nextCandidates
|
||||
g.last = start
|
||||
if apply {
|
||||
g.candidates = nextCandidates
|
||||
g.last = start
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -284,3 +334,6 @@ func (nilBlobs) Put(context.Context, []byte) (string, error) {
|
||||
func (nilBlobs) Get(context.Context, string) ([]byte, error) {
|
||||
return nil, errors.New("chunkstore: metadata-only remote")
|
||||
}
|
||||
|
||||
// The binding name was already validated before reclamation admission.
|
||||
func mustUnescapeGCKey(name string) string { k, _ := url.PathUnescape(name); return k }
|
||||
@@ -135,13 +135,18 @@ func (g *Collector) gcEntries(ctx context.Context, dir string) ([]*filerpb.Entry
|
||||
// Attempt entries are permanent. A deleting attempt stops rooting its keys
|
||||
// only after its deleting timestamp ages past grace; ordinary two marks
|
||||
// still apply afterward. An aborted attempt roots no keys.
|
||||
func (g *Collector) snapshotAttemptHeads(ctx context.Context, vol string, now time.Time) ([]storage.ChunkHead, error) {
|
||||
type gcSnapshotHead struct {
|
||||
Head storage.ChunkHead
|
||||
Name string
|
||||
}
|
||||
|
||||
func (g *Collector) snapshotAttemptHeads(ctx context.Context, vol string, now time.Time) ([]gcSnapshotHead, error) {
|
||||
root := path.Join(g.cat.base, vol, snapsDir)
|
||||
dirs, err := g.gcEntries(ctx, root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var heads []storage.ChunkHead
|
||||
var heads []gcSnapshotHead
|
||||
for _, dir := range dirs {
|
||||
if !dir.GetIsDirectory() || CheckSnapshotName(dir.Name) != nil {
|
||||
return nil, errors.New("chunkstore: invalid snapshot attempt directory")
|
||||
@@ -173,7 +178,7 @@ func (g *Collector) snapshotAttemptHeads(ctx context.Context, vol string, now ti
|
||||
continue
|
||||
}
|
||||
}
|
||||
heads = append(heads, info.Head())
|
||||
heads = append(heads, gcSnapshotHead{info.Head(), path.Join(dir.Name, e.Name)})
|
||||
}
|
||||
}
|
||||
return heads, nil
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
const gcMarkName = "_GC_MARK"
|
||||
const gcMarkKind = "chunkgcmark"
|
||||
const gcToken = "swb.gc.token"
|
||||
|
||||
type savedGCCandidate struct {
|
||||
SinceNs int64 `json:"since_ns"`
|
||||
Digest string `json:"digest"`
|
||||
}
|
||||
type savedGCMark struct {
|
||||
Format int `json:"format"`
|
||||
Base string `json:"base"`
|
||||
GraceNs int64 `json:"grace_ns"`
|
||||
TTLNs int64 `json:"ttl_ns"`
|
||||
OpDeadlineNs int64 `json:"op_deadline_ns"`
|
||||
Ready bool `json:"ready"`
|
||||
LastNs int64 `json:"last_ns"`
|
||||
Candidates map[string]savedGCCandidate `json:"candidates"`
|
||||
}
|
||||
|
||||
type GCExecution struct {
|
||||
DryRun bool `json:"dry_run"`
|
||||
SettledCopies int `json:"settled_copy_intents"`
|
||||
MarkSaved bool `json:"mark_saved"`
|
||||
GCResult
|
||||
}
|
||||
|
||||
// ExecuteGC binds independent CLI calls to completed filer-side marks.
|
||||
// Preview never writes even the watermark. Apply first invalidates stored
|
||||
// coverage with a conditional empty/in-progress record: crash or failure
|
||||
// cannot leave a failed pass's old coverage available to a later process.
|
||||
// The catalog namespace is the scope; permanent tombstones are untouched.
|
||||
func (c *Catalog) ExecuteGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig, apply bool) (out GCExecution, err error) {
|
||||
out.DryRun = !apply
|
||||
g, err := NewCollector(c, blobs, cfg)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
mark, previous, err := g.readMark(ctx)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
if mark != nil && mark.Ready && mark.GraceNs == int64(cfg.Grace) && mark.TTLNs == int64(cfg.IntentTTL) && mark.OpDeadlineNs == int64(c.deadline()) {
|
||||
for p, candidate := range mark.Candidates {
|
||||
raw, _ := hex.DecodeString(candidate.Digest)
|
||||
var digest [32]byte
|
||||
copy(digest[:], raw)
|
||||
g.candidates[p] = gcCandidate{time.Unix(0, candidate.SinceNs), digest}
|
||||
}
|
||||
g.last = time.Unix(0, mark.LastNs)
|
||||
}
|
||||
if !apply {
|
||||
out.GCResult, err = g.Preview(ctx)
|
||||
return out, err
|
||||
}
|
||||
busy := g.mark(false)
|
||||
token, err := g.writeMark(ctx, busy, previous)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.SettledCopies, err = g.SweepCopies(ctx)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.GCResult, err = g.Run(ctx)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
_, err = g.writeMark(ctx, g.mark(true), token)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.MarkSaved = true
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (g *Collector) mark(ready bool) savedGCMark {
|
||||
m := savedGCMark{Format: 1, Base: g.cat.base, GraceNs: int64(g.cfg.Grace), TTLNs: int64(g.cfg.IntentTTL), OpDeadlineNs: int64(g.cat.deadline()), Ready: ready, Candidates: map[string]savedGCCandidate{}}
|
||||
if ready {
|
||||
m.LastNs = g.last.UnixNano()
|
||||
for p, c := range g.candidates {
|
||||
m.Candidates[p] = savedGCCandidate{c.since.UnixNano(), hex.EncodeToString(c.digest[:])}
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (g *Collector) readMark(ctx context.Context) (*savedGCMark, string, error) {
|
||||
e, err := g.cat.f.LookupEntry(ctx, g.cat.base, gcMarkName)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, "", nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
token := string(e.Extended[gcToken])
|
||||
if e.GetIsDirectory() || len(e.GetChunks()) != 0 || string(e.Extended[extKind]) != gcMarkKind || !storage.ValidChunkIntentID(token) || len(e.Content) > 64<<20 {
|
||||
return nil, "", errors.New("chunkstore: invalid GC mark entry")
|
||||
}
|
||||
var m savedGCMark
|
||||
d := json.NewDecoder(bytes.NewReader(e.Content))
|
||||
d.DisallowUnknownFields()
|
||||
if err = d.Decode(&m); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
var trailing any
|
||||
if err = d.Decode(&trailing); err != io.EOF {
|
||||
return nil, "", errors.New("chunkstore: trailing GC mark content")
|
||||
}
|
||||
if m.Format != 1 || m.Base != g.cat.base || m.GraceNs <= 0 || m.TTLNs <= 0 || m.OpDeadlineNs <= 0 {
|
||||
return nil, "", errors.New("chunkstore: incompatible GC mark")
|
||||
}
|
||||
if m.Ready {
|
||||
now := g.cfg.Now().UnixNano()
|
||||
if m.LastNs <= 0 || m.LastNs > now {
|
||||
return nil, "", errors.New("chunkstore: invalid/future GC mark time")
|
||||
}
|
||||
for p, c := range m.Candidates {
|
||||
digest, err := hex.DecodeString(c.Digest)
|
||||
if err != nil || len(digest) != 32 || c.SinceNs <= 0 || c.SinceNs > m.LastNs || path.Clean(p) != p || !strings.HasPrefix(p, g.cat.base+"/") || !strings.Contains(p, "/"+keysDir+"/") {
|
||||
return nil, "", errors.New("chunkstore: invalid GC candidate state")
|
||||
}
|
||||
}
|
||||
} else if m.LastNs != 0 || len(m.Candidates) != 0 {
|
||||
return nil, "", errors.New("chunkstore: incomplete GC mark carries coverage")
|
||||
}
|
||||
return &m, token, nil
|
||||
}
|
||||
|
||||
func (g *Collector) writeMark(ctx context.Context, m savedGCMark, expected string) (string, error) {
|
||||
token, err := storage.NewChunkIntentID(0)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
body, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(body) > 64<<20 {
|
||||
return "", errors.New("chunkstore: GC mark exceeds 64 MiB")
|
||||
}
|
||||
now := g.cfg.Now().Unix()
|
||||
e := &filerpb.Entry{Name: gcMarkName, Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Crtime: now, Mtime: now, FileMode: 0600}, Content: body, Extended: map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(token)}}
|
||||
if expected == "" {
|
||||
err = g.cat.f.CreateEntry(ctx, g.cat.base, e, true)
|
||||
} else {
|
||||
err = g.cat.f.UpdateEntry(ctx, g.cat.base, e, map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(expected)})
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("chunkstore: GC watermark changed or unavailable: %w", err)
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
Reference in new issue
Block a user