mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Merge pull request #151 from seaweedfs/feat/parallel-segment-manifests
Parallelize chunk uploads and publish immutable manifest segments
This commit is contained in:
commit
139d649ddf
26 files changed
+1716
-85
No files matched your search
@@ -29,12 +29,13 @@ const (
|
||||
)
|
||||
|
||||
type chunkFlags struct {
|
||||
filer string
|
||||
path string
|
||||
collection string
|
||||
replication string
|
||||
captureInterval time.Duration
|
||||
dirtyThreshold int
|
||||
filer string
|
||||
path string
|
||||
collection string
|
||||
replication string
|
||||
captureInterval time.Duration
|
||||
dirtyThreshold int
|
||||
uploadConcurrency int
|
||||
// controlEndpoint mounts the /chunk/* routes on the status listener.
|
||||
controlEndpoint bool
|
||||
}
|
||||
@@ -44,7 +45,7 @@ func validateChunkFlags(f flags) error {
|
||||
if f.durableImpl != "walstore-chunk" {
|
||||
if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath ||
|
||||
c.captureInterval != defaultChunkCaptureInterval || c.dirtyThreshold != defaultChunkDirtyThreshold ||
|
||||
c.controlEndpoint {
|
||||
c.uploadConcurrency != 8 || c.controlEndpoint {
|
||||
return errors.New("--chunk-* flags require --durable-impl=walstore-chunk")
|
||||
}
|
||||
return nil
|
||||
@@ -64,6 +65,9 @@ func validateChunkFlags(f flags) error {
|
||||
if c.captureInterval < 0 {
|
||||
return fmt.Errorf("--chunk-capture-interval=%s must not be negative", c.captureInterval)
|
||||
}
|
||||
if c.uploadConcurrency < 1 || c.uploadConcurrency > 64 {
|
||||
return errors.New("--chunk-upload-concurrency must be between 1 and 64")
|
||||
}
|
||||
if c.dirtyThreshold < 0 {
|
||||
return fmt.Errorf("--chunk-dirty-threshold=%d must not be negative", c.dirtyThreshold)
|
||||
}
|
||||
|
||||
@@ -54,9 +54,11 @@ func TestWALStoreChunkFlags(t *testing.T) {
|
||||
"--chunk-control-endpoint"),
|
||||
"control endpoint without a status listener": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk",
|
||||
"--chunk-filer=x:1", "--chunk-control-endpoint"),
|
||||
"negative threshold": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=-1"),
|
||||
"threshold on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-dirty-threshold=8"),
|
||||
"interval on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-capture-interval=5s"),
|
||||
"zero upload concurrency": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-upload-concurrency=0"),
|
||||
"too many uploads": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-upload-concurrency=65"),
|
||||
"negative threshold": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=-1"),
|
||||
"threshold on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-dirty-threshold=8"),
|
||||
"interval on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-capture-interval=5s"),
|
||||
}
|
||||
for name, args := range refused {
|
||||
if _, err := parseFlags(args); err == nil {
|
||||
|
||||
@@ -191,6 +191,7 @@ func parseFlags(args []string) (flags, error) {
|
||||
fs.StringVar(&f.chunk.collection, "chunk-collection", "", "walstore-chunk: collection for chunk needles (empty = filer default / storage rule)")
|
||||
fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)")
|
||||
fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: automatic cut once this long has passed since the last successful cut; 0 (default) disables the timer, e.g. 15m as a host-loss safety net")
|
||||
fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)")
|
||||
fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", defaultChunkDirtyThreshold, "walstore-chunk: bound on one cut's barrier copy, in chunks; never triggers a cut; 0 = unbounded")
|
||||
fs.BoolVar(&f.chunk.controlEndpoint, "chunk-control-endpoint", false, "walstore-chunk: expose the /chunk/* control routes (cut, snapshot, snapshots, snapshot/delete, detach) on the status HTTP listener; off by default; loopback-only like the listener")
|
||||
fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)")
|
||||
@@ -604,6 +605,7 @@ func run(f flags) int {
|
||||
chunk, chunkErr = newChunkWiring(f.chunk)
|
||||
cfg.ChunkCaptureInterval = f.chunk.captureInterval
|
||||
cfg.ChunkDirtyThreshold = f.chunk.dirtyThreshold
|
||||
cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency
|
||||
cfg.ChunkHolder = chunkHolder(f)
|
||||
if chunkErr == nil {
|
||||
cfg.ChunkRemoteFor = chunk.remoteFor
|
||||
|
||||
@@ -102,7 +102,24 @@ func TestIntegration_OpsChunkGC_RealMasterAndStore(t *testing.T) {
|
||||
h.Holder = "holder-a"
|
||||
h.RemoteLSN = 1
|
||||
h.Chunks = map[uint64]storage.ChunkRef{0: {Key: "live", SHA256: sha256.Sum256(data)}}
|
||||
flat := h
|
||||
segmented, segmentIntents, err := remote.PrepareManifest(ctx, flat, h, 8*4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h = segmented
|
||||
h.Gen, err = remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: 0}, h)
|
||||
if err == nil {
|
||||
for _, id := range segmentIntents {
|
||||
if err = remote.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if h.Segments == nil || len(h.Segments) != 1 {
|
||||
t.Fatal("real-service acceptance requires a segmented root")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -281,8 +281,9 @@ type ForkResult struct {
|
||||
|
||||
// Catalog reads and writes the control-plane entries under one chunk base.
|
||||
type Catalog struct {
|
||||
f Filer
|
||||
base string
|
||||
blobs Blobs // optional immutable-object reader; SWFS supplies it directly
|
||||
f Filer
|
||||
base string
|
||||
// OpDeadline bounds a snapshot or fork (DefaultOpDeadline when zero).
|
||||
OpDeadline time.Duration
|
||||
now func() time.Time
|
||||
@@ -300,7 +301,8 @@ func NewCatalog(f Filer, base string) (*Catalog, error) {
|
||||
if !path.IsAbs(base) || path.Clean(base) != base || base == "/" {
|
||||
return nil, fmt.Errorf("chunkstore: chunk base %q must be a clean absolute directory other than /", base)
|
||||
}
|
||||
return &Catalog{f: f, base: base, now: time.Now}, nil
|
||||
blobs, _ := f.(Blobs)
|
||||
return &Catalog{f: f, blobs: blobs, base: base, now: time.Now}, nil
|
||||
}
|
||||
|
||||
// SetClock replaces the catalog's clock (tests).
|
||||
@@ -664,7 +666,7 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) {
|
||||
}
|
||||
return SnapshotInfo{
|
||||
VolumeID: doc.VolumeID, Name: doc.Name, HeadGen: head.Gen, HeadEpoch: head.Epoch, CutLSN: head.RemoteLSN,
|
||||
CreatedNs: doc.CreatedNs, State: state, ChunkCount: len(head.Chunks), ManifestBytes: len(e.GetContent()),
|
||||
CreatedNs: doc.CreatedNs, State: state, ChunkCount: manifestCount(head), ManifestBytes: len(e.GetContent()),
|
||||
Consistency: doc.Consistency, Labels: doc.Labels, Parent: doc.Parent, ExpiresAtNs: doc.ExpiresAtNs,
|
||||
Class: doc.Class, head: head, geo: doc.Geometry,
|
||||
}, doc.RequestID, nil
|
||||
@@ -785,6 +787,13 @@ func headDigest(h storage.ChunkHead) (string, error) {
|
||||
}
|
||||
|
||||
func headKeys(h storage.ChunkHead) []string {
|
||||
if h.Segments != nil {
|
||||
keys := make([]string, 0, len(h.Segments))
|
||||
for _, ref := range h.Segments {
|
||||
keys = append(keys, ref.Key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
keys := make([]string, 0, len(h.Chunks))
|
||||
for _, ref := range h.Chunks {
|
||||
keys = append(keys, ref.Key)
|
||||
@@ -864,7 +873,7 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe
|
||||
|
||||
tag := "snapshot:" + vol + "/" + req.Name + "/" + attempt
|
||||
deadline := readAt.Add(c.deadline())
|
||||
id, err := putIntent(ctx, c.f, root, storage.ChunkIntent{Gen: head.Gen, Epoch: head.Epoch, Holder: tag, Keys: headKeys(head),
|
||||
id, err := putIntent(ctx, c.f, root, storage.ChunkIntent{Gen: head.Gen, Epoch: head.Epoch, Holder: tag, Keys: headKeys(head), Segments: head.Segments, ChunkBytes: head.ChunkBytes,
|
||||
DeadlineNs: deadline.UnixNano()})
|
||||
if err != nil {
|
||||
return SnapshotInfo{}, remoteErr(err, "intent for snapshot %s/%s", vol, req.Name)
|
||||
@@ -1185,6 +1194,15 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error)
|
||||
}
|
||||
head := storage.ChunkHead{Gen: 1, Epoch: 0, Holder: "", RemoteLSN: src.RemoteLSN, Chunks: make(map[uint64]storage.ChunkRef, len(src.Chunks)), State: storage.ChunkHeadActive}
|
||||
qualified := 0
|
||||
if src.Segments != nil {
|
||||
head.Segments = make(map[uint64]storage.ChunkSegment, len(src.Segments))
|
||||
head.ChunkBytes, head.ManifestChunkCount = src.ChunkBytes, src.ManifestChunkCount
|
||||
for idx, ref := range src.Segments {
|
||||
ref.Key = qualifyManifestKey(req.Source, ref.Key)
|
||||
head.Segments[idx] = ref
|
||||
qualified++
|
||||
}
|
||||
}
|
||||
for idx, ref := range src.Chunks {
|
||||
if !strings.HasPrefix(ref.Key, "@") {
|
||||
ref.Key = "@" + req.Source + "/" + ref.Key
|
||||
@@ -1193,7 +1211,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error)
|
||||
head.Chunks[idx] = ref
|
||||
}
|
||||
record := &ForkRecord{RequestID: req.RequestID, Source: req.Source, Snapshot: req.Snapshot, SourceGen: snap.HeadGen,
|
||||
HeadSHA256: digest, RemoteLSN: head.RemoteLSN, ChunkCount: len(head.Chunks), QualifiedRefs: qualified}
|
||||
HeadSHA256: digest, RemoteLSN: head.RemoteLSN, ChunkCount: manifestCount(head), QualifiedRefs: qualified}
|
||||
|
||||
if ok {
|
||||
// An incomplete fork of this request resumes only on the same image.
|
||||
@@ -1230,7 +1248,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error)
|
||||
}
|
||||
he.Extended[extReq] = []byte(req.RequestID)
|
||||
deadline := readAt.Add(c.deadline())
|
||||
id, err := putIntent(ctx, c.f, dstRoot, storage.ChunkIntent{Gen: 0, Epoch: 0, Holder: tag, Keys: headKeys(head),
|
||||
id, err := putIntent(ctx, c.f, dstRoot, storage.ChunkIntent{Gen: 0, Epoch: 0, Holder: tag, Keys: headKeys(head), Segments: head.Segments, ChunkBytes: head.ChunkBytes,
|
||||
DeadlineNs: deadline.UnixNano()})
|
||||
if err != nil {
|
||||
return ForkResult{}, remoteErr(err, "intent for fork %s", req.Target)
|
||||
|
||||
@@ -489,8 +489,8 @@ func TestFork_ThenFreshHostReadsSnapshotImage(t *testing.T) {
|
||||
if len(keysAfter) != len(keysBefore) {
|
||||
t.Fatalf("the fork's cut wrote %d keys into the source volume", len(keysAfter)-len(keysBefore))
|
||||
}
|
||||
if own, _ := f.ListEntries(ctx, catBase+"/v2/keys", "", "", 0); len(own) != 1 {
|
||||
t.Fatalf("the fork's cut wrote %d keys of its own, want 1", len(own))
|
||||
if own, _ := f.ListEntries(ctx, catBase+"/v2/keys", "", "", 0); len(own) != 2 {
|
||||
t.Fatalf("the fork's cut wrote %d keys of its own, want one data chunk and one manifest", len(own))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -146,6 +146,10 @@ func (r *ChunkRemote) keyLocation(key string) (dir, name string, err error) {
|
||||
// create. A key that is already bound fails with storage.ErrChunkKeyExists
|
||||
// and its bytes are untouched.
|
||||
func (r *ChunkRemote) Put(ctx context.Context, key string, data []byte) error {
|
||||
return r.putObject(ctx, key, data, "")
|
||||
}
|
||||
|
||||
func (r *ChunkRemote) putObject(ctx context.Context, key string, data []byte, object string) error {
|
||||
if err := storage.ValidChunkKey(key); err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrInvalidKey, err)
|
||||
}
|
||||
@@ -172,6 +176,10 @@ func (r *ChunkRemote) Put(ctx context.Context, key string, data []byte) error {
|
||||
Attributes: &filerpb.FuseAttributes{Mtime: now, Crtime: now, FileMode: 0o644},
|
||||
Extended: map[string][]byte{extKind: []byte(kindChunkKey), extFid: []byte(fid)},
|
||||
}
|
||||
if object == "segment" {
|
||||
e.Extended["swb.object"] = []byte("segment")
|
||||
e.Attributes.FileSize = uint64(len(data))
|
||||
}
|
||||
if err := r.f.CreateEntry(ctx, r.keyDir(), e, true); err != nil {
|
||||
if errors.Is(err, ErrExists) {
|
||||
return fmt.Errorf("%w: %s", storage.ErrChunkKeyExists, key)
|
||||
@@ -214,12 +222,14 @@ func (r *ChunkRemote) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
func (r *ChunkRemote) Delete(context.Context, string) error { return ErrDeleteUnsupported }
|
||||
|
||||
type intentDoc struct {
|
||||
Format int `json:"format"`
|
||||
Gen uint64 `json:"gen"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
Holder string `json:"holder"`
|
||||
Keys []string `json:"keys"`
|
||||
CreatedNs int64 `json:"created_ns"`
|
||||
Segments map[uint64]storage.ChunkSegment `json:"segments,omitempty"`
|
||||
ChunkBytes uint64 `json:"chunk_bytes,omitempty"`
|
||||
Format int `json:"format"`
|
||||
Gen uint64 `json:"gen"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
Holder string `json:"holder"`
|
||||
Keys []string `json:"keys"`
|
||||
CreatedNs int64 `json:"created_ns"`
|
||||
// DeadlineNs: a copy intent's publication deadline (0: a capture intent).
|
||||
DeadlineNs int64 `json:"deadline_ns,omitempty"`
|
||||
}
|
||||
@@ -246,7 +256,7 @@ func putIntent(ctx context.Context, f Filer, root string, in storage.ChunkIntent
|
||||
return "", err
|
||||
}
|
||||
now := time.Now()
|
||||
body, err := json.Marshal(intentDoc{Format: intentFormat, Gen: in.Gen, Epoch: in.Epoch, Holder: in.Holder, Keys: in.Keys, CreatedNs: now.UnixNano(), DeadlineNs: in.DeadlineNs})
|
||||
body, err := json.Marshal(intentDoc{Format: intentFormat, Gen: in.Gen, Epoch: in.Epoch, Holder: in.Holder, Keys: in.Keys, CreatedNs: now.UnixNano(), DeadlineNs: in.DeadlineNs, Segments: in.Segments, ChunkBytes: in.ChunkBytes})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -325,16 +335,19 @@ func decodeIntent(p string, e *filerpb.Entry) (storage.ChunkIntent, error) {
|
||||
return fail("name or extended gen/epoch/holder disagree with the document")
|
||||
}
|
||||
return storage.ChunkIntent{ID: e.GetName(), Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder,
|
||||
Keys: append([]string(nil), doc.Keys...), CreatedNs: doc.CreatedNs, DeadlineNs: doc.DeadlineNs}, nil
|
||||
Keys: append([]string(nil), doc.Keys...), CreatedNs: doc.CreatedNs, DeadlineNs: doc.DeadlineNs, Segments: doc.Segments, ChunkBytes: doc.ChunkBytes}, nil
|
||||
}
|
||||
|
||||
type headDoc struct {
|
||||
Format int `json:"format"`
|
||||
Gen uint64 `json:"gen"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
Holder string `json:"holder"`
|
||||
RemoteLSN uint64 `json:"remote_lsn"`
|
||||
Chunks map[uint64]refDoc `json:"chunks"`
|
||||
Segments map[uint64]storage.ChunkSegment `json:"segments,omitempty"`
|
||||
ChunkBytes uint64 `json:"chunk_bytes,omitempty"`
|
||||
ChunkCount int `json:"chunk_count,omitempty"`
|
||||
Format int `json:"format"`
|
||||
Gen uint64 `json:"gen"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
Holder string `json:"holder"`
|
||||
RemoteLSN uint64 `json:"remote_lsn"`
|
||||
Chunks map[uint64]refDoc `json:"chunks,omitempty"`
|
||||
// State is "active" or "detached"; a document without it is active.
|
||||
// DetachedBy names the holder whose final cut (this generation) a
|
||||
// detached HEAD is; it is absent unless State is detached.
|
||||
@@ -364,7 +377,11 @@ func (r *ChunkRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
|
||||
if err != nil {
|
||||
return storage.ChunkHead{}, err
|
||||
}
|
||||
return decodeHead(path.Join(r.root, headName), e)
|
||||
h, err := decodeHead(path.Join(r.root, headName), e)
|
||||
if err != nil {
|
||||
return h, err
|
||||
}
|
||||
return r.resolveManifest(ctx, h)
|
||||
}
|
||||
|
||||
// CASHead installs next, at generation expected.Gen+1, only if the stored
|
||||
@@ -412,15 +429,28 @@ func (r *ChunkRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVer
|
||||
|
||||
func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) {
|
||||
doc := headDoc{Format: headFormat, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN,
|
||||
Chunks: make(map[uint64]refDoc, len(h.Chunks)), State: h.State}
|
||||
State: h.State}
|
||||
if h.DetachedBy != nil {
|
||||
doc.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen}
|
||||
}
|
||||
for idx, ref := range h.Chunks {
|
||||
if ref.Key == "" {
|
||||
return nil, fmt.Errorf("chunkstore: HEAD chunk %d has no key", idx)
|
||||
if h.Segments == nil {
|
||||
doc.Chunks = make(map[uint64]refDoc, len(h.Chunks))
|
||||
for idx, ref := range h.Chunks {
|
||||
if ref.Key == "" {
|
||||
return nil, fmt.Errorf("chunkstore: HEAD chunk %d has no key", idx)
|
||||
}
|
||||
doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])}
|
||||
}
|
||||
doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])}
|
||||
}
|
||||
if h.Segments != nil {
|
||||
if err := validateRoot(h); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
doc.Format = 2
|
||||
doc.Chunks = nil
|
||||
doc.Segments = h.Segments
|
||||
doc.ChunkBytes = h.ChunkBytes
|
||||
doc.ChunkCount = h.ManifestChunkCount
|
||||
}
|
||||
body, err := json.Marshal(doc)
|
||||
if err != nil {
|
||||
@@ -477,13 +507,10 @@ func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) {
|
||||
fail := func(format string, a ...any) (storage.ChunkHead, error) {
|
||||
return storage.ChunkHead{}, fmt.Errorf("chunkstore: HEAD %s: "+format, append([]any{p}, a...)...)
|
||||
}
|
||||
var doc headDoc
|
||||
if err := json.Unmarshal(content, &doc); err != nil {
|
||||
doc, err := decodeFormatHead(content)
|
||||
if err != nil {
|
||||
return fail("decode: %v", err)
|
||||
}
|
||||
if doc.Format != headFormat {
|
||||
return fail("format %d not supported (want %d)", doc.Format, headFormat)
|
||||
}
|
||||
if doc.Gen == 0 {
|
||||
return fail("generation 0")
|
||||
}
|
||||
@@ -519,6 +546,20 @@ func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) {
|
||||
copy(cr.SHA256[:], sum)
|
||||
h.Chunks[idx] = cr
|
||||
}
|
||||
if doc.Format == 2 {
|
||||
if len(doc.Chunks) != 0 {
|
||||
return fail("segmented root contains flat chunks")
|
||||
}
|
||||
h.Segments = doc.Segments
|
||||
if h.Segments == nil {
|
||||
h.Segments = map[uint64]storage.ChunkSegment{}
|
||||
}
|
||||
h.ChunkBytes = doc.ChunkBytes
|
||||
h.ManifestChunkCount = doc.ChunkCount
|
||||
if err := validateRoot(h); err != nil {
|
||||
return h, err
|
||||
}
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
@@ -529,3 +570,9 @@ func NewSWFSChunkRemote(c *SWFS, root string) (*ChunkRemote, error) {
|
||||
}
|
||||
|
||||
var _ storage.ChunkRemote = (*ChunkRemote)(nil)
|
||||
|
||||
// DecodeHeadDocument validates a persisted flat or segmented root without
|
||||
// fetching data. Control-plane readers share the same representation checks.
|
||||
func DecodeHeadDocument(name string, body []byte) (storage.ChunkHead, error) {
|
||||
return decodeHeadDoc(name, body)
|
||||
}
|
||||
@@ -290,8 +290,8 @@ func TestChunkRemote_ChunkLayerCaptureThenFreshHost(t *testing.T) {
|
||||
t.Fatalf("RemoteLSN %d after capture at %d", layer.RemoteLSN(), h)
|
||||
}
|
||||
puts, _, _ := b.counts()
|
||||
if puts != 4 { // chunks 0, 1, 2 and 7
|
||||
t.Fatalf("capture stored %d needles; want 4", puts)
|
||||
if puts != 5 { // chunks 0, 1, 2 and 7, plus their manifest segment
|
||||
t.Fatalf("capture stored %d needles; want 4 data chunks plus one manifest", puts)
|
||||
}
|
||||
_ = src.Close()
|
||||
|
||||
@@ -310,7 +310,7 @@ func TestChunkRemote_ChunkLayerCaptureThenFreshHost(t *testing.T) {
|
||||
t.Fatalf("fresh host block %d = %x...; want %x...", lba, got[:4], exp[:4])
|
||||
}
|
||||
}
|
||||
if _, gets, _ := b.counts(); gets != 4 { // each published chunk fetched once
|
||||
t.Fatalf("fresh host fetched %d needles; want 4", gets)
|
||||
if _, gets, _ := b.counts(); gets != 5 { // four data chunks and one manifest fetched once
|
||||
t.Fatalf("fresh host fetched %d needles; want 4 data chunks plus one manifest", gets)
|
||||
}
|
||||
}
|
||||
@@ -130,7 +130,7 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e
|
||||
}
|
||||
result.Volumes = len(volumes)
|
||||
for _, vol := range volumes {
|
||||
r, e := NewChunkRemote(g.cat.f, nilBlobs{}, path.Join(g.cat.base, vol))
|
||||
r, e := NewChunkRemote(g.cat.f, gcBlobReader{g.blobs}, path.Join(g.cat.base, vol))
|
||||
if e != nil {
|
||||
return result, e
|
||||
}
|
||||
@@ -139,7 +139,23 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e
|
||||
return result, e
|
||||
}
|
||||
addHead := func(kind, id string, head storage.ChunkHead) error {
|
||||
keys := make([]string, 0, len(head.Chunks))
|
||||
var err error
|
||||
head, err = r.resolveManifest(ctx, head)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, ref := range head.Segments {
|
||||
dir, name, err := r.keyLocation(ref.Key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
roots[path.Join(dir, name)] = true
|
||||
}
|
||||
|
||||
keys := make([]string, 0, len(head.Chunks)+len(head.Segments))
|
||||
for _, ref := range head.Segments {
|
||||
keys = append(keys, ref.Key)
|
||||
}
|
||||
for _, ref := range head.Chunks {
|
||||
keys = append(keys, ref.Key)
|
||||
}
|
||||
@@ -212,6 +228,15 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e
|
||||
if strings.HasPrefix(in.Holder, "snapshot:") || strings.HasPrefix(in.Holder, "fork:") {
|
||||
kind = "retained_copy_intent"
|
||||
}
|
||||
if in.Segments != nil {
|
||||
h := storage.ChunkHead{Segments: in.Segments, ChunkBytes: in.ChunkBytes}
|
||||
for _, ref := range in.Segments {
|
||||
h.ManifestChunkCount += ref.Count
|
||||
}
|
||||
if err := addHead(kind, in.ID, h); err != nil {
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
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)
|
||||
@@ -337,3 +362,20 @@ func (nilBlobs) Get(context.Context, string) ([]byte, error) {
|
||||
|
||||
// The binding name was already validated before reclamation admission.
|
||||
func mustUnescapeGCKey(name string) string { k, _ := url.PathUnescape(name); return k }
|
||||
|
||||
// GC needs immutable segment bytes as well as deletion. Flat-only legacy
|
||||
// adapters remain usable; a segmented root without a reader refuses the mark.
|
||||
type gcBlobReader struct{ BlobDeleter }
|
||||
|
||||
func (b gcBlobReader) Put(context.Context, []byte) (string, error) {
|
||||
return "", errors.New("chunkstore: GC is read-only during mark")
|
||||
}
|
||||
func (b gcBlobReader) Get(ctx context.Context, fid string) ([]byte, error) {
|
||||
reader, ok := b.BlobDeleter.(interface {
|
||||
Get(context.Context, string) ([]byte, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, errors.New("chunkstore: GC segment reader unavailable")
|
||||
}
|
||||
return reader.Get(ctx, fid)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// Only identity/proof fields are shared between persisted representations.
|
||||
// Format-specific structs deliberately have no field for the other format:
|
||||
// DisallowUnknownFields rejects even encoding/json's Unicode-folded aliases.
|
||||
type headIdentityDoc struct {
|
||||
Format int `json:"format"`
|
||||
Gen uint64 `json:"gen"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
Holder string `json:"holder"`
|
||||
RemoteLSN uint64 `json:"remote_lsn"`
|
||||
State string `json:"state,omitempty"`
|
||||
DetachedBy *detachedByDoc `json:"detachedBy,omitempty"`
|
||||
}
|
||||
type flatHeadDoc struct {
|
||||
headIdentityDoc
|
||||
Chunks map[uint64]refDoc `json:"chunks"`
|
||||
}
|
||||
type segmentedHeadDoc struct {
|
||||
headIdentityDoc
|
||||
Segments map[uint64]storage.ChunkSegment `json:"segments"`
|
||||
ChunkBytes uint64 `json:"chunk_bytes"`
|
||||
ChunkCount int `json:"chunk_count"`
|
||||
}
|
||||
|
||||
func (d headIdentityDoc) document() headDoc {
|
||||
return headDoc{Format: d.Format, Gen: d.Gen, Epoch: d.Epoch, Holder: d.Holder, RemoteLSN: d.RemoteLSN, State: d.State, DetachedBy: d.DetachedBy}
|
||||
}
|
||||
|
||||
func decodeFormatHead(content []byte) (headDoc, error) {
|
||||
var discriminator struct {
|
||||
Format int `json:"format"`
|
||||
}
|
||||
// Preserve duplicate/nesting/byte/trailing-byte checks before selecting the
|
||||
// schema. Unknown fields are allowed ONLY for this discriminator read.
|
||||
if err := decodeManifestJSON(content, &discriminator); err != nil {
|
||||
return headDoc{}, err
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(content))
|
||||
decoder.DisallowUnknownFields()
|
||||
switch discriminator.Format {
|
||||
case 1:
|
||||
var flat flatHeadDoc
|
||||
if err := decoder.Decode(&flat); err != nil {
|
||||
return headDoc{}, err
|
||||
}
|
||||
doc := flat.headIdentityDoc.document()
|
||||
doc.Chunks = flat.Chunks
|
||||
return doc, nil
|
||||
case 2:
|
||||
var segmented segmentedHeadDoc
|
||||
if err := decoder.Decode(&segmented); err != nil {
|
||||
return headDoc{}, err
|
||||
}
|
||||
doc := segmented.headIdentityDoc.document()
|
||||
doc.Segments, doc.ChunkBytes, doc.ChunkCount = segmented.Segments, segmented.ChunkBytes, segmented.ChunkCount
|
||||
return doc, nil
|
||||
default:
|
||||
return headDoc{}, fmt.Errorf("chunkstore: unsupported HEAD format %d", discriminator.Format)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// One segment spans a fixed logical GiB. This is a format constant, not a knob.
|
||||
const manifestSegmentBytes uint64 = 1 << 30
|
||||
const maxManifestBytes = 64 << 20
|
||||
|
||||
type segmentDoc struct {
|
||||
Format int `json:"format"`
|
||||
Range uint64 `json:"range"`
|
||||
ChunkBytes uint64 `json:"chunk_bytes"`
|
||||
Owner string `json:"owner"`
|
||||
Chunks map[uint64]storage.ChunkRef `json:"chunks"`
|
||||
}
|
||||
|
||||
func qualifyManifestKey(owner, key string) string {
|
||||
if strings.HasPrefix(key, "@") {
|
||||
return key
|
||||
}
|
||||
return "@" + owner + "/" + key
|
||||
}
|
||||
|
||||
func manifestCount(h storage.ChunkHead) int {
|
||||
if h.Segments != nil {
|
||||
return h.ManifestChunkCount
|
||||
}
|
||||
return len(h.Chunks)
|
||||
}
|
||||
|
||||
func validateRoot(h storage.ChunkHead) error {
|
||||
if h.ChunkBytes < 4096 || h.ChunkBytes > manifestSegmentBytes || manifestSegmentBytes%h.ChunkBytes != 0 || h.ManifestChunkCount < 0 {
|
||||
return errors.New("chunkstore: invalid manifest geometry/count")
|
||||
}
|
||||
count := 0
|
||||
for group, ref := range h.Segments {
|
||||
if CheckVolumeID(ref.Owner) != nil || storage.ValidChunkKey(ref.Key) != nil || ref.Count <= 0 || uint64(ref.Count) > manifestSegmentBytes/h.ChunkBytes || group > ^uint64(0)/(manifestSegmentBytes/h.ChunkBytes) {
|
||||
return errors.New("chunkstore: invalid segment reference")
|
||||
}
|
||||
count += ref.Count
|
||||
}
|
||||
if h.State == storage.ChunkHeadAborted && len(h.Segments) != 0 {
|
||||
return errors.New("chunkstore: aborted HEAD contains segments")
|
||||
}
|
||||
if count != h.ManifestChunkCount {
|
||||
return errors.New("chunkstore: manifest count mismatch")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PrepareManifest never changes generation/epoch or publishes the root. All
|
||||
// segment keys are protected before their Put; the cut owns returned intents.
|
||||
func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.ChunkHead, chunkBytes uint64) (storage.ChunkHead, []string, error) {
|
||||
next.ChunkBytes = chunkBytes
|
||||
next.ManifestChunkCount = len(next.Chunks)
|
||||
next.Segments = map[uint64]storage.ChunkSegment{}
|
||||
if chunkBytes < 4096 || chunkBytes > manifestSegmentBytes || manifestSegmentBytes%chunkBytes != 0 {
|
||||
return next, nil, errors.New("chunkstore: invalid segment geometry")
|
||||
}
|
||||
per := manifestSegmentBytes / chunkBytes
|
||||
owner := path.Base(r.root)
|
||||
groups := map[uint64]map[uint64]storage.ChunkRef{}
|
||||
canonical := make(map[uint64]storage.ChunkRef, len(next.Chunks))
|
||||
for idx, ref := range next.Chunks {
|
||||
ref.Key = qualifyManifestKey(owner, ref.Key)
|
||||
canonical[idx] = ref
|
||||
group := idx / per
|
||||
if groups[group] == nil {
|
||||
groups[group] = map[uint64]storage.ChunkRef{}
|
||||
}
|
||||
groups[group][idx] = ref
|
||||
}
|
||||
next.Chunks = canonical
|
||||
type upload struct {
|
||||
key string
|
||||
data []byte
|
||||
}
|
||||
var uploads []upload
|
||||
for group, chunks := range groups {
|
||||
old := map[uint64]storage.ChunkRef{}
|
||||
for idx, ref := range base.Chunks {
|
||||
if idx/per == group {
|
||||
ref.Key = qualifyManifestKey(owner, ref.Key)
|
||||
old[idx] = ref
|
||||
}
|
||||
}
|
||||
if previous, ok := base.Segments[group]; ok && base.ChunkBytes == chunkBytes && reflect.DeepEqual(chunks, old) {
|
||||
next.Segments[group] = previous
|
||||
continue
|
||||
}
|
||||
body, err := json.Marshal(segmentDoc{1, group, chunkBytes, owner, chunks})
|
||||
if err != nil {
|
||||
return next, nil, err
|
||||
}
|
||||
if len(body) > maxManifestBytes {
|
||||
return next, nil, errors.New("chunkstore: manifest too large")
|
||||
}
|
||||
nonce := make([]byte, 16)
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
return next, nil, err
|
||||
}
|
||||
key := fmt.Sprintf("seg/%x", nonce)
|
||||
next.Segments[group] = storage.ChunkSegment{Key: qualifyManifestKey(owner, key), SHA256: sha256.Sum256(body), Owner: owner, Count: len(chunks)}
|
||||
uploads = append(uploads, upload{key, body})
|
||||
}
|
||||
if err := validateRoot(next); err != nil {
|
||||
return next, nil, err
|
||||
}
|
||||
if len(uploads) == 0 {
|
||||
return next, nil, nil
|
||||
}
|
||||
keys := make([]string, len(uploads))
|
||||
for i, u := range uploads {
|
||||
keys[i] = u.key
|
||||
}
|
||||
id, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: base.Gen, Epoch: next.Epoch, Holder: next.Holder, Keys: keys})
|
||||
if err != nil {
|
||||
return next, nil, err
|
||||
}
|
||||
ids := []string{id}
|
||||
for _, u := range uploads {
|
||||
if err := r.putObject(ctx, u.key, u.data, "segment"); err != nil {
|
||||
return next, ids, err
|
||||
}
|
||||
}
|
||||
return next, ids, nil
|
||||
}
|
||||
|
||||
func (r *ChunkRemote) resolveManifest(ctx context.Context, h storage.ChunkHead) (storage.ChunkHead, error) {
|
||||
if h.Segments == nil {
|
||||
return h, nil
|
||||
}
|
||||
if err := validateRoot(h); err != nil {
|
||||
return h, err
|
||||
}
|
||||
h.Chunks = map[uint64]storage.ChunkRef{}
|
||||
for group, ref := range h.Segments {
|
||||
body, err := r.Get(ctx, ref.Key)
|
||||
if err != nil {
|
||||
return h, fmt.Errorf("chunkstore: read published segment: %w", err)
|
||||
}
|
||||
if len(body) > maxManifestBytes || sha256.Sum256(body) != ref.SHA256 {
|
||||
return h, errors.New("chunkstore: segment hash/size mismatch")
|
||||
}
|
||||
var doc segmentDoc
|
||||
if err := decodeManifestJSON(body, &doc); err != nil {
|
||||
return h, err
|
||||
}
|
||||
if doc.Format != 1 || doc.Range != group || doc.ChunkBytes != h.ChunkBytes || doc.Owner != ref.Owner || len(doc.Chunks) != ref.Count {
|
||||
return h, errors.New("chunkstore: invalid segment contents")
|
||||
}
|
||||
for idx, cr := range doc.Chunks {
|
||||
if idx/(manifestSegmentBytes/h.ChunkBytes) != group || storage.ValidChunkKey(cr.Key) != nil {
|
||||
return h, errors.New("chunkstore: segment index/key invalid")
|
||||
}
|
||||
cr.Key = qualifyManifestKey(ref.Owner, cr.Key)
|
||||
h.Chunks[idx] = cr
|
||||
}
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// Reject duplicate object keys instead of accepting a last-wins manifest.
|
||||
func decodeManifestJSON(body []byte, out any) error {
|
||||
if len(body) > maxManifestBytes {
|
||||
return errors.New("chunkstore: manifest exceeds byte bound")
|
||||
}
|
||||
d := json.NewDecoder(bytes.NewReader(body))
|
||||
var value func(int) error
|
||||
value = func(depth int) error {
|
||||
if depth > 8 {
|
||||
return errors.New("chunkstore: manifest nesting exceeds bound")
|
||||
}
|
||||
tok, err := d.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
delim, ok := tok.(json.Delim)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
switch delim {
|
||||
case '{':
|
||||
keys := map[string]bool{}
|
||||
for d.More() {
|
||||
t, err := d.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
k, ok := t.(string)
|
||||
if !ok || keys[k] {
|
||||
return errors.New("chunkstore: duplicate manifest key")
|
||||
}
|
||||
keys[k] = true
|
||||
if err := value(depth + 1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err = d.Token()
|
||||
return err
|
||||
case '[':
|
||||
for d.More() {
|
||||
if err := value(depth + 1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err = d.Token()
|
||||
return err
|
||||
default:
|
||||
return errors.New("chunkstore: invalid manifest delimiter")
|
||||
}
|
||||
}
|
||||
if err := value(0); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := d.Token(); err != io.EOF {
|
||||
return errors.New("chunkstore: trailing manifest bytes")
|
||||
}
|
||||
return json.Unmarshal(body, out)
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
//go:build manifest_perf
|
||||
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// File-backed proxy: every immutable object is written and fsynced. Metadata
|
||||
// RPCs use the deterministic filer model; results exclude network/guest fsync.
|
||||
type manifestFiles struct{ dir string }
|
||||
|
||||
func (b manifestFiles) Put(ctx context.Context, data []byte) (string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
f, err := os.CreateTemp(b.dir, "blob-")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err = f.Write(data); err == nil {
|
||||
err = f.Sync()
|
||||
}
|
||||
cerr := f.Close()
|
||||
if err == nil {
|
||||
err = cerr
|
||||
}
|
||||
return filepath.Base(f.Name()), err
|
||||
}
|
||||
func (b manifestFiles) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return os.ReadFile(filepath.Join(b.dir, key))
|
||||
}
|
||||
|
||||
func TestManifestPerf_64DirtyChunks(t *testing.T) {
|
||||
for rep := 0; rep < 3; rep++ {
|
||||
order := []int{1, 8}
|
||||
if rep%2 == 1 {
|
||||
order = []int{8, 1}
|
||||
}
|
||||
for _, parallel := range order {
|
||||
dir := t.TempDir()
|
||||
f := newFakeFiler()
|
||||
b := manifestFiles{dir}
|
||||
r, err := NewChunkRemote(f, b, "/chunks/v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := storage.CreateWALStore(filepath.Join(dir, "store"), 64*1024, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 1024, Epoch: 1, Holder: "h1", FreshFromHead: true, UploadConcurrency: parallel, Bitmap: storage.NewFileChunkBitmapStore(filepath.Join(dir, "bitmap"))})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 64; i++ {
|
||||
if _, err = s.Write(uint32(i*1024), bytes.Repeat([]byte{byte(i + 1)}, 4096)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
start := time.Now()
|
||||
if _, err = s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
syncTime := time.Since(start)
|
||||
start = time.Now()
|
||||
if _, err = l.Capture(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cutTime := time.Since(start)
|
||||
t.Logf("PERF dirty64 rep=%d parallel=%d chunk_bytes=4194304 upload_bytes=268435456 sync_ms=%.3f cut_ms=%.3f", rep, parallel, float64(syncTime.Microseconds())/1000, float64(cutTime.Microseconds())/1000)
|
||||
if err = s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifestPerf_Written10GiBSnapshotFork(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f := newFakeFiler()
|
||||
c := newCat(t, f)
|
||||
b := manifestFiles{t.TempDir()}
|
||||
if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v1", IsDirectory: true}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.EnsureVolume(ctx, "v1", Geometry{NumBlocks: 10 * 1024 * 1024 * 1024 / 4096, BlockSize: 4096, ChunkBlocks: 1024}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
|
||||
h, _ := r.GetHead(ctx)
|
||||
next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}}
|
||||
keys := make([]string, 2560)
|
||||
for i := range keys {
|
||||
keys[i] = fmt.Sprintf("data/%d", i)
|
||||
}
|
||||
intent, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: h.Gen, Epoch: 1, Holder: "h1", Keys: keys})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := bytes.Repeat([]byte{0xa5}, 4<<20)
|
||||
start := time.Now()
|
||||
for i, key := range keys {
|
||||
binary.LittleEndian.PutUint64(data, uint64(i))
|
||||
if err := r.Put(ctx, key, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next.Chunks[uint64(i)] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)}
|
||||
}
|
||||
gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next.Gen = gen
|
||||
if err = r.DeleteIntent(ctx, intent); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("PERF materialized_bytes=10737418240 chunks=2560 upload_ms=%.3f", float64(time.Since(start).Microseconds())/1000)
|
||||
for _, format := range []string{"flat", "segmented"} {
|
||||
if format == "segmented" {
|
||||
prepared, ids, err := r.PrepareManifest(ctx, next, next, 4<<20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: next.Gen, Epoch: next.Epoch}, prepared)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prepared.Gen = gen
|
||||
next = prepared
|
||||
for _, id := range ids {
|
||||
if err = r.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
entry, err := headEntry(next)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
segmentBytes := 0
|
||||
for _, ref := range next.Segments {
|
||||
body, err := r.Get(ctx, ref.Key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
segmentBytes += len(body)
|
||||
}
|
||||
for rep := 0; rep < 3; rep++ {
|
||||
name := fmt.Sprintf("%s-%d", format, rep)
|
||||
start := time.Now()
|
||||
snap, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: name, RequestID: name}, next)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snapTime := time.Since(start)
|
||||
target := "fork-" + name
|
||||
if err = f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: target, IsDirectory: true}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start = time.Now()
|
||||
if _, err = c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: name, Target: target, RequestID: target}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
forkTime := time.Since(start)
|
||||
t.Logf("PERF written10GiB format=%s rep=%d head_bytes=%d total_segment_bytes=%d snapshot_entry_bytes=%d snapshot_ms=%.3f fork_ms=%.3f", format, rep, len(entry.Content), segmentBytes, snap.ManifestBytes, float64(snapTime.Microseconds())/1000, float64(forkTime.Microseconds())/1000)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type manifestFilerBlobs struct {
|
||||
Filer
|
||||
Blobs
|
||||
}
|
||||
|
||||
func TestManifest_MixedRepresentationRefusesReadAndWholeGC(t *testing.T) {
|
||||
for _, format := range []int{1, 2} {
|
||||
t.Run(string(rune('0'+format)), func(t *testing.T) {
|
||||
f, b, c, g, now := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
r, _ := publishSegmented(t, f, b)
|
||||
if err := r.Put(ctx, "eligible-orphan", []byte("keep on mark error")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := g.Run(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
*now = now.Add(2 * time.Hour)
|
||||
e, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var doc map[string]json.RawMessage
|
||||
if err = json.Unmarshal(e.Content, &doc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if format == 1 {
|
||||
doc["format"] = json.RawMessage("1")
|
||||
} else {
|
||||
doc["chunks"] = json.RawMessage("{}")
|
||||
}
|
||||
e.Content, err = json.Marshal(doc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h, err := r.GetHead(ctx); err == nil {
|
||||
t.Errorf("mixed root returned readable image (possibly zeros): %+v", h)
|
||||
}
|
||||
if h, _, err := c.ReadHead(ctx, "v1"); err == nil {
|
||||
t.Errorf("catalog accepted mixed root: %+v", h)
|
||||
}
|
||||
_, _, before := b.counts()
|
||||
for _, apply := range []bool{false, true} {
|
||||
if _, err := g.run(ctx, apply); err == nil {
|
||||
t.Errorf("mixed root accepted by GC apply=%v", apply)
|
||||
}
|
||||
}
|
||||
_, _, after := b.counts()
|
||||
if before != after {
|
||||
t.Fatal("failed mark deleted objects")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifest_UsageCountsOwnedClippedChunksAndForkHolders(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f := newFakeFiler()
|
||||
b := gcBlobs{newFakeBlobs()}
|
||||
c, err := NewCatalog(manifestFilerBlobs{f, b}, catBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, vol := range []string{"v1", "v2"} {
|
||||
if err = f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err = c.EnsureVolume(ctx, "v1", Geometry{NumBlocks: 10, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, h := publishSegmented(t, f, b)
|
||||
if _, err = c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s", RequestID: "snapshot"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, err := c.Usage(ctx, "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u.LiveChunks != 2 || u.LiveBytes != 40960 || len(u.Snapshots) != 1 || u.Snapshots[0].Chunks != 2 || u.Snapshots[0].ExclusiveBytes != 0 {
|
||||
t.Fatalf("segmented clipped usage: %+v", u)
|
||||
}
|
||||
segmentBytes := uint64(0)
|
||||
for _, ref := range h.Segments {
|
||||
body, e := r.Get(ctx, ref.Key)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
segmentBytes += uint64(len(body))
|
||||
}
|
||||
if u.ManifestBindings != 1 || u.ManifestBytes != segmentBytes || u.StoredBytes != 40960+segmentBytes || u.StoredUpperBound {
|
||||
t.Fatalf("manifest bytes must not be charged as a full data chunk: %+v", u)
|
||||
}
|
||||
if _, err = c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s", Target: "v2", RequestID: "fork"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, err = c.Usage(ctx, "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u.LiveChunks != 0 || u.Snapshots[0].Chunks != 2 || u.Snapshots[0].ExclusiveBytes != 0 {
|
||||
t.Fatalf("foreign fork owner omitted: %+v", u)
|
||||
}
|
||||
fork, _ := NewChunkRemote(f, b, path.Join(catBase, "v2"))
|
||||
fh, err := fork.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = fork.CASHead(ctx, storage.ChunkHeadVersion{Gen: fh.Gen, Epoch: fh.Epoch}, storage.ChunkHead{RemoteLSN: fh.RemoteLSN}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, err = c.Usage(ctx, "v1")
|
||||
if err != nil || u.Snapshots[0].ExclusiveBytes != 40960 {
|
||||
t.Fatalf("snapshot exclusivity must use clipped owner bytes: %+v %v", u, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifest_RejectsFieldAliases(t *testing.T) {
|
||||
for _, field := range []string{`"segments":null`, `"Segments":null`, `"CHUNK_BYTES":0`, `"chunk_count":0`} {
|
||||
body := []byte(`{"format":1,"gen":1,"epoch":1,"holder":"h","chunks":{},` + field + `}`)
|
||||
if _, err := DecodeHeadDocument("mixed", body); err == nil {
|
||||
t.Errorf("format1 accepted residual field %s", field)
|
||||
}
|
||||
}
|
||||
for _, field := range []string{`"chunks":{}`, `"Chunks":null`} {
|
||||
body := []byte(`{"format":2,"gen":1,"epoch":1,"holder":"h","chunk_bytes":32768,"chunk_count":0,"segments":{},` + field + `}`)
|
||||
if _, err := DecodeHeadDocument("mixed", body); err == nil {
|
||||
t.Errorf("format2 accepted residual field %s", field)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifest_FormatSpecificFoldedFields(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
format int
|
||||
name string
|
||||
}{{1, "segments"}, {1, "chunk_bytes"}, {1, "chunk_count"}, {2, "chunks"}} {
|
||||
variants := map[string]bool{tc.name: true, strings.ToUpper(tc.name): true}
|
||||
original := []rune(tc.name)
|
||||
for i, r := range original {
|
||||
for folded := unicode.SimpleFold(r); folded != r; folded = unicode.SimpleFold(folded) {
|
||||
key := append([]rune(nil), original...)
|
||||
key[i] = folded
|
||||
variants[string(key)] = true
|
||||
}
|
||||
}
|
||||
for key := range variants {
|
||||
encoded, _ := json.Marshal(key)
|
||||
suffix := string(encoded) + `:null`
|
||||
root := `{"format":1,"gen":1,"epoch":1,"holder":"h",` + suffix + `}`
|
||||
if tc.format == 2 {
|
||||
root = `{"format":2,"gen":1,"epoch":1,"holder":"h","chunk_bytes":32768,"segments":{},` + suffix + `}`
|
||||
}
|
||||
if _, err := DecodeHeadDocument("folded", []byte(root)); err == nil {
|
||||
t.Errorf("format%d accepted folded residual %s", tc.format, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, root := range []string{
|
||||
`{"format":1,"gen":1,"epoch":1,"holder":"h","\u017fegments":null}`,
|
||||
`{"format":2,"gen":1,"epoch":1,"holder":"h","chunk_bytes":32768,"segments":{},"chun\u212as":null}`,
|
||||
} {
|
||||
if _, err := DecodeHeadDocument("escaped", []byte(root)); err == nil {
|
||||
t.Errorf("accepted escaped mixed root: %s", root)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifest_LongSDiscriminatorCorruptionRefusesReadAndGC(t *testing.T) {
|
||||
f, b, c, g, now := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
r, _ := publishSegmented(t, f, b)
|
||||
if err := r.Put(ctx, "orphan", []byte("do not delete after bad mark")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := g.Run(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
*now = now.Add(2 * time.Hour)
|
||||
e, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err = json.Unmarshal(e.Content, &fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fields["format"] = json.RawMessage("1")
|
||||
fields["\u017fegments"] = fields["segments"]
|
||||
delete(fields, "segments")
|
||||
delete(fields, "chunk_bytes")
|
||||
delete(fields, "chunk_count")
|
||||
e.Content, err = json.Marshal(fields)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h, err := r.GetHead(ctx); err == nil {
|
||||
t.Errorf("Unicode mixed root became readable empty image: %+v", h)
|
||||
}
|
||||
if h, _, err := c.ReadHead(ctx, "v1"); err == nil {
|
||||
t.Errorf("catalog accepted Unicode mixed root: %+v", h)
|
||||
}
|
||||
_, _, before := b.counts()
|
||||
for _, apply := range []bool{false, true} {
|
||||
if _, err := g.run(ctx, apply); err == nil {
|
||||
t.Errorf("Unicode mixed root accepted by GC apply=%v", apply)
|
||||
}
|
||||
}
|
||||
_, _, after := b.counts()
|
||||
if before != after {
|
||||
t.Fatal("Unicode mixed root allowed partial delete")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestManifest_CapturePublishesSegmentRoot(t *testing.T) {
|
||||
f, b, _, _, _ := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
r, err := NewChunkRemote(f, b, path.Join(catBase, "v1"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := filepath.Join(t.TempDir(), "volume")
|
||||
s, err := storage.CreateWALStore(p, 64, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
if _, err = s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true, Bitmap: storage.NewFileChunkBitmapStore(p + ".bitmap")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := bytes.Repeat([]byte{0x61}, 4096)
|
||||
if _, err = s.Write(0, want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = l.Capture(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e, err := f.LookupEntry(ctx, path.Join(catBase, "v1"), headName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var doc struct {
|
||||
Format int `json:"format"`
|
||||
Chunks map[string]any `json:"chunks"`
|
||||
Segments map[string]any `json:"segments"`
|
||||
}
|
||||
if err = json.Unmarshal(e.Content, &doc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if doc.Format != 2 || len(doc.Chunks) != 0 || len(doc.Segments) != 1 {
|
||||
t.Fatalf("cut did not publish a small segmented root: %s", e.Content)
|
||||
}
|
||||
h, err := r.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := r.Get(ctx, h.Chunks[0].Key)
|
||||
if err != nil || !bytes.Equal(data[:4096], want) {
|
||||
t.Fatalf("resolved cut bytes: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func publishSegmented(t *testing.T, f *fakeFiler, b gcBlobs) (*ChunkRemote, storage.ChunkHead) {
|
||||
t.Helper()
|
||||
h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41), 1: chunkBytes(0x42)})
|
||||
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
|
||||
next, ids, err := r.PrepareManifest(context.Background(), h, h, 32768)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gen, err := r.CASHead(context.Background(), storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next.Gen = gen
|
||||
for _, id := range ids {
|
||||
if err = r.DeleteIntent(context.Background(), id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return r, next
|
||||
}
|
||||
|
||||
func TestManifest_ForkAfterParentSnapshotDelete(t *testing.T) {
|
||||
f, b, c, g, now := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
r, h := publishSegmented(t, f, b)
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fork, _ := NewChunkRemote(f, b, path.Join(catBase, "v2"))
|
||||
fh, err := fork.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fh.Segments) != 1 || len(fh.Chunks) != 2 {
|
||||
t.Fatalf("fork lost root/children: %+v", fh)
|
||||
}
|
||||
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
if _, err := g.Run(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
*now = now.Add(2 * time.Hour)
|
||||
}
|
||||
fh, err = fork.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for idx, ref := range fh.Chunks {
|
||||
got, err := fork.Get(ctx, ref.Key)
|
||||
if err != nil || !bytes.Equal(got, chunkBytes(byte(0x41+idx))) {
|
||||
t.Fatalf("fork lost shared chunk %d after parent delete: %v", idx, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifest_GCReadsPublishedSegments(t *testing.T) {
|
||||
f, b, _, g, _ := gcFixture(t)
|
||||
publishSegmented(t, f, b)
|
||||
out, err := g.Preview(context.Background())
|
||||
if err != nil || len(out.Roots) == 0 {
|
||||
t.Fatalf("GC cannot trace published segment: %+v %v", out, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot(t *testing.T) {
|
||||
f, b, _, _, _ := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
r, h := publishSegmented(t, f, b)
|
||||
// A second logical GiB uses a different immutable range; no local 1GiB
|
||||
// allocation is needed to exercise remote manifest publication.
|
||||
per := manifestSegmentBytes / h.ChunkBytes
|
||||
key := "second-range"
|
||||
data := chunkBytes(0x77)
|
||||
if err := r.Put(ctx, key, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Chunks[per] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)}
|
||||
next, ids, err := r.PrepareManifest(ctx, h, h, h.ChunkBytes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if next.Segments[0] != h.Segments[0] {
|
||||
t.Fatal("unchanged range rewritten")
|
||||
}
|
||||
// Simulate death after immutable upload, with no CAS or cleanup.
|
||||
old, err := r.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(old.Chunks) != 2 || len(old.Segments) != 1 {
|
||||
t.Fatal("unpublished segment changed old root")
|
||||
}
|
||||
intents, err := r.ListIntents(ctx)
|
||||
if err != nil || len(intents) != len(ids) {
|
||||
t.Fatalf("uploaded segment unprotected: %v", err)
|
||||
}
|
||||
for _, ref := range old.Chunks {
|
||||
if _, err := r.Get(ctx, ref.Key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: old.Gen, Epoch: old.Epoch}, next)
|
||||
if err != nil || gen != old.Gen+1 {
|
||||
t.Fatalf("normal CAS semantics: %d %v", gen, err)
|
||||
}
|
||||
|
||||
published, err := r.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
changed := published
|
||||
changed.Chunks = make(map[uint64]storage.ChunkRef, len(published.Chunks))
|
||||
for idx, ref := range published.Chunks {
|
||||
changed.Chunks[idx] = ref
|
||||
}
|
||||
if err = r.Put(ctx, "changed-range-zero", data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
changed.Chunks[0] = storage.ChunkRef{Key: "changed-range-zero", SHA256: sha256.Sum256(data)}
|
||||
rewritten, _, err := r.PrepareManifest(ctx, published, changed, published.ChunkBytes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rewritten.Segments[0] == published.Segments[0] || rewritten.Segments[1] != published.Segments[1] {
|
||||
t.Fatal("cut must rewrite only the changed range")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifest_UnreadablePublishedSegmentRefusesWholeGC(t *testing.T) {
|
||||
for _, apply := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint(apply), func(t *testing.T) {
|
||||
f, b, _, g, now := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
r, h := publishSegmented(t, f, b)
|
||||
if err := r.Put(ctx, "unreachable", []byte("orphan")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := g.Run(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
*now = now.Add(2 * time.Hour)
|
||||
var ref storage.ChunkSegment
|
||||
for _, v := range h.Segments {
|
||||
ref = v
|
||||
break
|
||||
}
|
||||
dir, name, err := r.keyLocation(ref.Key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entry, err := f.LookupEntry(ctx, dir, name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b.mu.Lock()
|
||||
b.data[string(entry.Extended[extFid])] = []byte("corrupted segment")
|
||||
before := len(b.data)
|
||||
b.mu.Unlock()
|
||||
if _, err := g.run(ctx, apply); err == nil {
|
||||
t.Fatal("unreadable published segment accepted")
|
||||
}
|
||||
b.mu.Lock()
|
||||
after := len(b.data)
|
||||
b.mu.Unlock()
|
||||
if before != after {
|
||||
t.Fatal("failed mark partially deleted data")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifest_CopyIntentProtectsChildrenWithoutHead(t *testing.T) {
|
||||
f, b, _, g, now := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
r, h := publishSegmented(t, f, b)
|
||||
if _, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: h.Gen, Epoch: h.Epoch, Holder: "snapshot:v1/unpublished/attempt", Keys: headKeys(h), Segments: h.Segments, ChunkBytes: h.ChunkBytes}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
if out, err := g.Run(ctx); err != nil || out.Reclaimed != 0 {
|
||||
t.Fatalf("copy intent lost transitive children: %+v %v", out, err)
|
||||
}
|
||||
*now = now.Add(2 * time.Hour)
|
||||
}
|
||||
for _, ref := range h.Chunks {
|
||||
if _, err := r.Get(ctx, ref.Key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifest_NoopFlatUpgradeUsesOneNormalGeneration(t *testing.T) {
|
||||
f, b, _, _, _ := gcFixture(t)
|
||||
ctx := context.Background()
|
||||
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
|
||||
old, err := r.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := filepath.Join(t.TempDir(), "store")
|
||||
s, err := storage.CreateWALStore(p, 64, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
if _, err = s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 1, Holder: "h1", FreshFromHead: true, Bitmap: storage.NewFileChunkBitmapStore(p + ".bitmap")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = l.Capture(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := r.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h.Segments == nil || h.Gen != old.Gen+1 || h.Epoch != 1 || h.RemoteLSN != old.RemoteLSN {
|
||||
t.Fatalf("upgrade changed normal-cut lineage: old=%+v new=%+v", old, h)
|
||||
}
|
||||
if _, err = l.Capture(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, err := r.GetHead(ctx)
|
||||
if err != nil || again.Gen != h.Gen || again.Epoch != h.Epoch {
|
||||
t.Fatalf("second no-op advanced lineage: %+v %v", again, err)
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,8 @@ import (
|
||||
)
|
||||
|
||||
// Space accounting (claude05's rulings, 2026-11-15 22:53Z). Everything is
|
||||
// computed from manifests and filer listings; no chunk data is read.
|
||||
// computed from manifests and filer listings; segment objects are verified,
|
||||
// but data chunks are not read.
|
||||
//
|
||||
// A chunk's bytes are ChunkBlocks x BlockSize, the last chunk clipped to
|
||||
// NumBlocks (ChunkRef carries no size).
|
||||
@@ -52,6 +53,8 @@ type VolumeUsage struct {
|
||||
LiveChunks int `json:"liveChunks"`
|
||||
LiveBytes uint64 `json:"liveBytes"`
|
||||
Snapshots []SnapshotUsage `json:"snapshots"`
|
||||
ManifestBindings int `json:"manifestBindings"`
|
||||
ManifestBytes uint64 `json:"manifestBytes"`
|
||||
StoredBindings int `json:"storedBindings"`
|
||||
StoredBytes uint64 `json:"storedBytes"`
|
||||
StoredUpperBound bool `json:"storedUpperBound"`
|
||||
@@ -99,6 +102,16 @@ func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) {
|
||||
return VolumeUsage{}, err
|
||||
}
|
||||
|
||||
head, err = c.usageHead(ctx, vol, head)
|
||||
if err != nil {
|
||||
return VolumeUsage{}, err
|
||||
}
|
||||
for i := range snaps {
|
||||
snaps[i].head, err = c.usageHead(ctx, vol, snaps[i].head)
|
||||
if err != nil {
|
||||
return VolumeUsage{}, err
|
||||
}
|
||||
}
|
||||
// holders counts, per chunk identity (owner volume + key), how many
|
||||
// HEADs and live snapshots of any volume reference it; size is each
|
||||
// identity's byte size as this volume's geometry indexes it.
|
||||
@@ -138,6 +151,10 @@ func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) {
|
||||
return VolumeUsage{}, err
|
||||
}
|
||||
if has {
|
||||
oh, err = c.usageHead(ctx, other, oh)
|
||||
if err != nil {
|
||||
return VolumeUsage{}, err
|
||||
}
|
||||
addHolder(other, oh, false)
|
||||
}
|
||||
osnaps, err := c.allSnapshots(ctx, other)
|
||||
@@ -145,7 +162,11 @@ func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) {
|
||||
return VolumeUsage{}, err
|
||||
}
|
||||
for _, s := range osnaps {
|
||||
addHolder(other, s.Head(), false)
|
||||
otherHead, err := c.usageHead(ctx, other, s.Head())
|
||||
if err != nil {
|
||||
return VolumeUsage{}, err
|
||||
}
|
||||
addHolder(other, otherHead, false)
|
||||
}
|
||||
}
|
||||
for _, s := range snaps {
|
||||
@@ -194,6 +215,16 @@ func (c *Catalog) Usage(ctx context.Context, vol string) (VolumeUsage, error) {
|
||||
continue
|
||||
}
|
||||
u.StoredBindings++
|
||||
if string(e.Extended["swb.object"]) == "segment" {
|
||||
if e.Attributes == nil || e.Attributes.FileSize == 0 || e.Attributes.FileSize > maxManifestBytes {
|
||||
return VolumeUsage{}, errors.New("chunkstore: invalid manifest binding size")
|
||||
}
|
||||
u.ManifestBindings++
|
||||
u.ManifestBytes += e.Attributes.FileSize
|
||||
u.StoredBytes += e.Attributes.FileSize
|
||||
continue
|
||||
}
|
||||
|
||||
if n, ok := size[chunkIdentity(vol, key)]; ok {
|
||||
u.StoredBytes += n
|
||||
} else {
|
||||
@@ -218,3 +249,34 @@ func chunkIdentity(vol, key string) string {
|
||||
}
|
||||
return vol + "\x00" + key
|
||||
}
|
||||
|
||||
func (c *Catalog) usageHead(ctx context.Context, vol string, h storage.ChunkHead) (storage.ChunkHead, error) {
|
||||
if h.Segments == nil {
|
||||
return h, nil
|
||||
}
|
||||
var blobs Blobs = c.blobs
|
||||
if blobs == nil {
|
||||
return h, errors.New("chunkstore: usage segment reader unavailable")
|
||||
}
|
||||
r, err := NewChunkRemote(c.f, blobs, path.Join(c.base, vol))
|
||||
if err != nil {
|
||||
return h, err
|
||||
}
|
||||
resolved, err := r.resolveManifest(ctx, h)
|
||||
if err != nil {
|
||||
return h, err
|
||||
}
|
||||
v, ok, err := c.ReadVolume(ctx, vol)
|
||||
if err != nil {
|
||||
return h, err
|
||||
}
|
||||
if !ok || h.ChunkBytes != uint64(v.Geometry.ChunkBlocks)*uint64(v.Geometry.BlockSize) {
|
||||
return h, errors.New("chunkstore: usage manifest/volume geometry mismatch")
|
||||
}
|
||||
for idx := range resolved.Chunks {
|
||||
if idx >= (v.Geometry.NumBlocks+uint64(v.Geometry.ChunkBlocks)-1)/uint64(v.Geometry.ChunkBlocks) {
|
||||
return h, errors.New("chunkstore: usage chunk outside volume")
|
||||
}
|
||||
}
|
||||
return resolved, nil
|
||||
}
|
||||
@@ -152,6 +152,8 @@ type ProviderConfig struct {
|
||||
// cuts are published only by CaptureVolume, MakeVolumeRemoteDurable
|
||||
// (snapshot, detach) and the timer. Zero: unbounded.
|
||||
ChunkDirtyThreshold int
|
||||
// ChunkUploadConcurrency bounds remote uploads; zero defaults to 8.
|
||||
ChunkUploadConcurrency int
|
||||
}
|
||||
|
||||
// DurableProvider is the production frontend.Provider implementation.
|
||||
|
||||
@@ -255,17 +255,22 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
|
||||
if holder == "" {
|
||||
holder = proj.ReplicaID
|
||||
}
|
||||
remote := &closeBoundRemote{ChunkRemote: inner, done: p.closeCtx}
|
||||
remote.setAttach(ctx) // the attach's calls also end with the caller's ctx
|
||||
defer remote.setAttach(nil)
|
||||
bound := &closeBoundRemote{ChunkRemote: inner, done: p.closeCtx}
|
||||
bound.setAttach(ctx) // the attach's calls also end with the caller's ctx
|
||||
defer bound.setAttach(nil)
|
||||
var remote storage.ChunkRemote = bound
|
||||
if builder, ok := inner.(storage.ChunkManifestBuilder); ok {
|
||||
remote = &manifestBoundRemote{closeBoundRemote: bound, builder: builder}
|
||||
}
|
||||
cfg := storage.ChunkLayerConfig{
|
||||
ChunkBlocks: p.cfg.ChunkBlocks,
|
||||
Epoch: lin.epoch,
|
||||
Holder: holder,
|
||||
FreshFromHead: h.fresh,
|
||||
ReadMissTimeout: p.cfg.ChunkReadMissTimeout,
|
||||
Bitmap: storage.NewFileChunkBitmapStore(h.path + ".chunkbitmap"),
|
||||
BarrierBound: p.cfg.ChunkDirtyThreshold,
|
||||
ChunkBlocks: p.cfg.ChunkBlocks,
|
||||
Epoch: lin.epoch,
|
||||
Holder: holder,
|
||||
FreshFromHead: h.fresh,
|
||||
ReadMissTimeout: p.cfg.ChunkReadMissTimeout,
|
||||
Bitmap: storage.NewFileChunkBitmapStore(h.path + ".chunkbitmap"),
|
||||
BarrierBound: p.cfg.ChunkDirtyThreshold,
|
||||
UploadConcurrency: p.cfg.ChunkUploadConcurrency,
|
||||
CaptureAllowed: func() error {
|
||||
cur := p.view.Projection()
|
||||
if !cur.Healthy || cur.VolumeID != volumeID || lin.volumeID != volumeID {
|
||||
@@ -698,3 +703,16 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st
|
||||
}
|
||||
return r, h.storage.NextLSN() - 1, nil
|
||||
}
|
||||
|
||||
// Preserve the optional manifest capability only when the inner remote has it;
|
||||
// legacy in-memory/flat remotes keep their existing no-op cut behavior.
|
||||
type manifestBoundRemote struct {
|
||||
*closeBoundRemote
|
||||
builder storage.ChunkManifestBuilder
|
||||
}
|
||||
|
||||
func (r *manifestBoundRemote) PrepareManifest(ctx context.Context, base, next storage.ChunkHead, chunkBytes uint64) (storage.ChunkHead, []string, error) {
|
||||
c, end := r.bind(ctx)
|
||||
defer end()
|
||||
return r.builder.PrepareManifest(c, base, next, chunkBytes)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type manifestAwareRemote struct {
|
||||
*storage.MemChunkRemote
|
||||
prepared atomic.Int32
|
||||
}
|
||||
|
||||
func (r *manifestAwareRemote) PrepareManifest(ctx context.Context, base, next storage.ChunkHead, chunkBytes uint64) (storage.ChunkHead, []string, error) {
|
||||
r.prepared.Add(1)
|
||||
return next, nil, ctx.Err()
|
||||
}
|
||||
func TestWALStoreChunk_ProviderPreservesManifestCapability(t *testing.T) {
|
||||
r := &manifestAwareRemote{MemChunkRemote: storage.NewMemChunkRemote()}
|
||||
p := chunkProvider(t, t.TempDir(), r, v1View(), 0)
|
||||
s := openRecovered(t, p)
|
||||
if _, err := s.Write(0, block(0x65)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.prepared.Load() != 1 {
|
||||
t.Fatalf("provider erased remote manifest capability: preparations=%d", r.prepared.Load())
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
)
|
||||
|
||||
// NewWorkspaceHEADReader reads inline HEAD content from the configured filer
|
||||
@@ -63,7 +64,10 @@ func NewWorkspaceHEADReader(base string) (func(context.Context, string) (authori
|
||||
if err := json.Unmarshal(raw, &doc); err != nil {
|
||||
return authority.WorkspaceHead{}, err
|
||||
}
|
||||
if doc.Format != 1 || doc.Gen == 0 || doc.Epoch == 0 || doc.Holder == "" || doc.LegacyDetached != nil || (doc.State != "" && doc.State != "active" && doc.State != "detached") {
|
||||
if _, err := chunkstore.DecodeHeadDocument("workspace/"+volume, raw); err != nil {
|
||||
return authority.WorkspaceHead{}, err
|
||||
}
|
||||
if (doc.Format != 1 && doc.Format != 2) || doc.Gen == 0 || doc.Epoch == 0 || doc.Holder == "" || doc.LegacyDetached != nil || (doc.State != "" && doc.State != "active" && doc.State != "detached") {
|
||||
return authority.WorkspaceHead{}, fmt.Errorf("invalid HEAD identity/state")
|
||||
}
|
||||
// Missing state is the legacy active representation. Only a final-cut
|
||||
|
||||
@@ -5,6 +5,7 @@ package master
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -142,6 +143,14 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("producer HEAD persisted by filer: %s", stored.Content)
|
||||
var root struct {
|
||||
Format int `json:"format"`
|
||||
Segments map[string]json.RawMessage `json:"segments"`
|
||||
}
|
||||
if err = json.Unmarshal(stored.Content, &root); err != nil || root.Format != 2 || len(root.Segments) == 0 {
|
||||
t.Fatalf("CLEAN move must exercise upgraded segmented root: %s %v", stored.Content, err)
|
||||
}
|
||||
|
||||
if _, err = backend.Write(ctx, 0, want); err == nil {
|
||||
t.Fatal("W2 detach left frontend writable")
|
||||
}
|
||||
|
||||
@@ -134,6 +134,12 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
if remote == nil || cfg.Bitmap == nil || cfg.ChunkBlocks == 0 {
|
||||
return nil, errors.New("storage: chunk layer needs a remote, a bitmap store and ChunkBlocks > 0")
|
||||
}
|
||||
if cfg.UploadConcurrency < 0 || cfg.UploadConcurrency > 64 {
|
||||
return nil, errors.New("storage: upload concurrency must be between 1 and 64 (0 defaults to 8)")
|
||||
}
|
||||
if cfg.UploadConcurrency == 0 {
|
||||
cfg.UploadConcurrency = 8
|
||||
}
|
||||
if cfg.ReadMissTimeout <= 0 {
|
||||
cfg.ReadMissTimeout = defaultReadMissTimeout
|
||||
}
|
||||
@@ -260,6 +266,12 @@ func copyHead(h chunkHead) chunkHead {
|
||||
d := *h.DetachedBy
|
||||
out.DetachedBy = &d
|
||||
}
|
||||
if h.Segments != nil {
|
||||
out.Segments = make(map[uint64]ChunkSegment, len(h.Segments))
|
||||
for k, v := range h.Segments {
|
||||
out.Segments[k] = v
|
||||
}
|
||||
}
|
||||
out.Chunks = make(map[uint64]chunkRef, len(h.Chunks))
|
||||
for k, v := range h.Chunks {
|
||||
out.Chunks[k] = v
|
||||
@@ -846,20 +858,36 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
}
|
||||
intents = append(intents, id)
|
||||
}
|
||||
if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error {
|
||||
u := uploads[i]
|
||||
return l.remote.Put(ctx, u.key, u.c.data)
|
||||
}); err != nil {
|
||||
l.abortCut(all)
|
||||
l.dropIntents(ctx, intents)
|
||||
return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w: %w", errChunkRemoteUnavailable, err)
|
||||
}
|
||||
for _, u := range uploads {
|
||||
if err := l.remote.Put(ctx, u.key, u.c.data); err != nil {
|
||||
l.abortCut(all)
|
||||
l.dropIntents(ctx, intents)
|
||||
return chunkCutResult{}, fmt.Errorf("storage: capture upload chunk %d: %w: %w", u.c.idx, errChunkRemoteUnavailable, err)
|
||||
}
|
||||
next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum}
|
||||
newKeys[u.c.idx] = u.key
|
||||
changed = append(changed, u.c.idx)
|
||||
st.UploadedChunks++
|
||||
st.UploadedBytes += int64(len(u.c.data))
|
||||
}
|
||||
upgrade := false
|
||||
if builder, ok := l.remote.(ChunkManifestBuilder); ok {
|
||||
upgrade = baseHead.Segments == nil
|
||||
var ids []string
|
||||
var err error
|
||||
next, ids, err = builder.PrepareManifest(ctx, baseHead, next, uint64(l.blockSize)*l.chunkBlocks)
|
||||
intents = append(intents, ids...)
|
||||
if err != nil {
|
||||
l.abortCut(all)
|
||||
l.dropIntents(ctx, intents)
|
||||
return chunkCutResult{}, err
|
||||
}
|
||||
}
|
||||
st.UploadNs = time.Since(uploadStart).Nanoseconds()
|
||||
if !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) {
|
||||
if !upgrade && !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) {
|
||||
// A no-op cut still observes authority: a fresh host may have
|
||||
// claimed HEAD without uploading a single chunk since our last cut.
|
||||
cur, err := l.remote.GetHead(ctx)
|
||||
@@ -1006,6 +1034,15 @@ func (l *chunkLayerImpl) supersededBy(cur chunkHead) bool {
|
||||
}
|
||||
|
||||
func sameProposal(cur, next chunkHead) bool {
|
||||
if (cur.Segments == nil) != (next.Segments == nil) || cur.ChunkBytes != next.ChunkBytes || cur.ManifestChunkCount != next.ManifestChunkCount || len(cur.Segments) != len(next.Segments) {
|
||||
return false
|
||||
}
|
||||
for k, v := range next.Segments {
|
||||
if cur.Segments[k] != v {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if cur.Epoch != next.Epoch || cur.Holder != next.Holder || cur.RemoteLSN != next.RemoteLSN || len(cur.Chunks) != len(next.Chunks) {
|
||||
return false
|
||||
}
|
||||
@@ -1454,10 +1491,13 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint
|
||||
return nil, intents, fmt.Errorf("storage: capture stage intent: %w: %w", errChunkRemoteUnavailable, err)
|
||||
}
|
||||
intents = append(intents, id)
|
||||
if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error {
|
||||
u := uploads[i]
|
||||
return l.remote.Put(ctx, u.key, u.data)
|
||||
}); err != nil {
|
||||
return nil, intents, fmt.Errorf("storage: capture stage upload: %w: %w", errChunkRemoteUnavailable, err)
|
||||
}
|
||||
for _, u := range uploads {
|
||||
if err := l.remote.Put(ctx, u.key, u.data); err != nil {
|
||||
return nil, intents, fmt.Errorf("storage: capture stage chunk %d: %w: %w", u.idx, errChunkRemoteUnavailable, err)
|
||||
}
|
||||
st.UploadedChunks++
|
||||
st.UploadedBytes += int64(len(u.data))
|
||||
u.data = nil
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package storage
|
||||
|
||||
import "context"
|
||||
|
||||
// ChunkSegment names an immutable range manifest. Owner is the namespace in
|
||||
// which that manifest was encoded; forks preserve it without rewriting data.
|
||||
type ChunkSegment struct {
|
||||
Key string `json:"key"`
|
||||
SHA256 [32]byte `json:"sha256"`
|
||||
Owner string `json:"owner"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
// ChunkManifestBuilder prepares immutable segments before the existing root
|
||||
// CAS. Returned intents belong to the cut and follow its settlement rules.
|
||||
type ChunkManifestBuilder interface {
|
||||
PrepareManifest(context.Context, ChunkHead, ChunkHead, uint64) (ChunkHead, []string, error)
|
||||
}
|
||||
@@ -175,13 +175,16 @@ type chunkHeadVersion struct {
|
||||
// move). Every normal cut publishes State = active and no DetachedBy; a new
|
||||
// holder's takeover does the same.
|
||||
type chunkHead struct {
|
||||
Gen uint64
|
||||
Epoch uint64
|
||||
Holder string
|
||||
RemoteLSN uint64
|
||||
Chunks map[uint64]chunkRef
|
||||
State string
|
||||
DetachedBy *chunkDetachedBy
|
||||
Gen uint64
|
||||
Epoch uint64
|
||||
Holder string
|
||||
RemoteLSN uint64
|
||||
Chunks map[uint64]chunkRef
|
||||
Segments map[uint64]ChunkSegment
|
||||
ChunkBytes uint64
|
||||
ManifestChunkCount int
|
||||
State string
|
||||
DetachedBy *chunkDetachedBy
|
||||
}
|
||||
|
||||
// HEAD states.
|
||||
@@ -240,12 +243,14 @@ type chunkRemote interface {
|
||||
// chunkIntent is one live intent: the keys a holder at HEAD generation Gen
|
||||
// and epoch Epoch is about to publish.
|
||||
type chunkIntent struct {
|
||||
ID string // "<Gen>-<nonce>"; assigned by PutIntent
|
||||
Gen uint64
|
||||
Epoch uint64
|
||||
Holder string
|
||||
Keys []string
|
||||
CreatedNs int64 // assigned by PutIntent
|
||||
Segments map[uint64]ChunkSegment
|
||||
ChunkBytes uint64
|
||||
ID string // "<Gen>-<nonce>"; assigned by PutIntent
|
||||
Gen uint64
|
||||
Epoch uint64
|
||||
Holder string
|
||||
Keys []string
|
||||
CreatedNs int64 // assigned by PutIntent
|
||||
// DeadlineNs (unix ns) is a copy intent's publication deadline, kept as
|
||||
// metadata: a GC sweep settles a dead copy attempt by claiming its
|
||||
// publishing entry with a tombstone, never by the deadline alone (W5
|
||||
@@ -333,6 +338,9 @@ type chunkLayerConfig struct {
|
||||
// Zero: unbounded, no staging.
|
||||
BarrierBound int
|
||||
|
||||
// UploadConcurrency bounds capture/pre-copy Put calls (0 defaults to 8).
|
||||
UploadConcurrency int
|
||||
|
||||
// testReconcileHold, set only by this package's tests, holds the
|
||||
// reconciler before each slice until a token is received or the
|
||||
// channel is closed.
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// uploadBatch owns and joins all Put calls before its caller settles intents.
|
||||
// No storage/publication lock is acquired by workers. Cancellation stops new
|
||||
// admission; a remote ignoring cancellation remains joined, never declared done.
|
||||
func (l *chunkLayerImpl) uploadBatch(ctx context.Context, n int, put func(context.Context, int) error) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
var mu sync.Mutex
|
||||
next := 0
|
||||
var first error
|
||||
var wg sync.WaitGroup
|
||||
workers := min(l.cfg.UploadConcurrency, n)
|
||||
for j := 0; j < workers; j++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
mu.Lock()
|
||||
if first != nil || next == n || ctx.Err() != nil {
|
||||
mu.Unlock()
|
||||
return
|
||||
}
|
||||
i := next
|
||||
next++
|
||||
mu.Unlock()
|
||||
if err := put(ctx, i); err != nil {
|
||||
mu.Lock()
|
||||
if first == nil {
|
||||
first = err
|
||||
cancel()
|
||||
}
|
||||
mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if first != nil {
|
||||
return first
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestChunkUploads_DefaultOverlapsBeforeCAS(t *testing.T) {
|
||||
_, f, l, w := precopyLayer(t, 0, 3)
|
||||
f.mu.Lock()
|
||||
f.putGate = make(chan struct{})
|
||||
gate := f.putGate
|
||||
f.putEntered = make(chan string, 8)
|
||||
entered := f.putEntered
|
||||
f.mu.Unlock()
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := l.Cut(context.Background()); done <- err }()
|
||||
defer func() {
|
||||
close(gate)
|
||||
if err := <-done; err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
for i := 0; i < 2; i++ {
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatalf("only %d upload calls entered before release; default uploads must overlap", i)
|
||||
}
|
||||
}
|
||||
f.mu.Lock()
|
||||
if len(f.intents) == 0 || f.casCalls != 0 {
|
||||
t.Error("overlapping uploads require a durable intent and no root CAS")
|
||||
}
|
||||
f.mu.Unlock()
|
||||
_ = w
|
||||
}
|
||||
|
||||
func TestChunkUploads_ConfiguredBoundAndCancellation(t *testing.T) {
|
||||
for _, limit := range []int{1, 2, 8} {
|
||||
t.Run(fmt.Sprint(limit), func(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
cfg.FreshFromHead = true
|
||||
cfg.UploadConcurrency = limit
|
||||
l := mustAttach(t, s, f, cfg)
|
||||
w := newWriteLog()
|
||||
for i := 0; i < 8; i++ {
|
||||
w.write(t, s, uint32(i*ctChunkBlocks), byte(i+1))
|
||||
}
|
||||
gate := make(chan struct{})
|
||||
entered := make(chan string, 16)
|
||||
f.mu.Lock()
|
||||
f.putGate = gate
|
||||
f.putEntered = entered
|
||||
f.mu.Unlock()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := l.Cut(ctx); done <- err }()
|
||||
for i := 0; i < limit; i++ {
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(time.Second):
|
||||
cancel()
|
||||
<-done
|
||||
t.Fatal("worker bound not reached")
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-entered:
|
||||
cancel()
|
||||
<-done
|
||||
t.Fatal("upload cap exceeded")
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err == nil {
|
||||
t.Fatal("cancelled upload succeeded")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("cancelled workers not joined")
|
||||
}
|
||||
if f.stats().cas != 0 {
|
||||
t.Fatal("cancelled upload published root")
|
||||
}
|
||||
assertNoIntentsLeft(t, f) // joined abort; no publication can refer to its keys
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A remote may ignore cancellation. Its owned upload must settle before
|
||||
// failure cleanup can remove the intent; cancellation alone is not a join.
|
||||
type unjoinedUploadRemote struct {
|
||||
*fakeChunkRemote
|
||||
calls atomic.Int32
|
||||
second chan struct{}
|
||||
failed chan struct{}
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (r *unjoinedUploadRemote) Put(ctx context.Context, key string, data []byte) error {
|
||||
if r.calls.Add(1) == 1 {
|
||||
<-r.second
|
||||
close(r.failed)
|
||||
return errFakeRemoteDown
|
||||
}
|
||||
close(r.second)
|
||||
<-r.release
|
||||
return r.fakeChunkRemote.Put(context.Background(), key, data)
|
||||
}
|
||||
func TestChunkUploads_FailureJoinsBeforeIntentCleanup(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
r := &unjoinedUploadRemote{fakeChunkRemote: f, second: make(chan struct{}), failed: make(chan struct{}), release: make(chan struct{})}
|
||||
cfg := ctConfig(1)
|
||||
cfg.FreshFromHead = true
|
||||
cfg.UploadConcurrency = 2
|
||||
l := mustAttach(t, s, r, cfg)
|
||||
w := newWriteLog()
|
||||
w.write(t, s, 0, 0x21)
|
||||
w.write(t, s, ctChunkBlocks, 0x22)
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := l.Cut(context.Background()); done <- err }()
|
||||
select {
|
||||
case <-r.failed:
|
||||
case <-time.After(time.Second):
|
||||
close(r.release)
|
||||
<-done
|
||||
t.Fatal("uploads did not overlap")
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
close(r.release)
|
||||
t.Fatalf("returned with owned upload still active: %v", err)
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
if len(liveIntents(t, f)) == 0 {
|
||||
close(r.release)
|
||||
<-done
|
||||
t.Fatal("intent removed before join")
|
||||
}
|
||||
close(r.release)
|
||||
if err := <-done; !errors.Is(err, errFakeRemoteDown) {
|
||||
t.Fatalf("lost upload failure: %v", err)
|
||||
}
|
||||
if f.stats().cas != 0 {
|
||||
t.Fatal("failed batch published")
|
||||
}
|
||||
assertNoIntentsLeft(t, f)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
# Chunk upload and manifest format
|
||||
|
||||
`blockvolume --durable-impl=walstore-chunk` uploads dirty chunks in parallel.
|
||||
`--chunk-upload-concurrency` defaults to 8 and accepts 1 through 64; 1 selects
|
||||
serial upload. The setting applies to both capture and pre-copy. Segment size
|
||||
is a format constant: each segment covers one logical GiB.
|
||||
|
||||
HEAD format 1 remains readable. A volume's next cut upgrades it to format 2 in
|
||||
one ordinary fenced root CAS (including an otherwise no-op cut); generation
|
||||
advances once, with the ordinary epoch/holder/LSN checks. Old binaries cannot
|
||||
read format 2: deploy format-aware readers and GC before publishing new cuts.
|
||||
Downgrading a volume after its first format-2 cut is unsupported.
|
||||
|
||||
A format-2 HEAD contains lineage, chunk geometry/count, and immutable segment
|
||||
references, instead of a flat chunk map. Each segment contains a sparse map of
|
||||
chunk indices and SHA-256 references; missing indices mean ZERO. Unchanged
|
||||
ranges retain their exact segment keys. Data and segment keys are protected by
|
||||
cut intents before upload. A root is published only after its objects exist;
|
||||
an unknown root CAS retains the intents until reconciliation.
|
||||
|
||||
Segment keys are owner-qualified (`@<volume>/seg/<nonce>`); a segment's chunk
|
||||
references retain their source namespace. Snapshot/fork copies only the root.
|
||||
The fork's root alone keeps inherited segments/data live after deleting its
|
||||
parent snapshot. There is no separate segment claim or segment publication
|
||||
tombstone. Snapshot attempt tombstones and never-reused volume ids are
|
||||
unchanged. Reclaimed immutable key bindings keep the existing GC marker that
|
||||
prevents rebinding an old key.
|
||||
|
||||
GC traces HEADs, snapshot attempts and copy intents through their verified
|
||||
segments to data. It also marks segment objects themselves. A published
|
||||
segment that cannot be read or verified refuses the entire mark, in dry-run
|
||||
and apply; no chunks are deleted after an incomplete mark. Capture intents
|
||||
protect prospective keys directly, including not-yet-uploaded segments. The
|
||||
existing higher-epoch plus TTL rule, copy-target tombstone settlement, two
|
||||
marks separated by grace, upload age floor and unbound-needle retention remain.
|
||||
A collector adapter without blob reads can collect flat roots but refuses a
|
||||
segmented root rather than omitting its children.
|
||||
|
||||
## Locks and cancellation
|
||||
|
||||
The existing cut/publication serialization is unchanged. Capture buffers and
|
||||
staged versions are selected as before; upload workers acquire no WAL,
|
||||
publication, shard or capture-state lock. Only the caller updates maps and
|
||||
counters after joining workers. The worker queue mutex guards admission and
|
||||
first error only, with no I/O under it. Failure cancels new admission and joins
|
||||
all owned calls before clean-abort intent cleanup. A remote ignoring
|
||||
cancellation can delay that join; it is never reported settled early.
|
||||
|
||||
## Reproducible proxy measurements
|
||||
|
||||
`go test -tags=manifest_perf ./core/frontend/chunkstore -run '^TestManifestPerf_' -count=1 -timeout=600s -v`
|
||||
|
||||
This materializes and fsyncs immutable files, including all 10 GiB of the large
|
||||
volume. Metadata uses the deterministic filer model. It compares 64 dirty
|
||||
4 MiB chunks at concurrency 1/8 in alternating order (three samples each), and
|
||||
flat versus segmented snapshot/fork operations (three samples each). Reported
|
||||
root bytes exclude segment bytes, which are reported separately. It excludes
|
||||
network latency, the block frontend, guest fsync and power-loss behavior.
|
||||
Reference in new issue
Block a user