diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index cdea709acf..6e5aadd22c 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -329,12 +329,15 @@ func decodeIntent(p string, e *filerpb.Entry) (storage.ChunkIntent, error) { } 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 +367,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 @@ -422,6 +429,13 @@ func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) { } doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} } + if h.Segments != nil { + 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 { return nil, err @@ -481,7 +495,7 @@ func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) { if err := json.Unmarshal(content, &doc); err != nil { return fail("decode: %v", err) } - if doc.Format != headFormat { + if doc.Format != headFormat && doc.Format != 2 { return fail("format %d not supported (want %d)", doc.Format, headFormat) } if doc.Gen == 0 { @@ -519,6 +533,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 } diff --git a/seaweed-block/core/frontend/chunkstore/manifest.go b/seaweed-block/core/frontend/chunkstore/manifest.go new file mode 100644 index 0000000000..dc4c7ef9ec --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/manifest.go @@ -0,0 +1,170 @@ +package chunkstore + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "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 qualified(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 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 = qualified(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 = qualified(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("manifests/%x", nonce) + next.Segments[group] = storage.ChunkSegment{Key: qualified(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.Put(ctx, u.key, u.data); 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 := json.Unmarshal(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 = qualified(ref.Owner, cr.Key) + h.Chunks[idx] = cr + } + } + return h, nil +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 461ea7a337..f005af7267 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -266,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 @@ -867,8 +873,21 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch 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) diff --git a/seaweed-block/core/storage/chunk_manifest.go b/seaweed-block/core/storage/chunk_manifest.go new file mode 100644 index 0000000000..2125321931 --- /dev/null +++ b/seaweed-block/core/storage/chunk_manifest.go @@ -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) +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index f72e31e5ed..ef63dae8ed 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -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.