mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d41f4ca8b | ||
|
|
d7854ce88e | ||
|
|
8acf21e4d1 | ||
|
|
a99c8214bb | ||
|
|
2d41d37150 | ||
|
|
2b8349f9e9 | ||
|
|
7b4df8b9e2 | ||
|
|
ee56d1a5cd | ||
|
|
71de73bcd4 | ||
|
|
20934cc854 | ||
|
|
21af729cb4 | ||
|
|
1e70bd3fc6 | ||
|
|
4e421400e4 | ||
|
|
56c51e7f50 | ||
|
|
71c33cc1e2 | ||
|
|
d1665750e1 | ||
|
|
0566fbd552 | ||
|
|
d4e39b499b | ||
|
|
adfd731bb8 | ||
|
|
917a87928c |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.27"
|
||||
appVersion: "4.28"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.27.0
|
||||
version: 4.28.0
|
||||
@@ -22,6 +22,9 @@ service SeaweedFiler {
|
||||
rpc UpdateEntry (UpdateEntryRequest) returns (UpdateEntryResponse) {
|
||||
}
|
||||
|
||||
rpc FinalizeVersionedWrite (FinalizeVersionedWriteRequest) returns (FinalizeVersionedWriteResponse) {
|
||||
}
|
||||
|
||||
rpc TouchAccessTime (TouchAccessTimeRequest) returns (TouchAccessTimeResponse) {
|
||||
}
|
||||
|
||||
@@ -222,6 +225,29 @@ message CreateEntryRequest {
|
||||
bool is_from_other_cluster = 4;
|
||||
repeated int32 signatures = 5;
|
||||
bool skip_check_parent_directory = 6;
|
||||
// Optional precondition evaluated against the current entry atomically with
|
||||
// the write, under the filer's per-path lock. The caller must route the
|
||||
// key's writes to this entry's owner filer for the check to be authoritative.
|
||||
WriteCondition condition = 7;
|
||||
}
|
||||
|
||||
// WriteCondition is a single precondition the filer evaluates against the
|
||||
// existing entry before writing. The client reduces request semantics (e.g.
|
||||
// RFC 7232 precedence) to one primitive; the filer just compares. A failed
|
||||
// condition returns FilerError PRECONDITION_FAILED.
|
||||
message WriteCondition {
|
||||
enum Kind {
|
||||
NONE = 0; // unconditional
|
||||
IF_NOT_EXISTS = 1; // fail if the entry exists (If-None-Match: *)
|
||||
IF_EXISTS = 2; // fail if the entry is absent (If-Match: *)
|
||||
IF_ETAG_MATCH = 3; // fail if absent or etag != expected (If-Match: <etag>)
|
||||
IF_ETAG_NOT_MATCH = 4; // fail if present and etag == expected (If-None-Match: <etag>)
|
||||
IF_UNMODIFIED_SINCE = 5; // fail if present and mtime > unix_time
|
||||
IF_MODIFIED_SINCE = 6; // fail if present and mtime <= unix_time
|
||||
}
|
||||
Kind kind = 1;
|
||||
string etag = 2; // expected ETag for IF_ETAG_* kinds
|
||||
int64 unix_time = 3; // bound (unix seconds) for IF_*_SINCE kinds
|
||||
}
|
||||
|
||||
// Structured error codes for filer entry operations.
|
||||
@@ -233,6 +259,7 @@ enum FilerError {
|
||||
EXISTING_IS_DIRECTORY = 3; // cannot overwrite directory with file
|
||||
EXISTING_IS_FILE = 4; // cannot overwrite file with directory
|
||||
ENTRY_ALREADY_EXISTS = 5; // O_EXCL and entry already exists
|
||||
PRECONDITION_FAILED = 6; // WriteCondition not satisfied
|
||||
}
|
||||
|
||||
message CreateEntryResponse {
|
||||
@@ -252,6 +279,40 @@ message UpdateEntryResponse {
|
||||
SubscribeMetadataResponse metadata_event = 1;
|
||||
}
|
||||
|
||||
// FinalizeVersionedWrite atomically finalizes an S3 versioned write on the
|
||||
// object's owner filer, after the caller has created the new version file: under
|
||||
// one exclusive lock on lock_key (the object path — the same key all of this
|
||||
// object's writes serialize on, regardless of versioning state) it evaluates the
|
||||
// precondition against the current latest, stamps the previously-latest version
|
||||
// as noncurrent (before the pointer flip, so the lifecycle router observes it),
|
||||
// then merges the latest-pointer / cached metadata into the .versions directory
|
||||
// entry. The caller routes the object's writes to this owner so the whole
|
||||
// sequence shares one local lock — no distributed lock. Key names are passed in
|
||||
// so the filer stays free of S3 semantics; the new version's file name is read
|
||||
// from set_extended[prior_latest_key].
|
||||
message FinalizeVersionedWriteRequest {
|
||||
string lock_key = 13; // object path; the per-path lock all of this object's writes share
|
||||
string delete_path = 14; // optional entry to delete under the lock first (suspended delete: the null version)
|
||||
string versions_dir = 1; // full path of <object>/.versions
|
||||
map<string, bytes> set_extended = 3; // merge into the .versions directory entry
|
||||
repeated string delete_extended = 4; // remove from the .versions directory entry
|
||||
string prior_latest_key = 5; // .versions entry key holding the latest file name (prior value = demote target)
|
||||
string noncurrent_since_key = 6; // key to stamp on the demoted previous version
|
||||
int64 noncurrent_since_ns = 7; // stamp value; <=0 skips the demote stamp
|
||||
bool is_from_other_cluster = 8;
|
||||
repeated int32 signatures = 9;
|
||||
// Optional precondition, evaluated against the current latest version
|
||||
// (derived from the .versions directory entry's cached metadata) before
|
||||
// anything is written, so the check and the write are atomic on this owner.
|
||||
WriteCondition condition = 10;
|
||||
string latest_etag_key = 11; // .versions entry key holding the latest version's ETag
|
||||
string latest_delete_marker_key = 12; // .versions entry key; "true" means the latest is a delete marker
|
||||
}
|
||||
message FinalizeVersionedWriteResponse {
|
||||
string error = 1;
|
||||
FilerError error_code = 2;
|
||||
}
|
||||
|
||||
message TouchAccessTimeRequest {
|
||||
string directory = 1;
|
||||
string name = 2;
|
||||
@@ -280,11 +341,16 @@ message DeleteEntryRequest {
|
||||
bool is_from_other_cluster = 7;
|
||||
repeated int32 signatures = 8;
|
||||
int64 if_not_modified_after = 9;
|
||||
// Optional precondition evaluated against the current entry atomically with
|
||||
// the delete, under the filer's per-path lock. Only honored for a
|
||||
// non-recursive single-entry delete routed to the entry's owner filer.
|
||||
WriteCondition condition = 10;
|
||||
}
|
||||
|
||||
message DeleteEntryResponse {
|
||||
string error = 1;
|
||||
SubscribeMetadataResponse metadata_event = 2;
|
||||
FilerError error_code = 3; // machine-readable error code (e.g. PRECONDITION_FAILED)
|
||||
}
|
||||
|
||||
message AtomicRenameEntryRequest {
|
||||
@@ -421,6 +487,7 @@ message SubscribeMetadataRequest {
|
||||
repeated string directories = 10; // exact directory to watch
|
||||
bool client_supports_batching = 11; // client can unpack SubscribeMetadataResponse.events
|
||||
bool client_supports_metadata_chunks = 12; // client can read log file chunks from volume servers
|
||||
bool client_supports_idle_heartbeat = 13; // server may send empty responses carrying the current time while the client is caught up
|
||||
}
|
||||
message SubscribeMetadataResponse {
|
||||
string directory = 1;
|
||||
|
||||
@@ -54,6 +54,70 @@ func (at *ActiveTopology) GetEffectiveAvailableCapacityDetailed(nodeID string, d
|
||||
return at.getEffectiveAvailableCapacityUnsafe(disk)
|
||||
}
|
||||
|
||||
// GetEffectiveAvailableEcShardSlots returns a disk's free EC shard slots,
|
||||
// accounting for in-flight task reservations at shard granularity. Unlike the
|
||||
// volume-slot views (GetDisksWithEffectiveCapacity / GetEffectiveAvailableCapacity),
|
||||
// this does not truncate sub-volume shard reservations: it subtracts the full
|
||||
// reservation impact (volume slots converted to shard slots, plus the raw shard
|
||||
// slots) so a reservation that is not a whole multiple of ShardsPerVolumeSlot is
|
||||
// not lost. It does NOT subtract the EC shards already persisted on the disk;
|
||||
// callers that track those (from EcShardInfos) subtract them separately.
|
||||
//
|
||||
// shardsPerVolume is the number of EC shards of the target collection that fit in
|
||||
// one volume slot (i.e. its data-shard count): a 4+2 volume's shards are ~1/4 of a
|
||||
// volume each, so one volume slot holds 4 of them, not the default
|
||||
// ShardsPerVolumeSlot. Pass <= 0 to use the default. Using the target ratio keeps
|
||||
// Place from over-filling a disk for low-data-shard layouts.
|
||||
func (at *ActiveTopology) GetEffectiveAvailableEcShardSlots(nodeID string, diskID uint32, shardsPerVolume int) int {
|
||||
if shardsPerVolume <= 0 {
|
||||
shardsPerVolume = ShardsPerVolumeSlot
|
||||
}
|
||||
|
||||
at.mutex.RLock()
|
||||
defer at.mutex.RUnlock()
|
||||
|
||||
diskKey := fmt.Sprintf("%s:%d", nodeID, diskID)
|
||||
disk, exists := at.disks[diskKey]
|
||||
if !exists || disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
info := disk.DiskInfo.DiskInfo
|
||||
base := info.MaxVolumeCount - info.VolumeCount
|
||||
if base <= 0 && info.MaxVolumeCount == 0 && info.VolumeCount == 0 &&
|
||||
len(info.VolumeInfos) == 0 && len(info.EcShardInfos) == 0 {
|
||||
// Freshly started empty servers can report max=0 before publishing concrete
|
||||
// limits; keep one provisional slot so EC placement still sees the disk,
|
||||
// mirroring getEffectiveAvailableCapacityUnsafe.
|
||||
base = 1
|
||||
}
|
||||
if base < 0 {
|
||||
base = 0
|
||||
}
|
||||
// calculateTaskStorageImpact reports consumption as positive, so subtract it.
|
||||
// Volume-slot reservations scale by the target ratio; the sub-volume shard-slot
|
||||
// remainder is in default units and subtracted as-is (a small approximation).
|
||||
impact := at.getEffectiveCapacityUnsafe(disk)
|
||||
// impact.ShardSlots is recorded in default ShardsPerVolumeSlot units; convert it
|
||||
// to the target ratio's shard slots before subtracting (identity when
|
||||
// shardsPerVolume == ShardsPerVolumeSlot). Round a positive reservation up so a
|
||||
// sub-slot reservation (e.g. 1 default slot against a 4-shard target) is not
|
||||
// truncated to zero and wrongly counted as free.
|
||||
scaledShardImpact := int64(impact.ShardSlots) * int64(shardsPerVolume)
|
||||
if scaledShardImpact > 0 {
|
||||
scaledShardImpact = (scaledShardImpact + int64(ShardsPerVolumeSlot) - 1) / int64(ShardsPerVolumeSlot)
|
||||
} else {
|
||||
scaledShardImpact /= int64(ShardsPerVolumeSlot)
|
||||
}
|
||||
free := base*int64(shardsPerVolume) -
|
||||
int64(impact.VolumeSlots)*int64(shardsPerVolume) -
|
||||
scaledShardImpact
|
||||
if free < 0 {
|
||||
free = 0
|
||||
}
|
||||
return int(free)
|
||||
}
|
||||
|
||||
// GetEffectiveCapacityImpact returns the StorageSlotChange impact for a disk
|
||||
// This shows the net impact from all pending and assigned tasks
|
||||
func (at *ActiveTopology) GetEffectiveCapacityImpact(nodeID string, diskID uint32) StorageSlotChange {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -19,6 +20,14 @@ type LockClient struct {
|
||||
maxLockDuration time.Duration
|
||||
sleepDuration time.Duration
|
||||
seedFiler pb.ServerAddress
|
||||
|
||||
// ring is an optional client-side view of the filer lock hash ring. When
|
||||
// populated, a new lock starts at the key's primary filer instead of the
|
||||
// seed filer, avoiding the seed->primary forward hop. A stale view stays
|
||||
// correct: the filer forwards to the real primary as a fallback.
|
||||
ringMu sync.RWMutex
|
||||
ring *lock_manager.HashRing
|
||||
ringVersion int64
|
||||
}
|
||||
|
||||
func NewLockClient(grpcDialOption grpc.DialOption, seedFiler pb.ServerAddress) *LockClient {
|
||||
@@ -30,6 +39,49 @@ func NewLockClient(grpcDialOption grpc.DialOption, seedFiler pb.ServerAddress) *
|
||||
}
|
||||
}
|
||||
|
||||
// SetRing updates the client-side view of the filer lock ring. It mirrors the
|
||||
// master's LockRingUpdate broadcasts so the client computes the same primary
|
||||
// the filers do. Updates older than the current version are ignored to tolerate
|
||||
// reordered broadcasts; version 0 is always accepted (bootstrap).
|
||||
func (lc *LockClient) SetRing(servers []pb.ServerAddress, version int64) {
|
||||
lc.ringMu.Lock()
|
||||
defer lc.ringMu.Unlock()
|
||||
if version != 0 && version < lc.ringVersion {
|
||||
return
|
||||
}
|
||||
lc.ringVersion = version
|
||||
if lc.ring == nil {
|
||||
lc.ring = lock_manager.NewHashRing(lock_manager.DefaultVnodeCount)
|
||||
}
|
||||
lc.ring.SetServers(servers)
|
||||
}
|
||||
|
||||
// hostForKey returns the filer that should own key per the current ring view,
|
||||
// falling back to the seed filer when no view has been received yet.
|
||||
func (lc *LockClient) hostForKey(key string) pb.ServerAddress {
|
||||
lc.ringMu.RLock()
|
||||
defer lc.ringMu.RUnlock()
|
||||
if lc.ring == nil {
|
||||
return lc.seedFiler
|
||||
}
|
||||
if primary := lc.ring.GetPrimary(key); primary != "" {
|
||||
return primary
|
||||
}
|
||||
return lc.seedFiler
|
||||
}
|
||||
|
||||
// PrimaryForKey returns the filer that owns key per the current ring view, or
|
||||
// "" when no ring view has been received yet. Callers use it to route a key's
|
||||
// operations to a single owner so that owner's local lock serializes them.
|
||||
func (lc *LockClient) PrimaryForKey(key string) pb.ServerAddress {
|
||||
lc.ringMu.RLock()
|
||||
defer lc.ringMu.RUnlock()
|
||||
if lc.ring == nil {
|
||||
return ""
|
||||
}
|
||||
return lc.ring.GetPrimary(key)
|
||||
}
|
||||
|
||||
type LiveLock struct {
|
||||
key string
|
||||
renewToken string
|
||||
@@ -51,7 +103,7 @@ type LiveLock struct {
|
||||
func (lc *LockClient) NewShortLivedLock(key string, owner string) (lock *LiveLock) {
|
||||
lock = &LiveLock{
|
||||
key: key,
|
||||
hostFiler: lc.seedFiler,
|
||||
hostFiler: lc.hostForKey(key),
|
||||
cancelCh: make(chan struct{}),
|
||||
expireAtNs: time.Now().Add(5 * time.Second).UnixNano(),
|
||||
grpcDialOption: lc.grpcDialOption,
|
||||
@@ -72,7 +124,7 @@ func (lc *LockClient) NewBlockingLongLivedLock(key, owner string, lockTTL time.D
|
||||
}
|
||||
lock := &LiveLock{
|
||||
key: key,
|
||||
hostFiler: lc.seedFiler,
|
||||
hostFiler: lc.hostForKey(key),
|
||||
cancelCh: make(chan struct{}),
|
||||
expireAtNs: time.Now().Add(lockTTL).UnixNano(),
|
||||
grpcDialOption: lc.grpcDialOption,
|
||||
@@ -110,7 +162,7 @@ func (lc *LockClient) NewBlockingLongLivedLock(key, owner string, lockTTL time.D
|
||||
func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerChange func(newLockOwner string), lockTTL time.Duration) (lock *LiveLock) {
|
||||
lock = &LiveLock{
|
||||
key: key,
|
||||
hostFiler: lc.seedFiler,
|
||||
hostFiler: lc.hostForKey(key),
|
||||
cancelCh: make(chan struct{}),
|
||||
expireAtNs: time.Now().Add(lockTTL).UnixNano(),
|
||||
grpcDialOption: lc.grpcDialOption,
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
)
|
||||
|
||||
// The gateway must resolve a lock key to the same primary the filers do,
|
||||
// otherwise it dials the wrong filer and the lock still gets forwarded. Both
|
||||
// sides use the same HashRing over the same server set, so for every key the
|
||||
// client's hostForKey must equal the filer ring's GetPrimary.
|
||||
func TestLockClientHostMatchesFilerRing(t *testing.T) {
|
||||
servers := []pb.ServerAddress{
|
||||
"filer-a:8888", "filer-b:8888", "filer-c:8888", "filer-d:8888",
|
||||
}
|
||||
|
||||
filerRing := lock_manager.NewHashRing(lock_manager.DefaultVnodeCount)
|
||||
filerRing.SetServers(servers)
|
||||
|
||||
lc := NewLockClient(nil, "seed:8888")
|
||||
lc.SetRing(servers, 1)
|
||||
|
||||
for _, key := range []string{
|
||||
"s3.object.write:/buckets/b/obj-0",
|
||||
"s3.object.write:/buckets/b/obj-1",
|
||||
"s3.object.write:/buckets/b/obj-2",
|
||||
"s3.object.write:/buckets/gosbench-0/w0obj-kilo-0877",
|
||||
"some/other/key",
|
||||
} {
|
||||
if got, want := lc.hostForKey(key), filerRing.GetPrimary(key); got != want {
|
||||
t.Errorf("key %q: client host %q != filer primary %q", key, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Without a ring view, the client falls back to the seed filer (which the filer
|
||||
// forwards from), preserving the pre-optimization behavior.
|
||||
func TestLockClientHostFallsBackToSeed(t *testing.T) {
|
||||
lc := NewLockClient(nil, "seed:8888")
|
||||
if got := lc.hostForKey("any-key"); got != "seed:8888" {
|
||||
t.Errorf("expected seed fallback, got %q", got)
|
||||
}
|
||||
|
||||
// An empty ring (no members yet) also falls back to the seed.
|
||||
lc.SetRing(nil, 1)
|
||||
if got := lc.hostForKey("any-key"); got != "seed:8888" {
|
||||
t.Errorf("expected seed fallback on empty ring, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A stale (older-version) update must not regress a newer ring view, while
|
||||
// version 0 always applies as a bootstrap.
|
||||
func TestLockClientSetRingVersionGuard(t *testing.T) {
|
||||
lc := NewLockClient(nil, "seed:8888")
|
||||
|
||||
newer := []pb.ServerAddress{"filer-a:8888", "filer-b:8888"}
|
||||
lc.SetRing(newer, 10)
|
||||
primaryAt10 := lc.hostForKey("k")
|
||||
|
||||
// Older version is ignored.
|
||||
lc.SetRing([]pb.ServerAddress{"filer-z:8888"}, 5)
|
||||
if got := lc.hostForKey("k"); got != primaryAt10 {
|
||||
t.Errorf("stale update applied: host changed to %q", got)
|
||||
}
|
||||
|
||||
// version 0 is always accepted.
|
||||
lc.SetRing([]pb.ServerAddress{"filer-z:8888"}, 0)
|
||||
if got := lc.hostForKey("k"); got != "filer-z:8888" {
|
||||
t.Errorf("bootstrap update not applied, got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,9 @@ service SeaweedFiler {
|
||||
rpc UpdateEntry (UpdateEntryRequest) returns (UpdateEntryResponse) {
|
||||
}
|
||||
|
||||
rpc FinalizeVersionedWrite (FinalizeVersionedWriteRequest) returns (FinalizeVersionedWriteResponse) {
|
||||
}
|
||||
|
||||
rpc TouchAccessTime (TouchAccessTimeRequest) returns (TouchAccessTimeResponse) {
|
||||
}
|
||||
|
||||
@@ -222,6 +225,29 @@ message CreateEntryRequest {
|
||||
bool is_from_other_cluster = 4;
|
||||
repeated int32 signatures = 5;
|
||||
bool skip_check_parent_directory = 6;
|
||||
// Optional precondition evaluated against the current entry atomically with
|
||||
// the write, under the filer's per-path lock. The caller must route the
|
||||
// key's writes to this entry's owner filer for the check to be authoritative.
|
||||
WriteCondition condition = 7;
|
||||
}
|
||||
|
||||
// WriteCondition is a single precondition the filer evaluates against the
|
||||
// existing entry before writing. The client reduces request semantics (e.g.
|
||||
// RFC 7232 precedence) to one primitive; the filer just compares. A failed
|
||||
// condition returns FilerError PRECONDITION_FAILED.
|
||||
message WriteCondition {
|
||||
enum Kind {
|
||||
NONE = 0; // unconditional
|
||||
IF_NOT_EXISTS = 1; // fail if the entry exists (If-None-Match: *)
|
||||
IF_EXISTS = 2; // fail if the entry is absent (If-Match: *)
|
||||
IF_ETAG_MATCH = 3; // fail if absent or etag != expected (If-Match: <etag>)
|
||||
IF_ETAG_NOT_MATCH = 4; // fail if present and etag == expected (If-None-Match: <etag>)
|
||||
IF_UNMODIFIED_SINCE = 5; // fail if present and mtime > unix_time
|
||||
IF_MODIFIED_SINCE = 6; // fail if present and mtime <= unix_time
|
||||
}
|
||||
Kind kind = 1;
|
||||
string etag = 2; // expected ETag for IF_ETAG_* kinds
|
||||
int64 unix_time = 3; // bound (unix seconds) for IF_*_SINCE kinds
|
||||
}
|
||||
|
||||
// Structured error codes for filer entry operations.
|
||||
@@ -233,6 +259,7 @@ enum FilerError {
|
||||
EXISTING_IS_DIRECTORY = 3; // cannot overwrite directory with file
|
||||
EXISTING_IS_FILE = 4; // cannot overwrite file with directory
|
||||
ENTRY_ALREADY_EXISTS = 5; // O_EXCL and entry already exists
|
||||
PRECONDITION_FAILED = 6; // WriteCondition not satisfied
|
||||
}
|
||||
|
||||
message CreateEntryResponse {
|
||||
@@ -252,6 +279,40 @@ message UpdateEntryResponse {
|
||||
SubscribeMetadataResponse metadata_event = 1;
|
||||
}
|
||||
|
||||
// FinalizeVersionedWrite atomically finalizes an S3 versioned write on the
|
||||
// object's owner filer, after the caller has created the new version file: under
|
||||
// one exclusive lock on lock_key (the object path — the same key all of this
|
||||
// object's writes serialize on, regardless of versioning state) it evaluates the
|
||||
// precondition against the current latest, stamps the previously-latest version
|
||||
// as noncurrent (before the pointer flip, so the lifecycle router observes it),
|
||||
// then merges the latest-pointer / cached metadata into the .versions directory
|
||||
// entry. The caller routes the object's writes to this owner so the whole
|
||||
// sequence shares one local lock — no distributed lock. Key names are passed in
|
||||
// so the filer stays free of S3 semantics; the new version's file name is read
|
||||
// from set_extended[prior_latest_key].
|
||||
message FinalizeVersionedWriteRequest {
|
||||
string lock_key = 13; // object path; the per-path lock all of this object's writes share
|
||||
string delete_path = 14; // optional entry to delete under the lock first (suspended delete: the null version)
|
||||
string versions_dir = 1; // full path of <object>/.versions
|
||||
map<string, bytes> set_extended = 3; // merge into the .versions directory entry
|
||||
repeated string delete_extended = 4; // remove from the .versions directory entry
|
||||
string prior_latest_key = 5; // .versions entry key holding the latest file name (prior value = demote target)
|
||||
string noncurrent_since_key = 6; // key to stamp on the demoted previous version
|
||||
int64 noncurrent_since_ns = 7; // stamp value; <=0 skips the demote stamp
|
||||
bool is_from_other_cluster = 8;
|
||||
repeated int32 signatures = 9;
|
||||
// Optional precondition, evaluated against the current latest version
|
||||
// (derived from the .versions directory entry's cached metadata) before
|
||||
// anything is written, so the check and the write are atomic on this owner.
|
||||
WriteCondition condition = 10;
|
||||
string latest_etag_key = 11; // .versions entry key holding the latest version's ETag
|
||||
string latest_delete_marker_key = 12; // .versions entry key; "true" means the latest is a delete marker
|
||||
}
|
||||
message FinalizeVersionedWriteResponse {
|
||||
string error = 1;
|
||||
FilerError error_code = 2;
|
||||
}
|
||||
|
||||
message TouchAccessTimeRequest {
|
||||
string directory = 1;
|
||||
string name = 2;
|
||||
@@ -280,11 +341,16 @@ message DeleteEntryRequest {
|
||||
bool is_from_other_cluster = 7;
|
||||
repeated int32 signatures = 8;
|
||||
int64 if_not_modified_after = 9;
|
||||
// Optional precondition evaluated against the current entry atomically with
|
||||
// the delete, under the filer's per-path lock. Only honored for a
|
||||
// non-recursive single-entry delete routed to the entry's owner filer.
|
||||
WriteCondition condition = 10;
|
||||
}
|
||||
|
||||
message DeleteEntryResponse {
|
||||
string error = 1;
|
||||
SubscribeMetadataResponse metadata_event = 2;
|
||||
FilerError error_code = 3; // machine-readable error code (e.g. PRECONDITION_FAILED)
|
||||
}
|
||||
|
||||
message AtomicRenameEntryRequest {
|
||||
|
||||
+835
-413
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.6.2
|
||||
// - protoc v7.34.1
|
||||
// - protoc v6.33.4
|
||||
// source: filer.proto
|
||||
|
||||
package filer_pb
|
||||
@@ -23,6 +23,7 @@ const (
|
||||
SeaweedFiler_ListEntries_FullMethodName = "/filer_pb.SeaweedFiler/ListEntries"
|
||||
SeaweedFiler_CreateEntry_FullMethodName = "/filer_pb.SeaweedFiler/CreateEntry"
|
||||
SeaweedFiler_UpdateEntry_FullMethodName = "/filer_pb.SeaweedFiler/UpdateEntry"
|
||||
SeaweedFiler_FinalizeVersionedWrite_FullMethodName = "/filer_pb.SeaweedFiler/FinalizeVersionedWrite"
|
||||
SeaweedFiler_TouchAccessTime_FullMethodName = "/filer_pb.SeaweedFiler/TouchAccessTime"
|
||||
SeaweedFiler_AppendToEntry_FullMethodName = "/filer_pb.SeaweedFiler/AppendToEntry"
|
||||
SeaweedFiler_DeleteEntry_FullMethodName = "/filer_pb.SeaweedFiler/DeleteEntry"
|
||||
@@ -59,6 +60,7 @@ type SeaweedFilerClient interface {
|
||||
ListEntries(ctx context.Context, in *ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ListEntriesResponse], error)
|
||||
CreateEntry(ctx context.Context, in *CreateEntryRequest, opts ...grpc.CallOption) (*CreateEntryResponse, error)
|
||||
UpdateEntry(ctx context.Context, in *UpdateEntryRequest, opts ...grpc.CallOption) (*UpdateEntryResponse, error)
|
||||
FinalizeVersionedWrite(ctx context.Context, in *FinalizeVersionedWriteRequest, opts ...grpc.CallOption) (*FinalizeVersionedWriteResponse, error)
|
||||
TouchAccessTime(ctx context.Context, in *TouchAccessTimeRequest, opts ...grpc.CallOption) (*TouchAccessTimeResponse, error)
|
||||
AppendToEntry(ctx context.Context, in *AppendToEntryRequest, opts ...grpc.CallOption) (*AppendToEntryResponse, error)
|
||||
DeleteEntry(ctx context.Context, in *DeleteEntryRequest, opts ...grpc.CallOption) (*DeleteEntryResponse, error)
|
||||
@@ -147,6 +149,16 @@ func (c *seaweedFilerClient) UpdateEntry(ctx context.Context, in *UpdateEntryReq
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *seaweedFilerClient) FinalizeVersionedWrite(ctx context.Context, in *FinalizeVersionedWriteRequest, opts ...grpc.CallOption) (*FinalizeVersionedWriteResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(FinalizeVersionedWriteResponse)
|
||||
err := c.cc.Invoke(ctx, SeaweedFiler_FinalizeVersionedWrite_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *seaweedFilerClient) TouchAccessTime(ctx context.Context, in *TouchAccessTimeRequest, opts ...grpc.CallOption) (*TouchAccessTimeResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(TouchAccessTimeResponse)
|
||||
@@ -454,6 +466,7 @@ type SeaweedFilerServer interface {
|
||||
ListEntries(*ListEntriesRequest, grpc.ServerStreamingServer[ListEntriesResponse]) error
|
||||
CreateEntry(context.Context, *CreateEntryRequest) (*CreateEntryResponse, error)
|
||||
UpdateEntry(context.Context, *UpdateEntryRequest) (*UpdateEntryResponse, error)
|
||||
FinalizeVersionedWrite(context.Context, *FinalizeVersionedWriteRequest) (*FinalizeVersionedWriteResponse, error)
|
||||
TouchAccessTime(context.Context, *TouchAccessTimeRequest) (*TouchAccessTimeResponse, error)
|
||||
AppendToEntry(context.Context, *AppendToEntryRequest) (*AppendToEntryResponse, error)
|
||||
DeleteEntry(context.Context, *DeleteEntryRequest) (*DeleteEntryResponse, error)
|
||||
@@ -505,6 +518,9 @@ func (UnimplementedSeaweedFilerServer) CreateEntry(context.Context, *CreateEntry
|
||||
func (UnimplementedSeaweedFilerServer) UpdateEntry(context.Context, *UpdateEntryRequest) (*UpdateEntryResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method UpdateEntry not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) FinalizeVersionedWrite(context.Context, *FinalizeVersionedWriteRequest) (*FinalizeVersionedWriteResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method FinalizeVersionedWrite not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) TouchAccessTime(context.Context, *TouchAccessTimeRequest) (*TouchAccessTimeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method TouchAccessTime not implemented")
|
||||
}
|
||||
@@ -669,6 +685,24 @@ func _SeaweedFiler_UpdateEntry_Handler(srv interface{}, ctx context.Context, dec
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _SeaweedFiler_FinalizeVersionedWrite_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(FinalizeVersionedWriteRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(SeaweedFilerServer).FinalizeVersionedWrite(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: SeaweedFiler_FinalizeVersionedWrite_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(SeaweedFilerServer).FinalizeVersionedWrite(ctx, req.(*FinalizeVersionedWriteRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _SeaweedFiler_TouchAccessTime_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(TouchAccessTimeRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -1117,6 +1151,10 @@ var SeaweedFiler_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "UpdateEntry",
|
||||
Handler: _SeaweedFiler_UpdateEntry_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "FinalizeVersionedWrite",
|
||||
Handler: _SeaweedFiler_FinalizeVersionedWrite_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "TouchAccessTime",
|
||||
Handler: _SeaweedFiler_TouchAccessTime_Handler,
|
||||
|
||||
@@ -374,6 +374,7 @@ message ErasureCodingTaskConfig {
|
||||
int32 min_volume_size_mb = 3; // Minimum volume size for EC
|
||||
string collection_filter = 4; // Only process volumes from specific collections
|
||||
repeated string preferred_tags = 5; // Disk tags to prioritize for EC shard placement
|
||||
string replica_placement = 6; // EC shard replica placement (e.g. "020"); empty falls back to master default replication
|
||||
}
|
||||
|
||||
// BalanceTaskConfig contains balance-specific configuration
|
||||
|
||||
@@ -2960,6 +2960,7 @@ type ErasureCodingTaskConfig struct {
|
||||
MinVolumeSizeMb int32 `protobuf:"varint,3,opt,name=min_volume_size_mb,json=minVolumeSizeMb,proto3" json:"min_volume_size_mb,omitempty"` // Minimum volume size for EC
|
||||
CollectionFilter string `protobuf:"bytes,4,opt,name=collection_filter,json=collectionFilter,proto3" json:"collection_filter,omitempty"` // Only process volumes from specific collections
|
||||
PreferredTags []string `protobuf:"bytes,5,rep,name=preferred_tags,json=preferredTags,proto3" json:"preferred_tags,omitempty"` // Disk tags to prioritize for EC shard placement
|
||||
ReplicaPlacement string `protobuf:"bytes,6,opt,name=replica_placement,json=replicaPlacement,proto3" json:"replica_placement,omitempty"` // EC shard replica placement (e.g. "020"); empty falls back to master default replication
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -3029,6 +3030,13 @@ func (x *ErasureCodingTaskConfig) GetPreferredTags() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *ErasureCodingTaskConfig) GetReplicaPlacement() string {
|
||||
if x != nil {
|
||||
return x.ReplicaPlacement
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// BalanceTaskConfig contains balance-specific configuration
|
||||
type BalanceTaskConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
@@ -4218,13 +4226,14 @@ const file_worker_proto_rawDesc = "" +
|
||||
"\x10VacuumTaskConfig\x12+\n" +
|
||||
"\x11garbage_threshold\x18\x01 \x01(\x01R\x10garbageThreshold\x12/\n" +
|
||||
"\x14min_volume_age_hours\x18\x02 \x01(\x05R\x11minVolumeAgeHours\x120\n" +
|
||||
"\x14min_interval_seconds\x18\x03 \x01(\x05R\x12minIntervalSeconds\"\xed\x01\n" +
|
||||
"\x14min_interval_seconds\x18\x03 \x01(\x05R\x12minIntervalSeconds\"\x9a\x02\n" +
|
||||
"\x17ErasureCodingTaskConfig\x12%\n" +
|
||||
"\x0efullness_ratio\x18\x01 \x01(\x01R\rfullnessRatio\x12*\n" +
|
||||
"\x11quiet_for_seconds\x18\x02 \x01(\x05R\x0fquietForSeconds\x12+\n" +
|
||||
"\x12min_volume_size_mb\x18\x03 \x01(\x05R\x0fminVolumeSizeMb\x12+\n" +
|
||||
"\x11collection_filter\x18\x04 \x01(\tR\x10collectionFilter\x12%\n" +
|
||||
"\x0epreferred_tags\x18\x05 \x03(\tR\rpreferredTags\"n\n" +
|
||||
"\x0epreferred_tags\x18\x05 \x03(\tR\rpreferredTags\x12+\n" +
|
||||
"\x11replica_placement\x18\x06 \x01(\tR\x10replicaPlacement\"n\n" +
|
||||
"\x11BalanceTaskConfig\x12/\n" +
|
||||
"\x13imbalance_threshold\x18\x01 \x01(\x01R\x12imbalanceThreshold\x12(\n" +
|
||||
"\x10min_server_count\x18\x02 \x01(\x05R\x0eminServerCount\"I\n" +
|
||||
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
@@ -553,9 +554,16 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
uploadDirectory := s3a.genUploadsFolder(*input.Bucket) + "/" + *input.UploadId
|
||||
entryName, dirName := s3a.getEntryNameAndDir(input)
|
||||
var completionState *multipartCompletionState
|
||||
finalizeCode := s3a.withObjectWriteLock(*input.Bucket, *input.Key, func() s3err.ErrorCode {
|
||||
return s3a.checkConditionalHeaders(r, *input.Bucket, *input.Key)
|
||||
}, func() s3err.ErrorCode {
|
||||
// Non-versioned destination: the final write is a single CreateEntry, so route
|
||||
// it (with the precondition) to the object's owner and skip the distributed
|
||||
// lock. Assembly and the idempotency replay below are read-only and safe
|
||||
// outside any lock. Versioned/suspended completions keep the lock path.
|
||||
mpuCond, mpuCondOk := buildWriteCondition(r)
|
||||
var nvOwner pb.ServerAddress
|
||||
if vs, vErr := s3a.getVersioningState(*input.Bucket); vErr == nil && vs == "" && mpuCondOk {
|
||||
nvOwner, _ = s3a.routedObjectOwner(*input.Bucket, *input.Key)
|
||||
}
|
||||
finalizeBody := func() s3err.ErrorCode {
|
||||
var prepCode s3err.ErrorCode
|
||||
completionState, output, prepCode = s3a.prepareMultipartCompletionState(r, input, uploadDirectory, entryName, dirName, completedPartNumbers, completedPartMap, maxPartNo)
|
||||
if prepCode != s3err.ErrNone || output != nil {
|
||||
@@ -739,7 +747,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
}
|
||||
|
||||
// For non-versioned buckets, create main object file
|
||||
if err := s3a.mkFile(dirName, entryName, completionState.finalParts, func(entry *filer_pb.Entry) {
|
||||
nvModifier := func(entry *filer_pb.Entry) {
|
||||
if entry.Extended == nil {
|
||||
entry.Extended = make(map[string][]byte)
|
||||
}
|
||||
@@ -787,7 +795,14 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
if completionState.entityWithTtl {
|
||||
entry.Extended[s3_constants.SeaweedFSExpiresS3] = []byte("true")
|
||||
}
|
||||
}); err != nil {
|
||||
}
|
||||
if nvOwner != "" {
|
||||
// Routed path: the owner evaluates the precondition and writes under
|
||||
// its local lock, so the lock wrapper below is skipped.
|
||||
if code := s3a.mkFileRouted(nvOwner, dirName, entryName, completionState.finalParts, mpuCond, nvModifier); code != s3err.ErrNone {
|
||||
return code
|
||||
}
|
||||
} else if err := s3a.mkFile(dirName, entryName, completionState.finalParts, nvModifier); err != nil {
|
||||
glog.Errorf("completeMultipartUpload %s/%s error: %v", dirName, entryName, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
@@ -802,7 +817,17 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
ChecksumValue: completionState.checksumValue,
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
}
|
||||
var finalizeCode s3err.ErrorCode
|
||||
if nvOwner != "" {
|
||||
// Routed non-versioned completion: no distributed lock, no gateway
|
||||
// precondition here — the routed write carries the condition.
|
||||
finalizeCode = finalizeBody()
|
||||
} else {
|
||||
finalizeCode = s3a.withObjectWriteLock(*input.Bucket, *input.Key, func() s3err.ErrorCode {
|
||||
return s3a.checkConditionalHeaders(r, *input.Bucket, *input.Key)
|
||||
}, finalizeBody)
|
||||
}
|
||||
if finalizeCode != s3err.ErrNone {
|
||||
return nil, finalizeCode
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
|
||||
}
|
||||
switch state {
|
||||
case s3_constants.VersioningEnabled:
|
||||
if _, err := s3a.createDeleteMarker(req.Bucket, req.ObjectPath); err != nil {
|
||||
if _, err := s3a.createDeleteMarker(req.Bucket, req.ObjectPath, "", nil, ""); err != nil {
|
||||
return retryLater("TRANSPORT_ERROR: createDeleteMarker: " + err.Error()), nil
|
||||
}
|
||||
return done(), nil
|
||||
@@ -82,7 +82,7 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
|
||||
return retryLater("TRANSPORT_ERROR: deleteNullVersion: " + err.Error()), nil
|
||||
}
|
||||
}
|
||||
if _, err := s3a.createDeleteMarker(req.Bucket, req.ObjectPath); err != nil {
|
||||
if _, err := s3a.createDeleteMarker(req.Bucket, req.ObjectPath, "", nil, ""); err != nil {
|
||||
return retryLater("TRANSPORT_ERROR: createDeleteMarker: " + err.Error()), nil
|
||||
}
|
||||
return done(), nil
|
||||
|
||||
@@ -324,7 +324,7 @@ func removeDuplicateSlashes(object string) string {
|
||||
// hasChildren("bucket", "empty-dir") where no children exist → false
|
||||
//
|
||||
// Performance: ~1-5ms per call (one gRPC LIST request with Limit=1)
|
||||
func (s3a *S3ApiServer) hasChildren(bucket, prefix string) bool {
|
||||
func (s3a *S3ApiServer) hasChildren(ctx context.Context, bucket, prefix string) bool {
|
||||
// Clean up prefix: remove leading slashes
|
||||
cleanPrefix := strings.TrimPrefix(prefix, "/")
|
||||
|
||||
@@ -334,8 +334,10 @@ func (s3a *S3ApiServer) hasChildren(bucket, prefix string) bool {
|
||||
|
||||
// List one child object. filer_pb.List cancels the underlying ListEntries
|
||||
// stream when it returns, so gRPC's per-stream client goroutine is not leaked.
|
||||
// The caller's request context is propagated so the probe is cancelled if the
|
||||
// client disconnects.
|
||||
found := false
|
||||
err := filer_pb.List(context.Background(), s3a, fullPath, "", func(*filer_pb.Entry, bool) error {
|
||||
err := filer_pb.List(ctx, s3a, fullPath, "", func(*filer_pb.Entry, bool) error {
|
||||
found = true
|
||||
return nil
|
||||
}, "", true, 1)
|
||||
@@ -2320,7 +2322,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
}
|
||||
if isZeroByteFile {
|
||||
// Check if it has children (making it an implicit directory)
|
||||
if s3a.hasChildren(bucket, object) {
|
||||
if s3a.hasChildren(r.Context(), bucket, object) {
|
||||
// This is an implicit directory with children
|
||||
// Return 404 to force clients (like s3fs) to use LIST-based discovery
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
@@ -182,7 +183,7 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
}
|
||||
updatedEntry.Attributes.Mtime = t.Unix()
|
||||
|
||||
dstVersionId, etag, currentErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, updatedEntry)
|
||||
dstVersionId, etag, currentErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, updatedEntry, "", nil)
|
||||
if currentErr != nil {
|
||||
return filerErrorToS3Error(currentErr)
|
||||
}
|
||||
@@ -337,16 +338,49 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
var dstVersionId string
|
||||
var etag string
|
||||
|
||||
finalizeCode := s3a.withObjectWriteLock(dstBucket, dstObject, func() s3err.ErrorCode {
|
||||
return s3a.checkConditionalHeaders(r, dstBucket, dstObject)
|
||||
}, func() s3err.ErrorCode {
|
||||
var finalizeErr error
|
||||
dstVersionId, etag, finalizeErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, dstEntry)
|
||||
if finalizeErr != nil {
|
||||
return filerErrorToS3Error(finalizeErr)
|
||||
// Fast path: route the finalize to the destination's owner filer and skip the
|
||||
// distributed lock. A non-versioned destination is a single CreateEntry; a
|
||||
// versioning-enabled destination is a unique version file plus an atomic
|
||||
// latest-pointer update on the .versions owner (FinalizeVersionedWrite).
|
||||
// Suspended versioning (multi-version IsLatest rewrite) keeps the lock path.
|
||||
var finalizeCode s3err.ErrorCode
|
||||
routed := false
|
||||
if cond, condOk := buildWriteCondition(r); condOk {
|
||||
switch dstVersioningState {
|
||||
case "":
|
||||
if owner, ownerOk := s3a.routedObjectOwner(dstBucket, dstObject); ownerOk {
|
||||
if code, e, handled := s3a.routedCopyFinalize(owner, dstBucket, dstObject, dstEntry, cond); handled {
|
||||
finalizeCode, etag, routed = code, e, true
|
||||
}
|
||||
}
|
||||
case s3_constants.VersioningEnabled:
|
||||
if owner := s3a.objectWriteOwner(dstBucket, s3_constants.NormalizeObjectKey(dstObject)); owner != "" {
|
||||
var finalizeErr error
|
||||
dstVersionId, etag, finalizeErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, dstEntry, owner, cond)
|
||||
switch {
|
||||
case finalizeErr == nil:
|
||||
finalizeCode = s3err.ErrNone
|
||||
case errors.Is(finalizeErr, errVersionedPreconditionFailed):
|
||||
finalizeCode = s3err.ErrPreconditionFailed
|
||||
default:
|
||||
finalizeCode = filerErrorToS3Error(finalizeErr)
|
||||
}
|
||||
routed = true
|
||||
}
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
}
|
||||
if !routed {
|
||||
finalizeCode = s3a.withObjectWriteLock(dstBucket, dstObject, func() s3err.ErrorCode {
|
||||
return s3a.checkConditionalHeaders(r, dstBucket, dstObject)
|
||||
}, func() s3err.ErrorCode {
|
||||
var finalizeErr error
|
||||
dstVersionId, etag, finalizeErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, dstEntry, "", nil)
|
||||
if finalizeErr != nil {
|
||||
return filerErrorToS3Error(finalizeErr)
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
}
|
||||
if finalizeCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, finalizeCode)
|
||||
return
|
||||
@@ -412,7 +446,58 @@ func copyEntryToTarget(dst, src *filer_pb.Entry) {
|
||||
dst.WormEnforcedAtTsNs = src.WormEnforcedAtTsNs
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersioningState string, dstEntry *filer_pb.Entry) (versionId string, etag string, err error) {
|
||||
// routedCopyFinalize writes a non-versioned copy destination as a single
|
||||
// CreateEntry routed to the destination key's owner filer, building the same
|
||||
// entry that finalizeCopyDestination's default branch produces via mkFile. It
|
||||
// returns handled=false to fall back to the lock path on a transport error or an
|
||||
// unmapped in-band error.
|
||||
func (s3a *S3ApiServer) routedCopyFinalize(owner pb.ServerAddress, dstBucket, dstObject string, dstEntry *filer_pb.Entry, cond *filer_pb.WriteCondition) (errCode s3err.ErrorCode, etag string, handled bool) {
|
||||
normalizedObject := s3_constants.NormalizeObjectKey(dstObject)
|
||||
dstPath := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(dstBucket), normalizedObject))
|
||||
dstDir, dstName := dstPath.DirAndName()
|
||||
|
||||
if dstEntry.Attributes == nil {
|
||||
dstEntry.Attributes = &filer_pb.FuseAttributes{}
|
||||
}
|
||||
if dstEntry.Extended == nil {
|
||||
dstEntry.Extended = make(map[string][]byte)
|
||||
}
|
||||
etag = copyEntryETag(dstPath, dstEntry)
|
||||
cleanupVersioningMetadata(dstEntry.Extended)
|
||||
dstEntry.Extended[s3_constants.ExtETagKey] = []byte(etag)
|
||||
|
||||
// Build the destination entry exactly as mkFile + copyEntryToTarget would.
|
||||
entry := &filer_pb.Entry{Name: dstName, Chunks: dstEntry.Chunks}
|
||||
copyEntryToTarget(entry, dstEntry)
|
||||
|
||||
resp, err := s3a.createEntryOnFiler(owner, &filer_pb.CreateEntryRequest{
|
||||
Directory: dstDir,
|
||||
Entry: entry,
|
||||
Condition: cond,
|
||||
})
|
||||
switch {
|
||||
case err != nil:
|
||||
glog.Warningf("CopyObjectHandler: routed finalize to %s failed for %s/%s, falling back to lock: %v", owner, dstBucket, dstObject, err)
|
||||
return s3err.ErrNone, "", false
|
||||
case resp.ErrorCode != filer_pb.FilerError_OK:
|
||||
if code, mapped := filerErrorCodeToS3Error(resp.ErrorCode); mapped {
|
||||
return code, "", true
|
||||
}
|
||||
glog.Warningf("CopyObjectHandler: routed finalize to %s returned code %v for %s/%s, falling back to lock", owner, resp.ErrorCode, dstBucket, dstObject)
|
||||
return s3err.ErrNone, "", false
|
||||
case resp.Error != "":
|
||||
glog.Warningf("CopyObjectHandler: routed finalize to %s returned %q for %s/%s, falling back to lock", owner, resp.Error, dstBucket, dstObject)
|
||||
return s3err.ErrNone, "", false
|
||||
default:
|
||||
return s3err.ErrNone, etag, true
|
||||
}
|
||||
}
|
||||
|
||||
// finalizeCopyDestination writes the copy destination. When routedOwner is set
|
||||
// (versioning-enabled destination routed off the distributed lock), the latest-
|
||||
// pointer update goes through FinalizeVersionedWrite on that owner, which also
|
||||
// evaluates cond; otherwise it uses the lock-based updateLatestVersionInDirectory.
|
||||
func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersioningState string, dstEntry *filer_pb.Entry, routedOwner pb.ServerAddress, cond *filer_pb.WriteCondition) (versionId string, etag string, err error) {
|
||||
normalizedObject := s3_constants.NormalizeObjectKey(dstObject)
|
||||
dstPath := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(dstBucket), normalizedObject))
|
||||
dstDir, dstName := dstPath.DirAndName()
|
||||
@@ -444,6 +529,18 @@ func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersion
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
if routedOwner != "" {
|
||||
// Routed: precondition + demote + pointer flip run atomically on the
|
||||
// .versions owner. Roll back the version file if it does not succeed.
|
||||
if code := s3a.routedVersionedFinalize(routedOwner, dstBucket, normalizedObject, versionId, versionFileName, dstEntry, cond, ""); code != s3err.ErrNone {
|
||||
if rollbackErr := s3a.rollbackCopyVersion(bucketDir, versionObjectPath); rollbackErr != nil {
|
||||
glog.Errorf("CopyObjectHandler: failed to rollback version %s for %s/%s after routed finalize error: %v", versionId, dstBucket, normalizedObject, rollbackErr)
|
||||
}
|
||||
return "", "", finalizeCodeToError(code)
|
||||
}
|
||||
return versionId, etag, nil
|
||||
}
|
||||
|
||||
if err = s3a.updateLatestVersionInDirectory(dstBucket, normalizedObject, versionId, versionFileName, dstEntry); err != nil {
|
||||
if rollbackErr := s3a.rollbackCopyVersion(bucketDir, versionObjectPath); rollbackErr != nil {
|
||||
glog.Errorf("CopyObjectHandler: failed to rollback version %s for %s/%s after latest pointer update error: %v", versionId, dstBucket, normalizedObject, rollbackErr)
|
||||
|
||||
@@ -397,7 +397,7 @@ func (s3a *S3ApiServer) copyObjectPartViaReencryption(
|
||||
filePath := s3a.genPartUploadPath(dstBucket, uploadID, partID)
|
||||
// Copy-part is an MPU part write under .uploads/<id>/<n>; lifecycle
|
||||
// TTL only applies to the eventual completed object. Pass 0.
|
||||
tag, code, putSSE := s3a.putToFiler(cloned, filePath, srcReader, dstBucket, "", partID, 0, nil)
|
||||
tag, code, putSSE := s3a.putToFiler(cloned, filePath, srcReader, dstBucket, "", partID, 0, nil, false)
|
||||
if code != s3err.ErrNone {
|
||||
return "", SSEResponseMetadata{}, code
|
||||
}
|
||||
|
||||
@@ -133,7 +133,7 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
|
||||
return result, s3err.ErrNone
|
||||
|
||||
case versioningState == s3_constants.VersioningEnabled:
|
||||
deleteMarkerVersionId, err := s3a.createDeleteMarker(bucket, object)
|
||||
deleteMarkerVersionId, err := s3a.createDeleteMarker(bucket, object, "", nil, "")
|
||||
if err != nil {
|
||||
glog.Errorf("deleteVersionedObject: failed to create delete marker for %s/%s: %v", bucket, object, err)
|
||||
return result, s3err.ErrInternalError
|
||||
@@ -152,7 +152,7 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
|
||||
glog.Errorf("deleteVersionedObject: failed to delete null version for %s/%s: %v", bucket, object, err)
|
||||
return result, s3err.ErrInternalError
|
||||
}
|
||||
deleteMarkerVersionId, err := s3a.createDeleteMarker(bucket, object)
|
||||
deleteMarkerVersionId, err := s3a.createDeleteMarker(bucket, object, "", nil, "")
|
||||
if err != nil {
|
||||
glog.Errorf("deleteVersionedObject: failed to create delete marker for suspended versioning %s/%s: %v", bucket, object, err)
|
||||
return result, s3err.ErrInternalError
|
||||
@@ -214,33 +214,104 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
|
||||
}
|
||||
|
||||
var deleteResult deleteMutationResult
|
||||
deleteCode := s3a.withObjectWriteLock(bucket, object, func() s3err.ErrorCode {
|
||||
return s3a.checkDeleteIfMatch(bucket, object, versionId, versioningState, r.Header.Get(s3_constants.IfMatch), s3err.ErrPreconditionFailed)
|
||||
}, func() s3err.ErrorCode {
|
||||
if versioningConfigured {
|
||||
result, errCode := s3a.deleteVersionedObject(r, bucket, object, versionId, versioningState)
|
||||
if errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
var deleteCode s3err.ErrorCode
|
||||
|
||||
// Fast path: route an unversioned object delete to its owner filer, which
|
||||
// serializes it and evaluates the If-Match precondition under the per-path
|
||||
// lock, avoiding the distributed lock. Falls back below for versioned /
|
||||
// object-lock buckets, unsupported conditions, or an unreachable owner.
|
||||
deleteHandled := false
|
||||
if !versioningConfigured {
|
||||
if cond, condOk := buildDeleteCondition(r); condOk {
|
||||
if owner, ownerOk := s3a.routedObjectOwner(bucket, object); ownerOk {
|
||||
resp, err := s3a.deleteEntryOnFiler(owner, bucket, object, cond)
|
||||
switch {
|
||||
case err != nil:
|
||||
glog.Warningf("DeleteObjectHandler: routed delete to %s failed for %s/%s, falling back to lock: %v", owner, bucket, object, err)
|
||||
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
|
||||
deleteCode, deleteHandled = s3err.ErrPreconditionFailed, true
|
||||
case resp.Error != "":
|
||||
// Fall back to the lock path, which carries extra handling the
|
||||
// raw DeleteEntry lacks (e.g. demoting a directory marker that
|
||||
// still has children instead of failing on a non-empty folder).
|
||||
glog.Warningf("DeleteObjectHandler: routed delete to %s returned %q for %s/%s, falling back to lock", owner, resp.Error, bucket, object)
|
||||
default:
|
||||
deleteCode, deleteHandled = s3err.ErrNone, true
|
||||
}
|
||||
}
|
||||
deleteResult = result
|
||||
}
|
||||
}
|
||||
|
||||
// Fast path: a versioning-enabled delete (no specific version) creates a
|
||||
// delete marker — a unique marker file plus an atomic latest-pointer flip. We
|
||||
// route it to the .versions owner, off the distributed lock. Suspended
|
||||
// versioning (multi-step) and version-specific deletes keep the lock path.
|
||||
if !deleteHandled && versionId == "" && versioningState == s3_constants.VersioningEnabled {
|
||||
if cond, condOk := buildDeleteCondition(r); condOk {
|
||||
if owner := s3a.objectWriteOwner(bucket, s3_constants.NormalizeObjectKey(object)); owner != "" {
|
||||
vid, err := s3a.createDeleteMarker(bucket, object, owner, cond, "")
|
||||
switch {
|
||||
case err == nil:
|
||||
deleteResult = deleteMutationResult{versionId: vid, deleteMarker: true}
|
||||
deleteCode, deleteHandled = s3err.ErrNone, true
|
||||
case errors.Is(err, errVersionedPreconditionFailed):
|
||||
deleteCode, deleteHandled = s3err.ErrPreconditionFailed, true
|
||||
default:
|
||||
glog.Warningf("DeleteObjectHandler: routed delete marker for %s/%s failed, falling back to lock: %v", bucket, object, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fast path: a suspended-versioning delete (no specific version) removes the
|
||||
// null version (the main object entry) and adds a delete marker — the op does
|
||||
// both atomically under the object-key lock, so it serializes with the (also
|
||||
// routed) suspended PUT. Routed only without If-Match: that condition targets
|
||||
// the main object, not the .versions pointer the op evaluates, so a
|
||||
// conditional suspended delete stays on the lock path.
|
||||
if !deleteHandled && versionId == "" && versioningState == s3_constants.VersioningSuspended {
|
||||
if cond, condOk := buildDeleteCondition(r); condOk && cond.Kind == filer_pb.WriteCondition_NONE {
|
||||
if owner := s3a.objectWriteOwner(bucket, s3_constants.NormalizeObjectKey(object)); owner != "" {
|
||||
nullPath := s3a.toFilerPath(bucket, s3_constants.NormalizeObjectKey(object))
|
||||
vid, err := s3a.createDeleteMarker(bucket, object, owner, cond, nullPath)
|
||||
if err == nil {
|
||||
deleteResult = deleteMutationResult{versionId: vid, deleteMarker: true}
|
||||
deleteCode, deleteHandled = s3err.ErrNone, true
|
||||
} else {
|
||||
glog.Warningf("DeleteObjectHandler: routed suspended delete for %s/%s failed, falling back to lock: %v", bucket, object, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !deleteHandled {
|
||||
deleteCode = s3a.withObjectWriteLock(bucket, object, func() s3err.ErrorCode {
|
||||
return s3a.checkDeleteIfMatch(bucket, object, versionId, versioningState, r.Header.Get(s3_constants.IfMatch), s3err.ErrPreconditionFailed)
|
||||
}, func() s3err.ErrorCode {
|
||||
if versioningConfigured {
|
||||
result, errCode := s3a.deleteVersionedObject(r, bucket, object, versionId, versioningState)
|
||||
if errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
deleteResult = result
|
||||
return s3err.ErrNone
|
||||
}
|
||||
|
||||
governanceBypassAllowed := s3a.evaluateGovernanceBypassRequest(r, bucket, object)
|
||||
if err := s3a.enforceObjectLockProtections(r, bucket, object, "", governanceBypassAllowed); err != nil {
|
||||
glog.V(2).Infof("DeleteObjectHandler: object lock check failed for %s/%s: %v", bucket, object, err)
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
if err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return s3a.deleteUnversionedObjectWithClient(client, bucket, object, false)
|
||||
}); err != nil {
|
||||
glog.Errorf("DeleteObjectHandler: failed to delete %s/%s: %v", bucket, object, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
|
||||
return s3err.ErrNone
|
||||
}
|
||||
|
||||
governanceBypassAllowed := s3a.evaluateGovernanceBypassRequest(r, bucket, object)
|
||||
if err := s3a.enforceObjectLockProtections(r, bucket, object, "", governanceBypassAllowed); err != nil {
|
||||
glog.V(2).Infof("DeleteObjectHandler: object lock check failed for %s/%s: %v", bucket, object, err)
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
if err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return s3a.deleteUnversionedObjectWithClient(client, bucket, object, false)
|
||||
}); err != nil {
|
||||
glog.Errorf("DeleteObjectHandler: failed to delete %s/%s: %v", bucket, object, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
|
||||
return s3err.ErrNone
|
||||
})
|
||||
})
|
||||
}
|
||||
if deleteCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, deleteCode)
|
||||
return
|
||||
|
||||
@@ -109,7 +109,7 @@ func (s3a *S3ApiServer) ListObjectsV2Handler(w http.ResponseWriter, r *http.Requ
|
||||
// Adjust marker if it ends with delimiter to skip all entries with that prefix
|
||||
marker = adjustMarkerForDelimiter(marker, delimiter)
|
||||
|
||||
response, err := s3a.listFilerEntries(bucket, originalPrefix, maxKeys, marker, delimiter, encodingTypeUrl, fetchOwner)
|
||||
response, err := s3a.listFilerEntries(r.Context(), bucket, originalPrefix, maxKeys, marker, delimiter, encodingTypeUrl, fetchOwner)
|
||||
|
||||
if err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
@@ -173,7 +173,7 @@ func (s3a *S3ApiServer) ListObjectsV1Handler(w http.ResponseWriter, r *http.Requ
|
||||
// Adjust marker if it ends with delimiter to skip all entries with that prefix
|
||||
marker = adjustMarkerForDelimiter(marker, delimiter)
|
||||
|
||||
response, err := s3a.listFilerEntries(bucket, originalPrefix, uint16(maxKeys), marker, delimiter, encodingTypeUrl, true)
|
||||
response, err := s3a.listFilerEntries(r.Context(), bucket, originalPrefix, uint16(maxKeys), marker, delimiter, encodingTypeUrl, true)
|
||||
|
||||
if err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
@@ -232,7 +232,7 @@ func sanitizeV1MarkerEcho(response *ListBucketResult, marker string, encodingTyp
|
||||
}
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) listFilerEntries(bucket string, originalPrefix string, maxKeys uint16, originalMarker string, delimiter string, encodingTypeUrl bool, fetchOwner bool) (response ListBucketResult, err error) {
|
||||
func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, bucket string, originalPrefix string, maxKeys uint16, originalMarker string, delimiter string, encodingTypeUrl bool, fetchOwner bool) (response ListBucketResult, err error) {
|
||||
// convert full path prefix into directory name and prefix for entry name
|
||||
requestDir, prefix, marker := normalizePrefixMarker(originalPrefix, originalMarker)
|
||||
bucketPrefix := s3a.bucketPrefix(bucket)
|
||||
@@ -307,7 +307,7 @@ func (s3a *S3ApiServer) listFilerEntries(bucket string, originalPrefix string, m
|
||||
if normalizedPrefix != "" {
|
||||
relativePath := strings.TrimPrefix(fmt.Sprintf("%s/%s", dir, entry.Name), bucketPrefix)
|
||||
relativePath = strings.TrimPrefix(relativePath, "/")
|
||||
if normalizedPrefix == relativePath && !s3a.hasChildren(bucket, relativePath) && !entry.IsDirectoryKeyObject() {
|
||||
if normalizedPrefix == relativePath && !s3a.hasChildren(ctx, bucket, relativePath) && !entry.IsDirectoryKeyObject() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -457,7 +457,7 @@ func (s3a *S3ApiServer) PutObjectPartHandler(w http.ResponseWriter, r *http.Requ
|
||||
// transient .uploads/<id>/<n> path, and a part write would otherwise
|
||||
// start the TTL clock before CompleteMultipartUpload ever assembled
|
||||
// the object.
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, dataReader, bucket, "", partID, 0, nil)
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, dataReader, bucket, "", partID, 0, nil, false)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.Errorf("PutObjectPart: putToFiler failed with error code %v for bucket=%s, object=%s, partNumber=%d",
|
||||
errCode, bucket, object, partID)
|
||||
|
||||
@@ -135,7 +135,7 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
|
||||
// fields and boundaries inflates ContentLength relative to the
|
||||
// object body, which would mis-evaluate any size-filtered rule.
|
||||
ttlSec := s3a.lifecycleTTLForObjectWrite(bucket, object, fileSize)
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, fileBody, bucket, object, 1, ttlSec, nil)
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, fileBody, bucket, object, 1, ttlSec, nil, false)
|
||||
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
|
||||
@@ -297,7 +297,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
|
||||
ttlSec := s3a.lifecycleTTLForObjectWrite(bucket, object, r.ContentLength)
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, dataReader, bucket, object, 1, ttlSec, nil)
|
||||
etag, errCode, sseMetadata := s3a.putToFiler(r, filePath, dataReader, bucket, object, 1, ttlSec, nil, false)
|
||||
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
@@ -359,7 +359,12 @@ func (s3a *S3ApiServer) withObjectWriteLock(bucket, object string, preconditionF
|
||||
// pass 0 because their own keys aren't the user-visible object the rule
|
||||
// targets and a part write would otherwise bind a TTL clock starting
|
||||
// before CompleteMultipartUpload.
|
||||
func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader io.Reader, bucket string, object string, partNumber int, lifecycleTTLSec int32, afterCreate func(entry *filer_pb.Entry) s3err.ErrorCode) (etag string, code s3err.ErrorCode, sseMetadata SSEResponseMetadata) {
|
||||
// uniqueVersionPath marks writes whose target path never collides (an S3 object
|
||||
// version file under <object>/.versions/<versionId>). For those, putToFiler
|
||||
// skips the object write lock and the gateway precondition: the afterCreate hook
|
||||
// finalizes the version atomically on the .versions owner (precondition + demote
|
||||
// + pointer flip) and rolls back the file if that fails.
|
||||
func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader io.Reader, bucket string, object string, partNumber int, lifecycleTTLSec int32, afterCreate func(entry *filer_pb.Entry) s3err.ErrorCode, uniqueVersionPath bool) (etag string, code s3err.ErrorCode, sseMetadata SSEResponseMetadata) {
|
||||
// NEW OPTIMIZATION: Write directly to volume servers, bypassing filer proxy
|
||||
// This eliminates the filer proxy overhead for PUT operations
|
||||
// Note: filePath is now passed directly instead of URL (no parsing needed)
|
||||
@@ -802,7 +807,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
|
||||
}
|
||||
return s3a.checkConditionalHeaders(r, bucket, object)
|
||||
}
|
||||
createCode := s3a.withObjectWriteLock(bucket, object, preconditionFn, func() s3err.ErrorCode {
|
||||
createUnderLock := func() s3err.ErrorCode {
|
||||
createErr = s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
req := &filer_pb.CreateEntryRequest{
|
||||
Directory: path.Dir(filePath),
|
||||
@@ -831,7 +836,52 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
|
||||
}
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
}
|
||||
|
||||
// Fast path: route the create to the object key's owner filer, which
|
||||
// serializes it with its local per-path lock and evaluates the precondition,
|
||||
// avoiding the distributed lock. Restricted to the safe subset by
|
||||
// routedObjectWrite; falls back to the lock for everything else and if the
|
||||
// owner is unreachable.
|
||||
var createCode s3err.ErrorCode
|
||||
routed := false
|
||||
if uniqueVersionPath {
|
||||
// The version-file path never collides, so no object write lock is needed.
|
||||
// createUnderLock creates the file and runs afterCreate, which finalizes
|
||||
// the version (precondition + demote + pointer flip) atomically on the
|
||||
// .versions owner and rolls back the file on failure.
|
||||
createCode, routed = createUnderLock(), true
|
||||
}
|
||||
if !routed {
|
||||
if owner, cond, ok := s3a.routedObjectWrite(r, bucket, object, afterCreate != nil); ok {
|
||||
req := &filer_pb.CreateEntryRequest{
|
||||
Directory: path.Dir(filePath),
|
||||
Entry: entry,
|
||||
Condition: cond,
|
||||
}
|
||||
resp, err := s3a.createEntryOnFiler(owner, req)
|
||||
switch {
|
||||
case err != nil:
|
||||
glog.Warningf("putToFiler: routed create to %s failed for %s, falling back to lock: %v", owner, filePath, err)
|
||||
case resp.ErrorCode != filer_pb.FilerError_OK:
|
||||
// Map known filer error codes to the same S3 errors the lock path
|
||||
// would produce; fall back for any code this does not recognize.
|
||||
if code, mapped := filerErrorCodeToS3Error(resp.ErrorCode); mapped {
|
||||
createCode, routed = code, true
|
||||
} else {
|
||||
glog.Warningf("putToFiler: routed create to %s returned code %v for %s, falling back to lock", owner, resp.ErrorCode, filePath)
|
||||
}
|
||||
case resp.Error != "":
|
||||
// In-band error without a code: fall back so the lock path maps it.
|
||||
glog.Warningf("putToFiler: routed create to %s returned %q for %s, falling back to lock", owner, resp.Error, filePath)
|
||||
default:
|
||||
entryCreated, createCode, routed = true, s3err.ErrNone, true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !routed {
|
||||
createCode = s3a.withObjectWriteLock(bucket, object, preconditionFn, createUnderLock)
|
||||
}
|
||||
if createCode != s3err.ErrNone {
|
||||
if createErr != nil {
|
||||
glog.Errorf("putToFiler: failed to create entry for %s: %v", filePath, createErr)
|
||||
@@ -1280,18 +1330,22 @@ func (s3a *S3ApiServer) putSuspendedVersioningObject(r *http.Request, bucket, ob
|
||||
// it runs while withObjectWriteLock is still held in putToFiler.
|
||||
// Doing it after putToFiler returns would race a concurrent PUT
|
||||
// promoting a newer latest, which we'd then incorrectly wipe.
|
||||
etag, errCode, sseMetadata = s3a.putToFiler(r, filePath, body, bucket, normalizedObject, 1, 0, func(_ *filer_pb.Entry) s3err.ErrorCode {
|
||||
if err := s3a.updateIsLatestFlagsForSuspendedVersioning(bucket, normalizedObject); err != nil {
|
||||
// Best-effort: a stale IsLatest flag is recoverable on the
|
||||
// next list-versions resync, so don't fail the PUT.
|
||||
glog.Warningf("putSuspendedVersioningObject: failed to update IsLatest flags: %v", err)
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
// The null version is written to the main object path, so this is a
|
||||
// single-entry object write — route it on the object key like a normal PUT
|
||||
// (no afterCreate, so putToFiler can take the route-by-key path and skip the
|
||||
// distributed lock). The IsLatest flag rewrite over existing versions is
|
||||
// best-effort bookkeeping, so it runs after the write rather than inside the
|
||||
// atomic boundary.
|
||||
etag, errCode, sseMetadata = s3a.putToFiler(r, filePath, body, bucket, normalizedObject, 1, 0, nil, false)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.Errorf("putSuspendedVersioningObject: failed to upload object: %v", errCode)
|
||||
return "", errCode, SSEResponseMetadata{}
|
||||
}
|
||||
if err := s3a.updateIsLatestFlagsForSuspendedVersioning(bucket, normalizedObject); err != nil {
|
||||
// Best-effort: a stale IsLatest flag is recoverable on the next
|
||||
// list-versions resync, so don't fail the PUT.
|
||||
glog.Warningf("putSuspendedVersioningObject: failed to update IsLatest flags: %v", err)
|
||||
}
|
||||
|
||||
glog.V(2).Infof("putSuspendedVersioningObject: successfully created null version for %s/%s", bucket, object)
|
||||
|
||||
@@ -1453,13 +1507,13 @@ func (s3a *S3ApiServer) putVersionedObject(r *http.Request, bucket, object strin
|
||||
// Versioned bucket: resolver returns 0 by construction. Pass 0
|
||||
// directly — versioned objects sit on regular volumes and the
|
||||
// lifecycle worker handles their expiration.
|
||||
etag, errCode, sseMetadata = s3a.putToFiler(r, versionFilePath, body, bucket, normalizedObject, 1, 0, func(versionEntry *filer_pb.Entry) s3err.ErrorCode {
|
||||
if err := s3a.updateLatestVersionInDirectory(bucket, normalizedObject, versionId, versionFileName, versionEntry); err != nil {
|
||||
glog.Errorf("putVersionedObject: failed to update latest version in directory: %v", err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
//
|
||||
// The version file lives at a unique <object>/.versions/<versionId> path, so
|
||||
// when the .versions owner is known the finalize (precondition + demote +
|
||||
// pointer flip) routes there to run atomically under one local lock, and
|
||||
// putToFiler skips the object write lock. Otherwise it stays on the lock path.
|
||||
finalize, routedVersioned := s3a.versionedAfterCreate(r, bucket, normalizedObject, versionId, versionFileName)
|
||||
etag, errCode, sseMetadata = s3a.putToFiler(r, versionFilePath, body, bucket, normalizedObject, 1, 0, finalize, routedVersioned)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.Errorf("putVersionedObject: failed to upload version: %v", errCode)
|
||||
return "", "", errCode, SSEResponseMetadata{}
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// routedObjectOwner returns the filer that owns this object's metadata for
|
||||
// route-by-key on a single-entry object write, or ok=false when the write must
|
||||
// keep the distributed lock. Only versioning-*enabled* buckets are excluded:
|
||||
// their writes go to <obj>/.versions and flip the latest pointer (the versioned
|
||||
// finalize path handles those). Suspended and unversioned writes both go to the
|
||||
// main object path, so they route here. Object-lock buckets stay on the lock
|
||||
// path. On any lookup error it falls back to be safe.
|
||||
func (s3a *S3ApiServer) routedObjectOwner(bucket, object string) (pb.ServerAddress, bool) {
|
||||
if object == "" {
|
||||
return "", false
|
||||
}
|
||||
if enabled, err := s3a.isVersioningEnabled(bucket); err != nil || enabled {
|
||||
return "", false
|
||||
}
|
||||
// objectWriteOwner already excludes object-lock buckets (they stay fully on
|
||||
// the distributed lock), returning "" for them.
|
||||
owner := s3a.objectWriteOwner(bucket, object)
|
||||
if owner == "" {
|
||||
return "", false
|
||||
}
|
||||
return owner, true
|
||||
}
|
||||
|
||||
// routedObjectWrite decides whether an object PUT can take the route-by-key
|
||||
// fast path: the metadata write goes straight to the key's owner filer, which
|
||||
// serializes it with its local per-path lock and evaluates the precondition,
|
||||
// instead of acquiring a distributed lock. It returns the owner filer and the
|
||||
// reduced precondition, or ok=false to fall back to withObjectWriteLock.
|
||||
//
|
||||
// The fast path additionally requires no post-create hook and a precondition
|
||||
// that reduces to one primitive.
|
||||
func (s3a *S3ApiServer) routedObjectWrite(r *http.Request, bucket, object string, hasAfterCreate bool) (owner pb.ServerAddress, cond *filer_pb.WriteCondition, ok bool) {
|
||||
if hasAfterCreate {
|
||||
return "", nil, false
|
||||
}
|
||||
cond, condOk := buildWriteCondition(r)
|
||||
if !condOk {
|
||||
return "", nil, false
|
||||
}
|
||||
owner, ok = s3a.routedObjectOwner(bucket, object)
|
||||
if !ok {
|
||||
return "", nil, false
|
||||
}
|
||||
return owner, cond, true
|
||||
}
|
||||
|
||||
// buildWriteCondition reduces the request's conditional headers to a single
|
||||
// WriteCondition primitive the filer can evaluate. It only handles the
|
||||
// unambiguous single-condition cases; anything else (header combinations,
|
||||
// time-based conditions, ETag lists, weak ETags) returns ok=false so the caller
|
||||
// keeps the existing gateway-side evaluation under the distributed lock.
|
||||
func buildWriteCondition(r *http.Request) (*filer_pb.WriteCondition, bool) {
|
||||
headers, errCode := parseConditionalHeaders(r)
|
||||
if errCode != s3err.ErrNone {
|
||||
return nil, false
|
||||
}
|
||||
if !headers.isSet {
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_NONE}, true
|
||||
}
|
||||
// Time-based conditions are rare on writes; let the lock path handle them.
|
||||
if !headers.ifModifiedSince.IsZero() || !headers.ifUnmodifiedSince.IsZero() {
|
||||
return nil, false
|
||||
}
|
||||
hasMatch := headers.ifMatch != ""
|
||||
hasNoneMatch := headers.ifNoneMatch != ""
|
||||
switch {
|
||||
case hasMatch && !hasNoneMatch:
|
||||
if headers.ifMatch == "*" {
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_EXISTS}, true
|
||||
}
|
||||
if etag, single := singleStrongETag(headers.ifMatch); single {
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etag: etag}, true
|
||||
}
|
||||
return nil, false
|
||||
case hasNoneMatch && !hasMatch:
|
||||
if headers.ifNoneMatch == "*" {
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS}, true
|
||||
}
|
||||
if etag, single := singleStrongETag(headers.ifNoneMatch); single {
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_NOT_MATCH, Etag: etag}, true
|
||||
}
|
||||
return nil, false
|
||||
default:
|
||||
// Both If-Match and If-None-Match present — leave to the lock path.
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
// singleStrongETag returns the normalized ETag when the header carries exactly
|
||||
// one strong ETag, and false for ETag lists or weak ("W/") ETags, which the
|
||||
// fast path does not replicate.
|
||||
func singleStrongETag(v string) (string, bool) {
|
||||
v = strings.TrimSpace(v)
|
||||
if strings.Contains(v, ",") {
|
||||
return "", false
|
||||
}
|
||||
if strings.HasPrefix(v, "W/") || strings.HasPrefix(v, "w/") {
|
||||
return "", false
|
||||
}
|
||||
return strings.Trim(v, `"`), true
|
||||
}
|
||||
|
||||
// mkFileRouted builds a file entry the way filer_pb.MkFile does, applies fn, and
|
||||
// routes the CreateEntry (with an optional precondition) to the given owner filer
|
||||
// so its local per-path lock serializes the write. Used by callers that build an
|
||||
// object via a modifier (e.g. multipart completion) but want the routed,
|
||||
// distributed-lock-free write path.
|
||||
func (s3a *S3ApiServer) mkFileRouted(owner pb.ServerAddress, dir, name string, chunks []*filer_pb.FileChunk, cond *filer_pb.WriteCondition, fn func(*filer_pb.Entry)) s3err.ErrorCode {
|
||||
now := time.Now().Unix()
|
||||
entry := &filer_pb.Entry{
|
||||
Name: name,
|
||||
IsDirectory: false,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: now,
|
||||
Crtime: now,
|
||||
FileMode: uint32(0770),
|
||||
Uid: filer_pb.OS_UID,
|
||||
Gid: filer_pb.OS_GID,
|
||||
},
|
||||
Chunks: chunks,
|
||||
}
|
||||
if fn != nil {
|
||||
fn(entry)
|
||||
}
|
||||
resp, err := s3a.createEntryOnFiler(owner, &filer_pb.CreateEntryRequest{
|
||||
Directory: dir,
|
||||
Entry: entry,
|
||||
Condition: cond,
|
||||
})
|
||||
switch {
|
||||
case err != nil:
|
||||
glog.Errorf("mkFileRouted: %s/%s on %s: %v", dir, name, owner, err)
|
||||
return s3err.ErrInternalError
|
||||
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
|
||||
return s3err.ErrPreconditionFailed
|
||||
case resp.ErrorCode != filer_pb.FilerError_OK:
|
||||
if code, ok := filerErrorCodeToS3Error(resp.ErrorCode); ok {
|
||||
return code
|
||||
}
|
||||
glog.Errorf("mkFileRouted: %s/%s unexpected code %v", dir, name, resp.ErrorCode)
|
||||
return s3err.ErrInternalError
|
||||
case resp.Error != "":
|
||||
glog.Errorf("mkFileRouted: %s/%s: %s", dir, name, resp.Error)
|
||||
return s3err.ErrInternalError
|
||||
default:
|
||||
return s3err.ErrNone
|
||||
}
|
||||
}
|
||||
|
||||
// createEntryOnFiler sends a CreateEntry directly to the given owner filer so
|
||||
// its local per-path lock serializes the write. The raw response is returned so
|
||||
// the caller can distinguish PRECONDITION_FAILED from other outcomes.
|
||||
func (s3a *S3ApiServer) createEntryOnFiler(owner pb.ServerAddress, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
||||
var resp *filer_pb.CreateEntryResponse
|
||||
err := pb.WithFilerClient(false, 0, owner, s3a.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
var e error
|
||||
resp, e = client.CreateEntry(context.Background(), req)
|
||||
return e
|
||||
})
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// filerErrorCodeToS3Error maps a routed response's machine-readable FilerError
|
||||
// to the same S3 error the lock path produces via filerErrorToS3Error, so the
|
||||
// fast path keeps identical semantics. ok is false for codes it does not map,
|
||||
// signalling the caller to fall back to the lock path for exact behavior.
|
||||
func filerErrorCodeToS3Error(code filer_pb.FilerError) (s3err.ErrorCode, bool) {
|
||||
switch code {
|
||||
case filer_pb.FilerError_PRECONDITION_FAILED:
|
||||
return s3err.ErrPreconditionFailed, true
|
||||
case filer_pb.FilerError_ENTRY_NAME_TOO_LONG:
|
||||
return s3err.ErrKeyTooLongError, true
|
||||
case filer_pb.FilerError_PARENT_IS_FILE, filer_pb.FilerError_EXISTING_IS_FILE:
|
||||
return s3err.ErrExistingObjectIsFile, true
|
||||
case filer_pb.FilerError_EXISTING_IS_DIRECTORY:
|
||||
return s3err.ErrExistingObjectIsDirectory, true
|
||||
default:
|
||||
return s3err.ErrNone, false
|
||||
}
|
||||
}
|
||||
|
||||
// buildDeleteCondition reduces a DeleteObject's If-Match header to a primitive.
|
||||
// DeleteObject only honors If-Match (matching checkDeleteIfMatch), so other
|
||||
// conditional headers are ignored here as they are on the existing path.
|
||||
func buildDeleteCondition(r *http.Request) (*filer_pb.WriteCondition, bool) {
|
||||
ifMatch := strings.TrimSpace(r.Header.Get(s3_constants.IfMatch))
|
||||
switch {
|
||||
case ifMatch == "":
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_NONE}, true
|
||||
case ifMatch == "*":
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_EXISTS}, true
|
||||
default:
|
||||
if etag, single := singleStrongETag(ifMatch); single {
|
||||
return &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etag: etag}, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
// deleteEntryOnFiler sends a non-recursive DeleteEntry for the object directly
|
||||
// to its owner filer, which serializes it and evaluates the precondition under
|
||||
// the per-path lock. Flags mirror the unversioned delete path (doDeleteEntry).
|
||||
func (s3a *S3ApiServer) deleteEntryOnFiler(owner pb.ServerAddress, bucket, object string, cond *filer_pb.WriteCondition) (*filer_pb.DeleteEntryResponse, error) {
|
||||
dir, name := util.NewFullPath(s3a.bucketDir(bucket), object).DirAndName()
|
||||
var resp *filer_pb.DeleteEntryResponse
|
||||
err := pb.WithFilerClient(false, 0, owner, s3a.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
var e error
|
||||
resp, e = client.DeleteEntry(context.Background(), &filer_pb.DeleteEntryRequest{
|
||||
Directory: dir,
|
||||
Name: name,
|
||||
IsDeleteData: true,
|
||||
IsRecursive: false,
|
||||
IgnoreRecursiveError: true,
|
||||
Condition: cond,
|
||||
})
|
||||
return e
|
||||
})
|
||||
return resp, err
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
func reqWith(headers map[string]string) *http.Request {
|
||||
r, _ := http.NewRequest(http.MethodPut, "/b/o", nil)
|
||||
for k, v := range headers {
|
||||
r.Header.Set(k, v)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func TestBuildWriteCondition(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
headers map[string]string
|
||||
wantOk bool
|
||||
want filer_pb.WriteCondition_Kind
|
||||
wantTag string
|
||||
}{
|
||||
{"none", nil, true, filer_pb.WriteCondition_NONE, ""},
|
||||
{"ifnonematch-star", map[string]string{s3_constants.IfNoneMatch: "*"}, true, filer_pb.WriteCondition_IF_NOT_EXISTS, ""},
|
||||
{"ifmatch-star", map[string]string{s3_constants.IfMatch: "*"}, true, filer_pb.WriteCondition_IF_EXISTS, ""},
|
||||
{"ifmatch-etag", map[string]string{s3_constants.IfMatch: `"abc"`}, true, filer_pb.WriteCondition_IF_ETAG_MATCH, "abc"},
|
||||
{"ifnonematch-etag", map[string]string{s3_constants.IfNoneMatch: `"abc"`}, true, filer_pb.WriteCondition_IF_ETAG_NOT_MATCH, "abc"},
|
||||
// Cases that must fall back to the lock path:
|
||||
{"both", map[string]string{s3_constants.IfMatch: "*", s3_constants.IfNoneMatch: "*"}, false, 0, ""},
|
||||
{"etag-list", map[string]string{s3_constants.IfMatch: `"a","b"`}, false, 0, ""},
|
||||
{"weak-etag", map[string]string{s3_constants.IfMatch: `W/"abc"`}, false, 0, ""},
|
||||
{"time-based", map[string]string{s3_constants.IfUnmodifiedSince: "Wed, 21 Oct 2015 07:28:00 GMT"}, false, 0, ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
cond, ok := buildWriteCondition(reqWith(tc.headers))
|
||||
if ok != tc.wantOk {
|
||||
t.Errorf("%s: ok=%v want %v", tc.name, ok, tc.wantOk)
|
||||
continue
|
||||
}
|
||||
if ok {
|
||||
if cond.Kind != tc.want {
|
||||
t.Errorf("%s: kind=%v want %v", tc.name, cond.Kind, tc.want)
|
||||
}
|
||||
if cond.Etag != tc.wantTag {
|
||||
t.Errorf("%s: etag=%q want %q", tc.name, cond.Etag, tc.wantTag)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildDeleteCondition(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
ifMatch string
|
||||
wantOk bool
|
||||
want filer_pb.WriteCondition_Kind
|
||||
wantTag string
|
||||
}{
|
||||
{"none", "", true, filer_pb.WriteCondition_NONE, ""},
|
||||
{"star", "*", true, filer_pb.WriteCondition_IF_EXISTS, ""},
|
||||
{"etag", `"abc"`, true, filer_pb.WriteCondition_IF_ETAG_MATCH, "abc"},
|
||||
{"list", `"a","b"`, false, 0, ""},
|
||||
{"weak", `W/"abc"`, false, 0, ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
h := map[string]string{}
|
||||
if tc.ifMatch != "" {
|
||||
h[s3_constants.IfMatch] = tc.ifMatch
|
||||
}
|
||||
cond, ok := buildDeleteCondition(reqWith(h))
|
||||
if ok != tc.wantOk {
|
||||
t.Errorf("%s: ok=%v want %v", tc.name, ok, tc.wantOk)
|
||||
continue
|
||||
}
|
||||
if ok && (cond.Kind != tc.want || cond.Etag != tc.wantTag) {
|
||||
t.Errorf("%s: got kind=%v etag=%q want kind=%v etag=%q", tc.name, cond.Kind, cond.Etag, tc.want, tc.wantTag)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// errVersionedPreconditionFailed is returned by versioned finalize helpers whose
|
||||
// contract is (…, error) when the routed FinalizeVersionedWrite reports a failed
|
||||
// precondition, so callers can surface it as 412 rather than a generic 500.
|
||||
var errVersionedPreconditionFailed = errors.New("versioned write precondition failed")
|
||||
|
||||
// finalizeCodeToError adapts a routedVersionedFinalize result to an error: nil on
|
||||
// success, the precondition sentinel on 412, else a generic error.
|
||||
func finalizeCodeToError(code s3err.ErrorCode) error {
|
||||
switch code {
|
||||
case s3err.ErrNone:
|
||||
return nil
|
||||
case s3err.ErrPreconditionFailed:
|
||||
return errVersionedPreconditionFailed
|
||||
default:
|
||||
return fmt.Errorf("versioned finalize failed: code %v", code)
|
||||
}
|
||||
}
|
||||
|
||||
// objectWriteOwner returns the filer that owns all of an object's writes, or ""
|
||||
// when no ring view is available. It hashes the object key with the same prefix
|
||||
// the non-versioned path uses (routedObjectOwner), so normal, suspended, and
|
||||
// versioned writes to the same object all resolve to one owner and serialize on
|
||||
// the same lock — regardless of versioning state. The whole object subtree
|
||||
// (object, .versions dir, version files) belongs to this owner.
|
||||
func (s3a *S3ApiServer) objectWriteOwner(bucket, object string) pb.ServerAddress {
|
||||
if s3a.objectWriteLockClient == nil {
|
||||
return ""
|
||||
}
|
||||
// Object-lock (WORM) buckets keep ALL of their writes on the distributed
|
||||
// lock. Retention enforcement is a gateway-side check that the per-path-locked
|
||||
// filer ops don't perform, so routing only some of such a bucket's writes
|
||||
// would split serialization between the entry lock and the distributed lock
|
||||
// (they don't serialize against each other). Excluding the bucket entirely
|
||||
// keeps it internally consistent.
|
||||
if locked, err := s3a.isObjectLockEnabled(bucket); err != nil || locked {
|
||||
return ""
|
||||
}
|
||||
return s3a.objectWriteLockClient.PrimaryForKey("s3.object.write:" + s3a.toFilerPath(bucket, object))
|
||||
}
|
||||
|
||||
// versionedPointerExtended computes the Extended keys to set and to clear on the
|
||||
// .versions directory entry for a new latest version, mirroring
|
||||
// setCachedListMetadata (clear cached fields, then set id/filename + cached
|
||||
// size/mtime/etag/owner/delete-marker). The filer applies deletes before sets.
|
||||
func versionedPointerExtended(versionId, versionFileName string, versionEntry *filer_pb.Entry) (set map[string][]byte, del []string) {
|
||||
set = map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte(versionId),
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte(versionFileName),
|
||||
}
|
||||
if versionEntry.Attributes != nil {
|
||||
set[s3_constants.ExtLatestVersionSizeKey] = []byte(strconv.FormatUint(versionEntry.Attributes.FileSize, 10))
|
||||
set[s3_constants.ExtLatestVersionMtimeKey] = []byte(strconv.FormatInt(versionEntry.Attributes.Mtime, 10))
|
||||
}
|
||||
isDeleteMarker := []byte("false")
|
||||
if versionEntry.Extended != nil {
|
||||
if v, ok := versionEntry.Extended[s3_constants.ExtETagKey]; ok {
|
||||
set[s3_constants.ExtLatestVersionETagKey] = v
|
||||
}
|
||||
if v, ok := versionEntry.Extended[s3_constants.ExtAmzOwnerKey]; ok {
|
||||
set[s3_constants.ExtLatestVersionOwnerKey] = v
|
||||
}
|
||||
if v, ok := versionEntry.Extended[s3_constants.ExtDeleteMarkerKey]; ok {
|
||||
isDeleteMarker = v
|
||||
}
|
||||
}
|
||||
set[s3_constants.ExtLatestVersionIsDeleteMarker] = isDeleteMarker
|
||||
del = []string{
|
||||
s3_constants.ExtLatestVersionSizeKey,
|
||||
s3_constants.ExtLatestVersionMtimeKey,
|
||||
s3_constants.ExtLatestVersionETagKey,
|
||||
s3_constants.ExtLatestVersionOwnerKey,
|
||||
s3_constants.ExtLatestVersionIsDeleteMarker,
|
||||
}
|
||||
return set, del
|
||||
}
|
||||
|
||||
// routedVersionedFinalize finalizes a versioned write by routing the precondition
|
||||
// check, the demote of the previous latest, and the pointer flip to the owner of
|
||||
// the object's .versions directory, where they run atomically under one local
|
||||
// lock. The caller (putToFiler with uniqueVersionPath) has already created the
|
||||
// version file and skips the object write lock and gateway precondition. A
|
||||
// transport/in-band error maps to InternalError (the client retries); there is
|
||||
// no silent non-atomic fallback.
|
||||
func (s3a *S3ApiServer) routedVersionedFinalize(owner pb.ServerAddress, bucket, object, versionId, versionFileName string, versionEntry *filer_pb.Entry, cond *filer_pb.WriteCondition, deletePath string) s3err.ErrorCode {
|
||||
set, del := versionedPointerExtended(versionId, versionFileName, versionEntry)
|
||||
req := &filer_pb.FinalizeVersionedWriteRequest{
|
||||
LockKey: s3a.toFilerPath(bucket, object),
|
||||
DeletePath: deletePath,
|
||||
VersionsDir: s3a.toFilerPath(bucket, object+s3_constants.VersionsFolder),
|
||||
SetExtended: set,
|
||||
DeleteExtended: del,
|
||||
PriorLatestKey: s3_constants.ExtLatestVersionFileNameKey,
|
||||
NoncurrentSinceKey: s3_constants.ExtNoncurrentSinceNsKey,
|
||||
NoncurrentSinceNs: time.Now().UnixNano(),
|
||||
Condition: cond,
|
||||
LatestEtagKey: s3_constants.ExtLatestVersionETagKey,
|
||||
LatestDeleteMarkerKey: s3_constants.ExtLatestVersionIsDeleteMarker,
|
||||
}
|
||||
var resp *filer_pb.FinalizeVersionedWriteResponse
|
||||
err := pb.WithFilerClient(false, 0, owner, s3a.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
var e error
|
||||
resp, e = client.FinalizeVersionedWrite(context.Background(), req)
|
||||
return e
|
||||
})
|
||||
switch {
|
||||
case err != nil:
|
||||
glog.Errorf("routedVersionedFinalize: %s/%s on %s: %v", bucket, object, owner, err)
|
||||
return s3err.ErrInternalError
|
||||
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
|
||||
return s3err.ErrPreconditionFailed
|
||||
case resp.ErrorCode != filer_pb.FilerError_OK:
|
||||
if code, ok := filerErrorCodeToS3Error(resp.ErrorCode); ok {
|
||||
return code
|
||||
}
|
||||
glog.Errorf("routedVersionedFinalize: %s/%s unexpected code %v", bucket, object, resp.ErrorCode)
|
||||
return s3err.ErrInternalError
|
||||
case resp.Error != "":
|
||||
glog.Errorf("routedVersionedFinalize: %s/%s: %s", bucket, object, resp.Error)
|
||||
return s3err.ErrInternalError
|
||||
default:
|
||||
return s3err.ErrNone
|
||||
}
|
||||
}
|
||||
|
||||
// versionedAfterCreate returns the putToFiler afterCreate hook for a versioned
|
||||
// write: the routed atomic finalize when the .versions owner is known and the
|
||||
// precondition reduces to a single primitive, otherwise the existing lock-based
|
||||
// updateLatestVersionInDirectory path. The bool reports whether the routed path
|
||||
// was selected, which the caller passes as putToFiler's uniqueVersionPath.
|
||||
func (s3a *S3ApiServer) versionedAfterCreate(r *http.Request, bucket, object, versionId, versionFileName string) (func(*filer_pb.Entry) s3err.ErrorCode, bool) {
|
||||
owner := s3a.objectWriteOwner(bucket, object)
|
||||
cond, condOk := buildWriteCondition(r)
|
||||
if owner != "" && condOk {
|
||||
return func(versionEntry *filer_pb.Entry) s3err.ErrorCode {
|
||||
return s3a.routedVersionedFinalize(owner, bucket, object, versionId, versionFileName, versionEntry, cond, "")
|
||||
}, true
|
||||
}
|
||||
return func(versionEntry *filer_pb.Entry) s3err.ErrorCode {
|
||||
if err := s3a.updateLatestVersionInDirectory(bucket, object, versionId, versionFileName, versionEntry); err != nil {
|
||||
glog.Errorf("putVersionedObject: failed to update latest version in directory: %v", err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
return s3err.ErrNone
|
||||
}, false
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
s3_constants "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
@@ -191,7 +192,13 @@ type ObjectVersion struct {
|
||||
}
|
||||
|
||||
// createDeleteMarker creates a delete marker for versioned delete operations
|
||||
func (s3a *S3ApiServer) createDeleteMarker(bucket, object string) (string, error) {
|
||||
// createDeleteMarker writes a delete-marker version and makes it the latest.
|
||||
// When routedOwner is set, the latest-pointer update (and the optional cond) run
|
||||
// atomically via FinalizeVersionedWrite on that owner, off the distributed lock;
|
||||
// otherwise it uses the lock-based updateLatestVersionInDirectory. A failed
|
||||
// routed finalize rolls back the marker file and returns
|
||||
// errVersionedPreconditionFailed for a precondition miss.
|
||||
func (s3a *S3ApiServer) createDeleteMarker(bucket, object string, routedOwner pb.ServerAddress, cond *filer_pb.WriteCondition, deleteNullPath string) (string, error) {
|
||||
// Clean up the object path first
|
||||
cleanObject := strings.TrimPrefix(object, "/")
|
||||
|
||||
@@ -242,6 +249,19 @@ func (s3a *S3ApiServer) createDeleteMarker(bucket, object string) (string, error
|
||||
},
|
||||
Extended: deleteMarkerExtended,
|
||||
}
|
||||
if routedOwner != "" {
|
||||
// Routed: precondition + demote + pointer flip run atomically on the
|
||||
// .versions owner. Roll back the marker file if it does not succeed.
|
||||
if code := s3a.routedVersionedFinalize(routedOwner, bucket, cleanObject, versionId, versionFileName, deleteMarkerEntry, cond, deleteNullPath); code != s3err.ErrNone {
|
||||
if rbErr := s3a.rmObject(versionsDir, versionFileName, true, false); rbErr != nil {
|
||||
glog.Errorf("createDeleteMarker: rollback %s/%s: %v", versionsDir, versionFileName, rbErr)
|
||||
}
|
||||
return "", finalizeCodeToError(code)
|
||||
}
|
||||
glog.V(2).Infof("createDeleteMarker: routed delete marker %s for %s/%s", versionId, bucket, object)
|
||||
return versionId, nil
|
||||
}
|
||||
|
||||
err = s3a.updateLatestVersionInDirectory(bucket, cleanObject, versionId, versionFileName, deleteMarkerEntry)
|
||||
if err != nil {
|
||||
glog.Errorf("createDeleteMarker: failed to update latest version in directory: %v", err)
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
@@ -95,6 +96,11 @@ type S3ApiServer struct {
|
||||
stsHandlers *STSHandlers // STS HTTP handlers for AssumeRoleWithWebIdentity
|
||||
cipher bool // encrypt data on volume servers
|
||||
newObjectWriteLock func(bucket, object string) objectWriteLock
|
||||
// objectWriteLockClient holds the lock-ring view used to route an object's
|
||||
// metadata writes to its owner filer (route-by-key), so that owner's local
|
||||
// per-path lock serializes them without acquiring a distributed lock. Nil
|
||||
// when no filers are configured.
|
||||
objectWriteLockClient *cluster.LockClient
|
||||
// Shared ReaderCache used by the S3 GET streaming path. It lives for the
|
||||
// lifetime of the server so that concurrent and repeat reads share a
|
||||
// single in-flight download per chunk, and so that no per-request
|
||||
@@ -152,6 +158,8 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
// Uses the battle-tested vidMap with filer-based lookups
|
||||
// Supports multiple filer addresses with automatic failover for high availability
|
||||
var filerClient *wdclient.FilerClient
|
||||
var masterClient *wdclient.MasterClient
|
||||
var objectWriteLockClient *cluster.LockClient
|
||||
if len(option.Masters) > 0 {
|
||||
// Enable filer discovery via master
|
||||
masterMap := make(map[string]pb.ServerAddress)
|
||||
@@ -162,7 +170,22 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
if clientHost == "0.0.0.0" || clientHost == "" {
|
||||
clientHost = util.DetectedHostAddress()
|
||||
}
|
||||
masterClient := wdclient.NewMasterClient(option.GrpcDialOption, option.FilerGroup, cluster.S3Type, pb.ServerAddress(util.JoinHostPort(clientHost, option.GrpcPort)), "", "", *pb.NewServiceDiscoveryFromMap(masterMap))
|
||||
masterClient = wdclient.NewMasterClient(option.GrpcDialOption, option.FilerGroup, cluster.S3Type, pb.ServerAddress(util.JoinHostPort(clientHost, option.GrpcPort)), "", "", *pb.NewServiceDiscoveryFromMap(masterMap))
|
||||
// Build the object-write lock client and subscribe to the master's
|
||||
// lock-ring updates BEFORE starting the master loop, so the initial
|
||||
// LockRingUpdate sent on connect isn't dropped (the master only delivers
|
||||
// it once per connect). The masterClient already filters updates to this
|
||||
// server's filer group.
|
||||
if len(option.Filers) > 0 {
|
||||
objectWriteLockClient = cluster.NewLockClient(option.GrpcDialOption, option.Filers[0])
|
||||
masterClient.SetOnLockRingUpdateFn(func(update *master_pb.LockRingUpdate) {
|
||||
servers := make([]pb.ServerAddress, 0, len(update.Servers))
|
||||
for _, s := range update.Servers {
|
||||
servers = append(servers, pb.ServerAddress(s))
|
||||
}
|
||||
objectWriteLockClient.SetRing(servers, update.Version)
|
||||
})
|
||||
}
|
||||
// Start the master client connection loop - required for GetMaster() to work
|
||||
go masterClient.KeepConnectedToMaster(context.Background())
|
||||
|
||||
@@ -263,7 +286,12 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
}
|
||||
|
||||
if len(option.Filers) > 0 {
|
||||
objectWriteLockClient := cluster.NewLockClient(option.GrpcDialOption, option.Filers[0])
|
||||
// Reuse the lock client built in the masters block (already subscribed to
|
||||
// ring updates); create a plain one when no masters are configured.
|
||||
if objectWriteLockClient == nil {
|
||||
objectWriteLockClient = cluster.NewLockClient(option.GrpcDialOption, option.Filers[0])
|
||||
}
|
||||
s3ApiServer.objectWriteLockClient = objectWriteLockClient
|
||||
s3ApiServer.newObjectWriteLock = func(bucket, object string) objectWriteLock {
|
||||
lockKey := fmt.Sprintf("s3.object.write:%s", s3ApiServer.toFilerPath(bucket, object))
|
||||
owner := fmt.Sprintf("s3api-%d", s3ApiServer.randomClientId)
|
||||
|
||||
@@ -7,15 +7,16 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
@@ -186,6 +187,32 @@ func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntr
|
||||
newEntry.TtlSec = 0
|
||||
}
|
||||
|
||||
// Serialize concurrent mutations to the same path on this filer so the
|
||||
// read (existence/condition) and the write are atomic. Callers route a
|
||||
// key's writes to this owner filer, making this local lock sufficient.
|
||||
fullpath := util.NewFullPath(req.Directory, req.Entry.Name)
|
||||
pathLock := fs.entryLockTable.AcquireLock("CreateEntry", fullpath, util.ExclusiveLock)
|
||||
defer fs.entryLockTable.ReleaseLock(fullpath, pathLock)
|
||||
|
||||
// Evaluate the optional precondition against the current entry while the
|
||||
// path lock is held, so the check and the write are atomic on this filer.
|
||||
if req.Condition != nil && req.Condition.Kind != filer_pb.WriteCondition_NONE {
|
||||
current, findErr := fs.filer.FindEntry(ctx, fullpath)
|
||||
if findErr != nil && findErr != filer_pb.ErrNotFound {
|
||||
return &filer_pb.CreateEntryResponse{}, fmt.Errorf("CreateEntry condition check %s: %w", fullpath, findErr)
|
||||
}
|
||||
if findErr == filer_pb.ErrNotFound {
|
||||
current = nil
|
||||
}
|
||||
if !writeConditionSatisfied(req.Condition, current) {
|
||||
glog.V(3).InfofCtx(ctx, "CreateEntry %s: precondition %v failed", fullpath, req.Condition.Kind)
|
||||
return &filer_pb.CreateEntryResponse{
|
||||
Error: "precondition failed",
|
||||
ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
ctx, eventSink := filer.WithMetadataEventSink(ctx)
|
||||
createErr := fs.filer.CreateEntry(ctx, newEntry, req.OExcl, req.IsFromOtherCluster, req.Signatures, req.SkipCheckParentDirectory, so.MaxFileNameLength)
|
||||
|
||||
@@ -212,6 +239,170 @@ func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntr
|
||||
return
|
||||
}
|
||||
|
||||
// writeConditionSatisfied reports whether the precondition holds against the
|
||||
// current entry (nil if absent). The caller reduces request semantics to one
|
||||
// primitive; each kind is a single comparison evaluated under the path lock.
|
||||
func writeConditionSatisfied(cond *filer_pb.WriteCondition, current *filer.Entry) bool {
|
||||
exists := current != nil
|
||||
switch cond.Kind {
|
||||
case filer_pb.WriteCondition_IF_NOT_EXISTS:
|
||||
return !exists
|
||||
case filer_pb.WriteCondition_IF_EXISTS:
|
||||
return exists
|
||||
case filer_pb.WriteCondition_IF_ETAG_MATCH:
|
||||
return exists && storedEntryETag(current) == normalizeETag(cond.Etag)
|
||||
case filer_pb.WriteCondition_IF_ETAG_NOT_MATCH:
|
||||
return !exists || storedEntryETag(current) != normalizeETag(cond.Etag)
|
||||
case filer_pb.WriteCondition_IF_UNMODIFIED_SINCE:
|
||||
return !exists || current.Attr.Mtime.Unix() <= cond.UnixTime
|
||||
case filer_pb.WriteCondition_IF_MODIFIED_SINCE:
|
||||
return !exists || current.Attr.Mtime.Unix() > cond.UnixTime
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// storedEntryETag mirrors the S3 gateway's ETag precedence (the stored
|
||||
// Seaweed ETag extended attribute, then the chunk/Md5 fallback) so conditional
|
||||
// comparisons match what the gateway computes, without coupling the filer to
|
||||
// S3 request handling.
|
||||
func storedEntryETag(entry *filer.Entry) string {
|
||||
if v, ok := entry.Extended[s3_constants.ExtETagKey]; ok && len(v) > 0 {
|
||||
return normalizeETag(string(v))
|
||||
}
|
||||
return normalizeETag(filer.ETagEntry(entry))
|
||||
}
|
||||
|
||||
func normalizeETag(etag string) string {
|
||||
return strings.Trim(etag, `"`)
|
||||
}
|
||||
|
||||
// versionedConditionSatisfied evaluates a precondition against the current
|
||||
// latest version, derived from the .versions directory entry's cached metadata
|
||||
// (whether a latest exists and isn't a delete marker, and its ETag). It mirrors
|
||||
// writeConditionSatisfied but reads the cached pointer fields instead of a plain
|
||||
// object entry.
|
||||
func versionedConditionSatisfied(req *filer_pb.FinalizeVersionedWriteRequest, versionsEntry *filer.Entry) bool {
|
||||
exists := false
|
||||
etag := ""
|
||||
if versionsEntry != nil && versionsEntry.Extended != nil {
|
||||
latestFile := string(versionsEntry.Extended[req.PriorLatestKey])
|
||||
isDeleteMarker := req.LatestDeleteMarkerKey != "" && string(versionsEntry.Extended[req.LatestDeleteMarkerKey]) == "true"
|
||||
exists = latestFile != "" && !isDeleteMarker
|
||||
if req.LatestEtagKey != "" {
|
||||
etag = normalizeETag(string(versionsEntry.Extended[req.LatestEtagKey]))
|
||||
}
|
||||
}
|
||||
want := normalizeETag(req.Condition.Etag)
|
||||
switch req.Condition.Kind {
|
||||
case filer_pb.WriteCondition_IF_NOT_EXISTS:
|
||||
return !exists
|
||||
case filer_pb.WriteCondition_IF_EXISTS:
|
||||
return exists
|
||||
case filer_pb.WriteCondition_IF_ETAG_MATCH:
|
||||
return exists && etag == want
|
||||
case filer_pb.WriteCondition_IF_ETAG_NOT_MATCH:
|
||||
return !exists || etag != want
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// FinalizeVersionedWrite performs an S3 versioned-write finalize atomically on
|
||||
// the owner of the object's .versions directory: it creates the new version
|
||||
// file, stamps the previous latest as noncurrent (before the pointer flip so the
|
||||
// lifecycle router observes it), then merges the latest-pointer / cached
|
||||
// metadata into the .versions directory entry. A single exclusive lock on the
|
||||
// .versions directory serializes the whole sequence against concurrent versioned
|
||||
// writes to the same object, replacing the distributed lock. Key names come from
|
||||
// the caller so the filer carries no S3 versioning semantics.
|
||||
func (fs *FilerServer) FinalizeVersionedWrite(ctx context.Context, req *filer_pb.FinalizeVersionedWriteRequest) (*filer_pb.FinalizeVersionedWriteResponse, error) {
|
||||
resp := &filer_pb.FinalizeVersionedWriteResponse{}
|
||||
versionsDir := util.FullPath(req.VersionsDir)
|
||||
|
||||
// Serialize on the object key — the same lock all of this object's writes
|
||||
// (normal, suspended, versioned) share — not the .versions directory, so a
|
||||
// versioned write and a non-versioned write to the same object can't run on
|
||||
// different owners during a versioning-state change. Fall back to the
|
||||
// .versions directory for older callers that don't set lock_key.
|
||||
lockKey := util.FullPath(req.LockKey)
|
||||
if lockKey == "" {
|
||||
lockKey = versionsDir
|
||||
}
|
||||
lock := fs.entryLockTable.AcquireLock("FinalizeVersionedWrite", lockKey, util.ExclusiveLock)
|
||||
defer fs.entryLockTable.ReleaseLock(lockKey, lock)
|
||||
|
||||
// The caller already created the new version file under this .versions
|
||||
// directory, so it exists; read the directory entry that holds the pointer.
|
||||
versionsEntry, err := fs.filer.FindEntry(ctx, versionsDir)
|
||||
if err != nil {
|
||||
resp.Error = err.Error()
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// 1. Evaluate the optional precondition against the current latest version
|
||||
// (the .versions directory's cached pointer metadata) before the flip, so the
|
||||
// check and the flip are atomic under this lock.
|
||||
if req.Condition != nil && req.Condition.Kind != filer_pb.WriteCondition_NONE {
|
||||
if !versionedConditionSatisfied(req, versionsEntry) {
|
||||
glog.V(3).InfofCtx(ctx, "FinalizeVersionedWrite %s: precondition %v failed", versionsDir, req.Condition.Kind)
|
||||
resp.Error = "precondition failed"
|
||||
resp.ErrorCode = filer_pb.FilerError_PRECONDITION_FAILED
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Optional: delete an entry under the same lock first (suspended delete
|
||||
// removes the "null" version at the main object path before adding the
|
||||
// marker). Not-found is fine (idempotent).
|
||||
if req.DeletePath != "" {
|
||||
if derr := fs.filer.DeleteEntryMetaAndData(ctx, util.FullPath(req.DeletePath), false, false, true, req.IsFromOtherCluster, req.Signatures, 0); derr != nil && derr != filer_pb.ErrNotFound {
|
||||
resp.Error = derr.Error()
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Stamp the previously-latest version as noncurrent BEFORE the pointer
|
||||
// flip (so the lifecycle router observes it). Best-effort.
|
||||
newFileName := string(req.SetExtended[req.PriorLatestKey])
|
||||
if req.NoncurrentSinceNs > 0 && req.PriorLatestKey != "" && req.NoncurrentSinceKey != "" {
|
||||
prior := string(versionsEntry.Extended[req.PriorLatestKey])
|
||||
if prior != "" && prior != newFileName {
|
||||
demotedPath := util.NewFullPath(req.VersionsDir, prior)
|
||||
if demoted, derr := fs.filer.FindEntry(ctx, demotedPath); derr == nil {
|
||||
if demoted.Extended == nil {
|
||||
demoted.Extended = make(map[string][]byte)
|
||||
}
|
||||
demoted.Extended[req.NoncurrentSinceKey] = []byte(strconv.FormatInt(req.NoncurrentSinceNs, 10))
|
||||
if uerr := fs.filer.UpdateEntry(ctx, demoted, demoted); uerr != nil {
|
||||
glog.Warningf("FinalizeVersionedWrite: demote stamp %s: %v", demotedPath, uerr)
|
||||
}
|
||||
} else {
|
||||
glog.V(2).InfofCtx(ctx, "FinalizeVersionedWrite: demote target %s not found: %v", demotedPath, derr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Flip the latest pointer: merge the requested Extended keys into the
|
||||
// .versions directory entry and write it back (emits the meta-log event the
|
||||
// lifecycle router consumes).
|
||||
if versionsEntry.Extended == nil {
|
||||
versionsEntry.Extended = make(map[string][]byte)
|
||||
}
|
||||
for _, k := range req.DeleteExtended {
|
||||
delete(versionsEntry.Extended, k)
|
||||
}
|
||||
for k, v := range req.SetExtended {
|
||||
versionsEntry.Extended[k] = v
|
||||
}
|
||||
if err := fs.filer.CreateEntry(ctx, versionsEntry, false, req.IsFromOtherCluster, req.Signatures, true, fs.filer.MaxFilenameLength); err != nil {
|
||||
resp.Error = err.Error()
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (fs *FilerServer) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
|
||||
|
||||
glog.V(4).InfofCtx(ctx, "UpdateEntry %v", req)
|
||||
@@ -328,9 +519,11 @@ func (fs *FilerServer) AppendToEntry(ctx context.Context, req *filer_pb.AppendTo
|
||||
glog.V(4).InfofCtx(ctx, "AppendToEntry %v", req)
|
||||
fullpath := util.NewFullPath(req.Directory, req.EntryName)
|
||||
|
||||
lockClient := cluster.NewLockClient(fs.grpcDialOption, fs.option.Host)
|
||||
lock := lockClient.NewShortLivedLock(string(fullpath), string(fs.option.Host))
|
||||
defer lock.StopShortLivedLock()
|
||||
// Serialize the read-modify-write against concurrent mutations to the same
|
||||
// path on this filer. The append must route to this entry's owner filer for
|
||||
// this local lock to be authoritative.
|
||||
pathLock := fs.entryLockTable.AcquireLock("AppendToEntry", fullpath, util.ExclusiveLock)
|
||||
defer fs.entryLockTable.ReleaseLock(fullpath, pathLock)
|
||||
|
||||
var offset int64 = 0
|
||||
entry, err := fs.filer.FindEntry(ctx, fullpath)
|
||||
@@ -375,9 +568,35 @@ func (fs *FilerServer) DeleteEntry(ctx context.Context, req *filer_pb.DeleteEntr
|
||||
|
||||
glog.V(4).InfofCtx(ctx, "DeleteEntry %v", req)
|
||||
|
||||
ctx, eventSink := filer.WithMetadataEventSink(ctx)
|
||||
err = fs.filer.DeleteEntryMetaAndData(ctx, util.JoinPath(req.Directory, req.Name), req.IsRecursive, req.IgnoreRecursiveError, req.IsDeleteData, req.IsFromOtherCluster, req.Signatures, req.IfNotModifiedAfter)
|
||||
fullpath := util.JoinPath(req.Directory, req.Name)
|
||||
resp = &filer_pb.DeleteEntryResponse{}
|
||||
|
||||
// A single-entry delete serializes against concurrent mutations to the same
|
||||
// path so a conditional delete's check and the removal are atomic. Recursive
|
||||
// deletes span many paths and keep the prior unlocked behavior.
|
||||
if !req.IsRecursive {
|
||||
pathLock := fs.entryLockTable.AcquireLock("DeleteEntry", fullpath, util.ExclusiveLock)
|
||||
defer fs.entryLockTable.ReleaseLock(fullpath, pathLock)
|
||||
|
||||
if req.Condition != nil && req.Condition.Kind != filer_pb.WriteCondition_NONE {
|
||||
current, findErr := fs.filer.FindEntry(ctx, fullpath)
|
||||
if findErr != nil && findErr != filer_pb.ErrNotFound {
|
||||
return &filer_pb.DeleteEntryResponse{}, fmt.Errorf("DeleteEntry condition check %s: %w", fullpath, findErr)
|
||||
}
|
||||
if findErr == filer_pb.ErrNotFound {
|
||||
current = nil
|
||||
}
|
||||
if !writeConditionSatisfied(req.Condition, current) {
|
||||
glog.V(3).InfofCtx(ctx, "DeleteEntry %s: precondition %v failed", fullpath, req.Condition.Kind)
|
||||
resp.Error = "precondition failed"
|
||||
resp.ErrorCode = filer_pb.FilerError_PRECONDITION_FAILED
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ctx, eventSink := filer.WithMetadataEventSink(ctx)
|
||||
err = fs.filer.DeleteEntryMetaAndData(ctx, fullpath, req.IsRecursive, req.IgnoreRecursiveError, req.IsDeleteData, req.IsFromOtherCluster, req.Signatures, req.IfNotModifiedAfter)
|
||||
if err != nil && err != filer_pb.ErrNotFound {
|
||||
resp.Error = err.Error()
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func entryWithETag(etag string, mtime time.Time) *filer.Entry {
|
||||
return &filer.Entry{
|
||||
FullPath: "/test/obj",
|
||||
Attr: filer.Attr{Mtime: mtime},
|
||||
Extended: map[string][]byte{s3_constants.ExtETagKey: []byte(etag)},
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteConditionSatisfied(t *testing.T) {
|
||||
base := time.Unix(1700000000, 0)
|
||||
present := entryWithETag("abc", base)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
cond *filer_pb.WriteCondition
|
||||
cur *filer.Entry
|
||||
want bool
|
||||
}{
|
||||
{"none-absent", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_NONE}, nil, true},
|
||||
{"ifnotexists-absent", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS}, nil, true},
|
||||
{"ifnotexists-present", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS}, present, false},
|
||||
{"ifexists-absent", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_EXISTS}, nil, false},
|
||||
{"ifexists-present", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_EXISTS}, present, true},
|
||||
{"etagmatch-hit", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etag: `"abc"`}, present, true},
|
||||
{"etagmatch-miss", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etag: `"zzz"`}, present, false},
|
||||
{"etagmatch-absent", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etag: `"abc"`}, nil, false},
|
||||
{"etagnotmatch-hit", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_NOT_MATCH, Etag: `"abc"`}, present, false},
|
||||
{"etagnotmatch-miss", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_NOT_MATCH, Etag: `"zzz"`}, present, true},
|
||||
{"etagnotmatch-absent", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_NOT_MATCH, Etag: `"abc"`}, nil, true},
|
||||
{"unmodsince-ok", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_UNMODIFIED_SINCE, UnixTime: base.Unix()}, present, true},
|
||||
{"unmodsince-fail", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_UNMODIFIED_SINCE, UnixTime: base.Unix() - 1}, present, false},
|
||||
{"modsince-ok", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_MODIFIED_SINCE, UnixTime: base.Unix() - 1}, present, true},
|
||||
{"modsince-fail", &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_MODIFIED_SINCE, UnixTime: base.Unix()}, present, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := writeConditionSatisfied(tc.cond, tc.cur); got != tc.want {
|
||||
t.Errorf("%s: got %v want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// storedEntryETag prefers the stored Seaweed ETag attribute and falls back to
|
||||
// the Md5-derived ETag, matching the S3 gateway.
|
||||
func TestStoredEntryETag(t *testing.T) {
|
||||
withExt := entryWithETag("explicit", time.Unix(0, 0))
|
||||
if got := storedEntryETag(withExt); got != "explicit" {
|
||||
t.Errorf("extended etag: got %q", got)
|
||||
}
|
||||
md5Only := &filer.Entry{Attr: filer.Attr{Md5: []byte{0xab, 0xcd}}}
|
||||
if got := storedEntryETag(md5Only); got != "abcd" {
|
||||
t.Errorf("md5 fallback: got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The CreateEntry handler enforces the precondition atomically: a matching
|
||||
// If-Match overwrites, a non-matching one returns PRECONDITION_FAILED.
|
||||
func TestCreateEntryConditionEnforced(t *testing.T) {
|
||||
store := newRenameTestStore()
|
||||
store.entries["/test/obj"] = &filer.Entry{
|
||||
FullPath: "/test/obj",
|
||||
Attr: filer.Attr{Inode: 1, Mtime: time.Unix(1700000000, 0)},
|
||||
Extended: map[string][]byte{s3_constants.ExtETagKey: []byte("abc")},
|
||||
}
|
||||
f := newRenameTestFiler(store)
|
||||
f.DirBucketsPath = "/buckets"
|
||||
fs := &FilerServer{filer: f, option: &FilerOption{}, entryLockTable: util.NewLockTable[util.FullPath]()}
|
||||
|
||||
req := func(etag string) *filer_pb.CreateEntryRequest {
|
||||
return &filer_pb.CreateEntryRequest{
|
||||
Directory: "/test",
|
||||
SkipCheckParentDirectory: true,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: "obj",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1700000001, FileMode: 0644, Inode: 2},
|
||||
},
|
||||
Condition: &filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etag: etag},
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := fs.CreateEntry(context.Background(), req(`"zzz"`))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if resp.ErrorCode != filer_pb.FilerError_PRECONDITION_FAILED {
|
||||
t.Fatalf("mismatched etag: want PRECONDITION_FAILED, got %v (%q)", resp.ErrorCode, resp.Error)
|
||||
}
|
||||
|
||||
resp, err = fs.CreateEntry(context.Background(), req(`"abc"`))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
t.Fatalf("matching etag should overwrite, got error %q", resp.Error)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// Concurrent OExcl creates for the same path must yield exactly one winner. The
|
||||
// filer's CreateEntry is a FindEntry-then-Insert; without the per-path lock both
|
||||
// racers observe "not found" and both insert. The exclusive entry lock makes the
|
||||
// check-then-act atomic so the losers see ErrEntryAlreadyExists.
|
||||
func TestCreateEntryOExclSerialized(t *testing.T) {
|
||||
store := newRenameTestStore()
|
||||
store.findDelay = 5 * time.Millisecond
|
||||
f := newRenameTestFiler(store)
|
||||
f.DirBucketsPath = "/buckets"
|
||||
|
||||
fs := &FilerServer{
|
||||
filer: f,
|
||||
option: &FilerOption{},
|
||||
entryLockTable: util.NewLockTable[util.FullPath](),
|
||||
}
|
||||
|
||||
const racers = 8
|
||||
var success int32
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for i := 0; i < racers; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
resp, err := fs.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{
|
||||
Directory: "/test",
|
||||
OExcl: true,
|
||||
SkipCheckParentDirectory: true,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: "obj",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1700000000, FileMode: 0644, Inode: 1},
|
||||
},
|
||||
})
|
||||
if err == nil && resp.Error == "" {
|
||||
atomic.AddInt32(&success, 1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
if success != 1 {
|
||||
t.Fatalf("expected exactly 1 OExcl winner, got %d", success)
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ type renameTestStore struct {
|
||||
findCalls map[string]int
|
||||
commitErr error
|
||||
deleteErr error
|
||||
findDelay time.Duration // optional: widen check-then-act windows in tests
|
||||
}
|
||||
|
||||
func newRenameTestStore() *renameTestStore {
|
||||
@@ -69,6 +70,9 @@ func (s *renameTestStore) UpdateEntry(_ context.Context, entry *filer.Entry) err
|
||||
}
|
||||
|
||||
func (s *renameTestStore) FindEntry(_ context.Context, p util.FullPath) (*filer.Entry, error) {
|
||||
if s.findDelay > 0 {
|
||||
time.Sleep(s.findDelay)
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.findCalls[string(p)]++
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func newFinalizeTestServer(store *renameTestStore) *FilerServer {
|
||||
f := newRenameTestFiler(store)
|
||||
f.DirBucketsPath = "/buckets"
|
||||
return &FilerServer{filer: f, option: &FilerOption{}, entryLockTable: util.NewLockTable[util.FullPath]()}
|
||||
}
|
||||
|
||||
func seedVersions(store *renameTestStore, latestFile, latestEtag string) {
|
||||
store.entries["/buckets/b/obj/.versions"] = &filer.Entry{
|
||||
FullPath: "/buckets/b/obj/.versions",
|
||||
Attr: filer.Attr{Inode: 10, Mode: 0755 | (1 << 31)},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte(latestFile),
|
||||
s3_constants.ExtLatestVersionETagKey: []byte(latestEtag),
|
||||
},
|
||||
}
|
||||
store.entries["/buckets/b/obj/.versions/"+latestFile] = &filer.Entry{
|
||||
FullPath: util.FullPath("/buckets/b/obj/.versions/" + latestFile),
|
||||
Attr: filer.Attr{Inode: 11},
|
||||
Extended: map[string][]byte{},
|
||||
}
|
||||
}
|
||||
|
||||
func finalizeReq(cond *filer_pb.WriteCondition) *filer_pb.FinalizeVersionedWriteRequest {
|
||||
return &filer_pb.FinalizeVersionedWriteRequest{
|
||||
VersionsDir: "/buckets/b/obj/.versions",
|
||||
SetExtended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte("v2.ver"),
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("vid2"),
|
||||
},
|
||||
DeleteExtended: []string{s3_constants.ExtLatestVersionETagKey},
|
||||
PriorLatestKey: s3_constants.ExtLatestVersionFileNameKey,
|
||||
NoncurrentSinceKey: s3_constants.ExtNoncurrentSinceNsKey,
|
||||
NoncurrentSinceNs: 77777,
|
||||
Condition: cond,
|
||||
LatestEtagKey: s3_constants.ExtLatestVersionETagKey,
|
||||
LatestDeleteMarkerKey: s3_constants.ExtLatestVersionIsDeleteMarker,
|
||||
}
|
||||
}
|
||||
|
||||
// The finalize flips the latest pointer and stamps the previously-latest version
|
||||
// noncurrent, atomically under the .versions lock.
|
||||
func TestFinalizeVersionedWriteFlipAndDemote(t *testing.T) {
|
||||
store := newRenameTestStore()
|
||||
seedVersions(store, "v1.ver", "etag1")
|
||||
fs := newFinalizeTestServer(store)
|
||||
|
||||
resp, err := fs.FinalizeVersionedWrite(context.Background(), finalizeReq(&filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_NONE}))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
t.Fatalf("unexpected resp error: %s", resp.Error)
|
||||
}
|
||||
|
||||
if got := string(store.entries["/buckets/b/obj/.versions"].Extended[s3_constants.ExtLatestVersionFileNameKey]); got != "v2.ver" {
|
||||
t.Errorf("latest pointer not flipped: %q", got)
|
||||
}
|
||||
if got := string(store.entries["/buckets/b/obj/.versions/v1.ver"].Extended[s3_constants.ExtNoncurrentSinceNsKey]); got != "77777" {
|
||||
t.Errorf("previous latest not demoted: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A failing precondition is reported and nothing is flipped or demoted.
|
||||
func TestFinalizeVersionedWritePreconditionFailed(t *testing.T) {
|
||||
store := newRenameTestStore()
|
||||
seedVersions(store, "v1.ver", "etag1")
|
||||
fs := newFinalizeTestServer(store)
|
||||
|
||||
// IF_NOT_EXISTS against an existing latest must fail.
|
||||
resp, err := fs.FinalizeVersionedWrite(context.Background(), finalizeReq(&filer_pb.WriteCondition{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS}))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected err: %v", err)
|
||||
}
|
||||
if resp.ErrorCode != filer_pb.FilerError_PRECONDITION_FAILED {
|
||||
t.Fatalf("want PRECONDITION_FAILED, got %v (%q)", resp.ErrorCode, resp.Error)
|
||||
}
|
||||
if got := string(store.entries["/buckets/b/obj/.versions"].Extended[s3_constants.ExtLatestVersionFileNameKey]); got != "v1.ver" {
|
||||
t.Errorf("pointer should be unchanged on precondition failure, got %q", got)
|
||||
}
|
||||
if _, stamped := store.entries["/buckets/b/obj/.versions/v1.ver"].Extended[s3_constants.ExtNoncurrentSinceNsKey]; stamped {
|
||||
t.Errorf("previous latest should not be demoted on precondition failure")
|
||||
}
|
||||
}
|
||||
@@ -124,6 +124,13 @@ type FilerServer struct {
|
||||
// mountPeerRegistry backs the MountRegister / MountList RPCs for peer
|
||||
// chunk sharing (tier 1). Always populated.
|
||||
mountPeerRegistry *filer.MountPeerRegistry
|
||||
|
||||
// entryLockTable serializes mutations to the same entry path on this filer.
|
||||
// It is the local serialization point for read-modify-write operations
|
||||
// (conditional create, append) once writers for a key are routed to this
|
||||
// node, replacing the distributed lock for that purpose. Idle keys are
|
||||
// evicted automatically, so the table stays bounded.
|
||||
entryLockTable *util.LockTable[util.FullPath]
|
||||
}
|
||||
|
||||
func NewFilerServer(defaultMux, readonlyMux *http.ServeMux, option *FilerOption) (fs *FilerServer, err error) {
|
||||
@@ -162,6 +169,7 @@ func NewFilerServer(defaultMux, readonlyMux *http.ServeMux, option *FilerOption)
|
||||
inFlightDataLimitCond: sync.NewCond(new(sync.Mutex)),
|
||||
recentCopyRequests: make(map[string]recentCopyRequest),
|
||||
CredentialManager: option.CredentialManager,
|
||||
entryLockTable: util.NewLockTable[util.FullPath](),
|
||||
}
|
||||
fs.mountPeerRegistry = filer.NewMountPeerRegistry()
|
||||
go fs.runMountPeerRegistrySweeper()
|
||||
|
||||
@@ -393,7 +393,13 @@ func (ms *MasterServer) KeepConnected(stream master_pb.Seaweed_KeepConnectedServ
|
||||
}
|
||||
|
||||
func (ms *MasterServer) initialLockRingUpdate(clientType string, filerGroup string) *master_pb.KeepConnectedResponse {
|
||||
if clientType != cluster.FilerType || ms.LockRingManager == nil {
|
||||
if ms.LockRingManager == nil {
|
||||
return nil
|
||||
}
|
||||
// Filers are ring members; S3 gateways are lock clients that need the same
|
||||
// view to dial a key's primary directly. Both get the initial snapshot;
|
||||
// later membership changes already broadcast to every connected client.
|
||||
if clientType != cluster.FilerType && clientType != cluster.S3Type {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -781,6 +781,10 @@ func (ecb *ecBalancer) balance(collections []string) error {
|
||||
ImbalanceThreshold: 0, // the shell balances to an even distribution
|
||||
ReplicaPlacement: ecb.replicaPlacement,
|
||||
Ratio: shellECRatio,
|
||||
// Balance the global phase by fractional fullness so heterogeneous-capacity
|
||||
// nodes fill proportionally (matching the worker). This is identical to raw
|
||||
// shard count when capacities are uniform.
|
||||
GlobalUtilizationBased: true,
|
||||
})
|
||||
return ecb.executeMoves(moves)
|
||||
}
|
||||
|
||||
@@ -340,7 +340,11 @@ func TestCommandEcBalanceIssue8793Topology(t *testing.T) {
|
||||
// Simulate 22 EC volumes across 14 nodes (each volume has 14 shards, 1 per node).
|
||||
// Give nodes 0-3 an extra volume each (vol 23-26, all 14 shards) to create imbalance.
|
||||
// Before balancing: nodes 0-3 have 22+14=36 shards each, nodes 4-13 have 22 shards each.
|
||||
// Total = 4*36 + 10*22 = 144+220 = 364. Average = ceil(364/14) = 26.
|
||||
// Total = 4*36 + 10*22 = 144+220 = 364. Capacities are heterogeneous (max 80 vs
|
||||
// 33), so the utilization-based global phase balances by fullness, not count:
|
||||
// 364 shards over 9*80+5*33=885 slots is ~41% full, so large nodes settle near
|
||||
// 33 shards and small nodes near 14 (all ~41% full) rather than ~26 each, which
|
||||
// would drive the small nodes to ~79%.
|
||||
|
||||
type nodeSpec struct {
|
||||
id string
|
||||
@@ -396,8 +400,17 @@ func TestCommandEcBalanceIssue8793Topology(t *testing.T) {
|
||||
|
||||
ecb.balance([]string{"cldata"})
|
||||
|
||||
// Verify: no node should exceed the average
|
||||
// Verify even FULLNESS (shards/capacity), not even count: with heterogeneous
|
||||
// capacities the utilization-based global phase fills nodes proportionally, so
|
||||
// large nodes hold more shards than small ones while every node ends near the
|
||||
// overall fullness. (An even-count result would over-fill the small nodes.)
|
||||
capacityByID := make(map[string]int, len(nodes))
|
||||
for _, ns := range nodes {
|
||||
capacityByID[ns.id] = ns.maxSlot
|
||||
}
|
||||
|
||||
totalShards := 0
|
||||
totalCapacity := 0
|
||||
shardCounts := make(map[string]int)
|
||||
for _, node := range ecb.ecNodes {
|
||||
count := 0
|
||||
@@ -408,14 +421,22 @@ func TestCommandEcBalanceIssue8793Topology(t *testing.T) {
|
||||
}
|
||||
shardCounts[node.info.Id] = count
|
||||
totalShards += count
|
||||
totalCapacity += capacityByID[node.info.Id]
|
||||
}
|
||||
avg := ceilDivide(totalShards, len(ecNodes))
|
||||
overallFullness := float64(totalShards) / float64(totalCapacity)
|
||||
|
||||
// Tolerance well below the gap a count-even result would show (small nodes
|
||||
// would sit ~38 points above overall), but above integer-rounding skew.
|
||||
const tolerance = 0.05
|
||||
for _, node := range ecb.ecNodes {
|
||||
count := shardCounts[node.info.Id]
|
||||
t.Logf("AFTER node %s: %d shards (avg %d)", node.info.Id, count, avg)
|
||||
if count > avg {
|
||||
t.Errorf("node %s has %d shards, expected at most %d (avg)", node.info.Id, count, avg)
|
||||
capacity := capacityByID[node.info.Id]
|
||||
fullness := float64(count) / float64(capacity)
|
||||
t.Logf("AFTER node %s: %d/%d shards (%.0f%% full, overall %.0f%%)",
|
||||
node.info.Id, count, capacity, fullness*100, overallFullness*100)
|
||||
if diff := fullness - overallFullness; diff > tolerance || diff < -tolerance {
|
||||
t.Errorf("node %s fullness %.1f%% deviates from overall %.1f%% by more than %.0f points",
|
||||
node.info.Id, fullness*100, overallFullness*100, tolerance*100)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package erasure_coding
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"iter"
|
||||
"math/bits"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -40,6 +41,20 @@ func (sb ShardBits) Count() int {
|
||||
return bits.OnesCount32(uint32(sb))
|
||||
}
|
||||
|
||||
// All iterates the shard ids present in the bitmap, in ascending order. It walks
|
||||
// only the set bits (trailing-zero scan), so cost scales with the number of
|
||||
// shards present rather than the full id range. Prefer this over scanning
|
||||
// 0..MaxShardCount and calling Has on each id.
|
||||
func (sb ShardBits) All() iter.Seq[ShardId] {
|
||||
return func(yield func(ShardId) bool) {
|
||||
for b := uint32(sb); b != 0; b &= b - 1 {
|
||||
if !yield(ShardId(bits.TrailingZeros32(b))) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ShardsInfo encapsulates information for EC shards with memory-efficient storage
|
||||
type ShardsInfo struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
@@ -43,6 +43,7 @@ type Node struct {
|
||||
type disk struct {
|
||||
diskID uint32
|
||||
diskType string
|
||||
tags []string // placement tags, for preferred-tag tiering
|
||||
freeSlots int
|
||||
shardCount int // total EC shards on this disk across all volumes
|
||||
}
|
||||
@@ -88,8 +89,8 @@ type Options struct {
|
||||
GlobalMaxMovesPerRack int
|
||||
// GlobalUtilizationBased selects the global phase's balance metric: when true,
|
||||
// nodes are balanced by fractional fullness (shards/capacity), which suits
|
||||
// heterogeneous-capacity racks; when false, by raw shard count. The worker
|
||||
// uses utilization; the shell uses raw count.
|
||||
// heterogeneous-capacity racks; when false, by raw shard count. Both the worker
|
||||
// and the shell enable it; the two metrics agree when capacities are uniform.
|
||||
GlobalUtilizationBased bool
|
||||
}
|
||||
|
||||
@@ -132,6 +133,14 @@ func (n *Node) AddDisk(diskID uint32, diskType string, freeSlots, shardCount int
|
||||
n.disks[diskID] = &disk{diskID: diskID, diskType: diskType, freeSlots: freeSlots, shardCount: shardCount}
|
||||
}
|
||||
|
||||
// AddDiskTags records placement tags (e.g. "ssd","fast") for a disk, used by
|
||||
// preferred-tag tiering in Place. Call after AddDisk; a no-op if the disk is unknown.
|
||||
func (n *Node) AddDiskTags(diskID uint32, tags []string) {
|
||||
if d, ok := n.disks[diskID]; ok {
|
||||
d.tags = append([]string(nil), tags...)
|
||||
}
|
||||
}
|
||||
|
||||
// AddShards records that the volume's shards in bits live on diskID. Call it
|
||||
// only for the volumes that should be balanced; the disk's overall occupancy is
|
||||
// reported separately via AddDisk.
|
||||
@@ -251,10 +260,8 @@ func detectDuplicateShards(vk volKey, nodes map[string]*Node) []*move {
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for shardID := 0; shardID < erasure_coding.MaxShardCount; shardID++ {
|
||||
if info.shardBits.Has(erasure_coding.ShardId(shardID)) {
|
||||
shardLocations[shardID] = append(shardLocations[shardID], node)
|
||||
}
|
||||
for sid := range info.shardBits.All() {
|
||||
shardLocations[int(sid)] = append(shardLocations[int(sid)], node)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -354,8 +361,11 @@ func balanceShardTypeAcrossRacks(vk volKey, nodes map[string]*Node, racks map[st
|
||||
destRack, ok := pickTarget(rackKeys, shardsPerRack, maxPerRack, antiAffinity,
|
||||
func(r string) bool { return racks[r].freeSlots > 0 },
|
||||
func(r string) bool {
|
||||
if rp != nil && rp.DiffRackCount > 0 {
|
||||
return rackShardCount[r] < rp.DiffRackCount
|
||||
if rp == nil {
|
||||
return true
|
||||
}
|
||||
if rp.DiffRackCount > 0 && rackShardCount[r] >= rp.DiffRackCount {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
@@ -403,7 +413,7 @@ func pickNodeInRack(r *rack, vk volKey, rp *super_block.ReplicaPlacement) *Node
|
||||
continue
|
||||
}
|
||||
count := volumeShardCount(node, vk)
|
||||
if rp != nil && rp.SameRackCount > 0 && count >= rp.SameRackCount+1 {
|
||||
if rp != nil && rp.SameRackCount > 0 && count >= rp.SameRackCount {
|
||||
continue
|
||||
}
|
||||
if best == nil || count < bestCount {
|
||||
@@ -479,7 +489,7 @@ func balanceShardTypeAcrossNodes(vk volKey, r *rack, diskType string, dataShards
|
||||
func(n string) bool { return n != pm.src.id && r.nodes[n].freeSlots > 0 },
|
||||
func(n string) bool {
|
||||
if rp != nil && rp.SameRackCount > 0 {
|
||||
return nodeShardCount[n] < rp.SameRackCount+1
|
||||
return nodeShardCount[n] < rp.SameRackCount
|
||||
}
|
||||
return true
|
||||
})
|
||||
@@ -610,13 +620,10 @@ func detectGlobalImbalance(nodes map[string]*Node, racks map[string]*rack, diskT
|
||||
if pass == 1 && !volumeOnMin {
|
||||
continue // pass 1: only volumes already on the destination
|
||||
}
|
||||
// Iterate the full shard-id space so custom ratios with more than
|
||||
// the standard total (ids 14..MaxShardCount-1) are candidates too.
|
||||
for shardID := 0; shardID < erasure_coding.MaxShardCount; shardID++ {
|
||||
sid := erasure_coding.ShardId(shardID)
|
||||
if !info.shardBits.Has(sid) {
|
||||
continue
|
||||
}
|
||||
// Walk the volume's actual shard bitmap so custom ratios with more
|
||||
// than the standard total (ids 14..MaxShardCount-1) are candidates too.
|
||||
for sid := range info.shardBits.All() {
|
||||
shardID := int(sid)
|
||||
if minInfo != nil && minInfo.shardBits.Has(sid) {
|
||||
continue
|
||||
}
|
||||
@@ -669,10 +676,8 @@ func shardsByGroup(vk volKey, nodes map[string]*Node, dataShards int, key func(*
|
||||
continue
|
||||
}
|
||||
k := key(node)
|
||||
for s := 0; s < erasure_coding.MaxShardCount; s++ {
|
||||
if !info.shardBits.Has(erasure_coding.ShardId(s)) {
|
||||
continue
|
||||
}
|
||||
for sid := range info.shardBits.All() {
|
||||
s := int(sid)
|
||||
if s < dataShards {
|
||||
dataPer[k] = append(dataPer[k], s)
|
||||
} else {
|
||||
@@ -747,11 +752,8 @@ func pickBestDiskOnNode(node *Node, vk volKey, diskType string, shardID, dataSha
|
||||
bits := info.diskShardBits[diskID]
|
||||
existingShards = bits.Count()
|
||||
if dataShardCount > 0 {
|
||||
for s := 0; s < erasure_coding.MaxShardCount; s++ {
|
||||
if !bits.Has(erasure_coding.ShardId(s)) {
|
||||
continue
|
||||
}
|
||||
if s < dataShardCount {
|
||||
for sid := range bits.All() {
|
||||
if int(sid) < dataShardCount {
|
||||
hasData = true
|
||||
} else {
|
||||
hasParity = true
|
||||
@@ -807,9 +809,11 @@ func reserveShard(node *Node, vk volKey, shardID int, diskID uint32) {
|
||||
info.diskShardBits[diskID] = info.diskShardBits[diskID].Set(sid)
|
||||
if d, ok := node.disks[diskID]; ok {
|
||||
d.shardCount++
|
||||
if d.freeSlots > 0 {
|
||||
d.freeSlots--
|
||||
}
|
||||
// Decrement unconditionally so reserve/release stay symmetric (releaseShard
|
||||
// credits a slot unconditionally). Callers only reserve onto disks
|
||||
// pickBestDisk* already vetted as having free slots, so this won't go
|
||||
// negative; if it ever did, freeSlots<=0 correctly reads as full.
|
||||
d.freeSlots--
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,558 @@
|
||||
package ecbalancer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
storagetypes "github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
// Constraints configures a Place call. Ratio resolves a collection's
|
||||
// (dataShards, parityShards); nil uses the standard scheme. ReplicaPlacement,
|
||||
// when non-nil, caps shards per rack (DiffRackCount = max shards/rack) and per
|
||||
// node within a rack (SameRackCount = max shards/node); both digits are direct
|
||||
// hard caps. The data-center digit (DiffDataCenterCount) is not honored:
|
||||
// the 1-byte volume ReplicaPlacement can only encode 0-2 there, too small to be a
|
||||
// meaningful per-DC EC shard cap, so EC relies on the rack/node even spread instead.
|
||||
//
|
||||
// DiskTypePolicy controls how DiskType constrains placement (Any / Prefer /
|
||||
// Require). PreferredTags drives whole-plan tag tiering: Place tries disks
|
||||
// carrying the earliest tags first and widens to all disks only if a tier cannot
|
||||
// place every shard.
|
||||
type Constraints struct {
|
||||
DiskType string
|
||||
DiskTypePolicy DiskTypePolicy
|
||||
PreferredTags []string
|
||||
ReplicaPlacement *super_block.ReplicaPlacement
|
||||
Ratio func(collection string) (dataShards, parityShards int)
|
||||
}
|
||||
|
||||
// DiskTypePolicy controls how Constraints.DiskType constrains placement.
|
||||
type DiskTypePolicy int
|
||||
|
||||
const (
|
||||
DiskTypeAny DiskTypePolicy = iota // any disk type
|
||||
DiskTypePrefer // prefer DiskType, spill to other types if needed
|
||||
DiskTypeRequire // only DiskType (HardDriveType when "")
|
||||
)
|
||||
|
||||
// diskTypeEqual compares disk types after normalization, so "" and "hdd" (both
|
||||
// HardDriveType) are equal.
|
||||
func diskTypeEqual(a, b string) bool {
|
||||
return storagetypes.ToDiskType(a).String() == storagetypes.ToDiskType(b).String()
|
||||
}
|
||||
|
||||
// diskHasAnyTag reports whether the disk carries any of the given tags.
|
||||
func diskHasAnyTag(d *disk, tags []string) bool {
|
||||
for _, want := range tags {
|
||||
for _, have := range d.tags {
|
||||
if have == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Destination is a chosen target for one shard. DataCenter and Rack are kept as
|
||||
// separate values (matching topology.DiskInfo) rather than a "dc:rack" composite,
|
||||
// so callers read them directly instead of parsing.
|
||||
type Destination struct {
|
||||
Node string
|
||||
DiskID uint32
|
||||
DataCenter string
|
||||
Rack string // bare rack id within DataCenter
|
||||
}
|
||||
|
||||
// PlaceResult holds the chosen destinations, which constraints had to be relaxed
|
||||
// (durability-first only), and whether placement spilled outside the preferred
|
||||
// disk type or tag tiers (for parity with today's logging).
|
||||
type PlaceResult struct {
|
||||
Destinations map[int]Destination
|
||||
Relaxed []string
|
||||
SpilledToOtherDiskType bool
|
||||
SpilledOutsidePreferredTags bool
|
||||
}
|
||||
|
||||
// PlacementMode selects the strictness/relaxation policy.
|
||||
type PlacementMode int
|
||||
|
||||
const (
|
||||
// PlaceStrict: caps and ReplicaPlacement are hard. Place fails rather than
|
||||
// violate them, so the caller can defer (leave the volume as-is and retry).
|
||||
PlaceStrict PlacementMode = iota
|
||||
// PlaceDurabilityFirst (used by both encode and repair): relax per-type caps ->
|
||||
// data/parity anti-affinity -> ReplicaPlacement, in that order, until each shard
|
||||
// lands, reporting what was relaxed in PlaceResult.Relaxed. The per-disk
|
||||
// durability cap (<= parityShards per disk) is never relaxed. Fails only if no
|
||||
// disk has free capacity. Encode places best-effort this way and rebalancing
|
||||
// tightens the spread afterward.
|
||||
PlaceDurabilityFirst
|
||||
)
|
||||
|
||||
// relaxation controls which placement-quality constraints are enforced on an
|
||||
// attempt. preferring fresh nodes (repair's "avoid surviving-shard nodes") is not
|
||||
// listed: pickNodeInRack already selects the node with the fewest shards of the
|
||||
// volume, so survivors are deprioritized with built-in fallback.
|
||||
type relaxation struct {
|
||||
caps bool
|
||||
antiAffinity bool
|
||||
rp bool
|
||||
}
|
||||
|
||||
func (r relaxation) relaxedNames() []string {
|
||||
var n []string
|
||||
if !r.caps {
|
||||
n = append(n, "caps")
|
||||
}
|
||||
if !r.antiAffinity {
|
||||
n = append(n, "anti-affinity")
|
||||
}
|
||||
if !r.rp {
|
||||
n = append(n, "replica-placement")
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
var strictAttempts = []relaxation{{caps: true, antiAffinity: true, rp: true}}
|
||||
|
||||
var durabilityAttempts = []relaxation{
|
||||
{caps: true, antiAffinity: true, rp: true},
|
||||
{caps: false, antiAffinity: true, rp: true},
|
||||
{caps: false, antiAffinity: false, rp: true},
|
||||
{caps: false, antiAffinity: false, rp: false},
|
||||
}
|
||||
|
||||
type placedEntry struct {
|
||||
node *Node
|
||||
sid int
|
||||
rackKey string
|
||||
}
|
||||
|
||||
// Place assigns destinations for the `need` shard ids of volume (collection,vid),
|
||||
// reading the volume's already-placed shards from the snapshot (so encode passes
|
||||
// an empty-for-this-volume snapshot, repair passes one seeded with the surviving
|
||||
// shards).
|
||||
//
|
||||
// Tag tiering (whole-plan retry): it tries the preferred-tag tiers in order, each
|
||||
// a complete candidate set, and returns the first tier that places every shard;
|
||||
// only when it falls through to the no-tag tier does it set
|
||||
// SpilledOutsidePreferredTags. Within a tier, disk-type Prefer spills to other
|
||||
// types per shard (SpilledToOtherDiskType); Require filters strictly.
|
||||
func (t *Topology) Place(vid uint32, collection string, need []int, c Constraints, mode PlacementMode) (*PlaceResult, error) {
|
||||
if len(need) == 0 {
|
||||
return &PlaceResult{Destinations: map[int]Destination{}}, nil
|
||||
}
|
||||
|
||||
vk := volKey{collection: collection, vid: vid}
|
||||
dataShards, parityShards := erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount
|
||||
if c.Ratio != nil {
|
||||
if d, p := c.Ratio(collection); d > 0 && p > 0 {
|
||||
dataShards, parityShards = d, p
|
||||
}
|
||||
}
|
||||
|
||||
racks := buildRacks(t.nodes)
|
||||
if len(racks) == 0 {
|
||||
return nil, fmt.Errorf("no racks available for EC placement")
|
||||
}
|
||||
rackKeys := sortedKeys(racks)
|
||||
|
||||
// Disk-type eligibility (Require filters; Any/Prefer admit all) and the soft
|
||||
// type preference applied in scoring under Prefer.
|
||||
typeEligible := func(d *disk) bool {
|
||||
if c.DiskTypePolicy == DiskTypeRequire {
|
||||
return diskTypeEqual(d.diskType, c.DiskType)
|
||||
}
|
||||
return true
|
||||
}
|
||||
var prefer func(*disk) bool
|
||||
if c.DiskTypePolicy == DiskTypePrefer {
|
||||
prefer = func(d *disk) bool { return diskTypeEqual(d.diskType, c.DiskType) }
|
||||
}
|
||||
|
||||
// Whole-plan retry over preferred-tag tiers; the first tier that places every
|
||||
// shard wins. Reaching the no-tag tier means we spilled outside the tags.
|
||||
tiers := tagTiers(c.PreferredTags)
|
||||
var lastErr error
|
||||
for _, tierTags := range tiers {
|
||||
tt := tierTags
|
||||
eligible := func(d *disk) bool {
|
||||
return typeEligible(d) && (len(tt) == 0 || diskHasAnyTag(d, tt))
|
||||
}
|
||||
res, err := t.tryPlace(vk, need, dataShards, parityShards, racks, rackKeys, mode, c.ReplicaPlacement, eligible, prefer)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
if len(c.PreferredTags) > 0 && len(tierTags) == 0 {
|
||||
res.SpilledOutsidePreferredTags = true
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
// tagTiers returns the eligibility tag-sets in increasing breadth, ending with an
|
||||
// empty set ("any disk"). Empty preferredTags yields a single any-disk tier.
|
||||
func tagTiers(preferredTags []string) [][]string {
|
||||
if len(preferredTags) == 0 {
|
||||
return [][]string{nil}
|
||||
}
|
||||
tiers := make([][]string, 0, len(preferredTags)+1)
|
||||
for k := range preferredTags {
|
||||
tiers = append(tiers, append([]string(nil), preferredTags[:k+1]...))
|
||||
}
|
||||
return append(tiers, nil)
|
||||
}
|
||||
|
||||
// tryPlace runs one whole-plan placement attempt restricted to disks satisfying
|
||||
// `eligible`, with `prefer` (may be nil) ranking soft-preferred disks first. It
|
||||
// journals reservations and rolls them all back if any shard cannot be placed, so
|
||||
// a failed tier leaves the snapshot unchanged for the next attempt.
|
||||
func (t *Topology) tryPlace(vk volKey, need []int, dataShards, parityShards int, racks map[string]*rack, rackKeys []string, mode PlacementMode, rp *super_block.ReplicaPlacement, eligible func(*disk) bool, prefer func(*disk) bool) (*PlaceResult, error) {
|
||||
result := &PlaceResult{Destinations: make(map[int]Destination, len(need))}
|
||||
|
||||
// Per-type shard ids per rack (even caps), total shard count per rack
|
||||
// (DiffRackCount), and the racks bearing each type (anti-affinity) — all seeded
|
||||
// from the volume's existing shards.
|
||||
shardsPerRack := map[bool]map[string][]int{true: {}, false: {}}
|
||||
rackShardCount := map[string]int{}
|
||||
bearing := map[bool]map[string]bool{true: {}, false: {}}
|
||||
for _, n := range t.nodes {
|
||||
info, ok := n.shards[vk]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for sid := range info.shardBits.All() {
|
||||
s := int(sid)
|
||||
isData := s < dataShards
|
||||
shardsPerRack[isData][n.rack] = append(shardsPerRack[isData][n.rack], s)
|
||||
rackShardCount[n.rack]++
|
||||
bearing[isData][n.rack] = true
|
||||
}
|
||||
}
|
||||
|
||||
// Even per-rack caps divide by racks that actually have an eligible free disk,
|
||||
// not all racks (the snapshot keeps every disk type/tag), so a valid tiered
|
||||
// cluster — e.g. SSDs in only 2 of 4 racks — is not capped impossibly low.
|
||||
numEligibleRacks := 0
|
||||
for _, rk := range rackKeys {
|
||||
if rackHasFreeDisk(racks[rk], eligible) {
|
||||
numEligibleRacks++
|
||||
}
|
||||
}
|
||||
if numEligibleRacks < 1 {
|
||||
numEligibleRacks = 1
|
||||
}
|
||||
|
||||
attempts := strictAttempts
|
||||
if mode == PlaceDurabilityFirst {
|
||||
attempts = durabilityAttempts
|
||||
}
|
||||
|
||||
var journal []placedEntry
|
||||
relaxedSeen := map[string]bool{}
|
||||
spilledType := false
|
||||
|
||||
placeShard := func(sid int, isData bool) bool {
|
||||
typeTotal := dataShards
|
||||
if !isData {
|
||||
typeTotal = parityShards
|
||||
}
|
||||
for _, rl := range attempts {
|
||||
node, diskID, spilled, ok := chooseShardDest(vk, sid, isData, dataShards, typeTotal, numEligibleRacks, parityShards, racks, rackKeys, rp, eligible, prefer, shardsPerRack[isData], rackShardCount, bearing, rl)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
reserveShard(node, vk, sid, diskID)
|
||||
node.freeSlots--
|
||||
racks[node.rack].freeSlots--
|
||||
shardsPerRack[isData][node.rack] = append(shardsPerRack[isData][node.rack], sid)
|
||||
rackShardCount[node.rack]++
|
||||
bearing[isData][node.rack] = true
|
||||
journal = append(journal, placedEntry{node: node, sid: sid, rackKey: node.rack})
|
||||
result.Destinations[sid] = Destination{
|
||||
Node: node.id,
|
||||
DiskID: diskID,
|
||||
DataCenter: node.dc,
|
||||
Rack: strings.TrimPrefix(node.rack, node.dc+":"),
|
||||
}
|
||||
if spilled {
|
||||
spilledType = true
|
||||
}
|
||||
for _, name := range rl.relaxedNames() {
|
||||
relaxedSeen[name] = true
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Data shards first, then parity, so parity can avoid data-bearing racks.
|
||||
for _, isData := range []bool{true, false} {
|
||||
for _, sid := range shardsOfType(need, isData, dataShards) {
|
||||
if placeShard(sid, isData) {
|
||||
continue
|
||||
}
|
||||
for _, e := range journal {
|
||||
releaseShard(e.node, vk, e.sid)
|
||||
e.node.freeSlots++
|
||||
racks[e.rackKey].freeSlots++
|
||||
}
|
||||
return nil, fmt.Errorf("cannot place EC shard %d of volume %d (collection %q)", sid, vk.vid, vk.collection)
|
||||
}
|
||||
}
|
||||
|
||||
result.SpilledToOtherDiskType = spilledType
|
||||
for name := range relaxedSeen {
|
||||
result.Relaxed = append(result.Relaxed, name)
|
||||
}
|
||||
sort.Strings(result.Relaxed)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// chooseShardDest selects a (node, disk) for one shard at the given relaxation
|
||||
// level: pick a rack (even per-type cap + ReplicaPlacement caps + two-pass
|
||||
// anti-affinity to the opposite type), then the least-loaded eligible node, then
|
||||
// the best eligible disk. The third return reports whether the disk spilled off
|
||||
// the soft-preferred type. ok=false when no rack/node/disk fits.
|
||||
func chooseShardDest(vk volKey, sid int, isData bool, dataShards, typeTotal, numEligibleRacks, maxPerDisk int, racks map[string]*rack, rackKeys []string, rp *super_block.ReplicaPlacement, eligible func(*disk) bool, prefer func(*disk) bool, shardsPerRackType map[string][]int, rackShardCount map[string]int, bearing map[bool]map[string]bool, rl relaxation) (*Node, uint32, bool, bool) {
|
||||
maxPerRack := numEligibleRacks*typeTotal + 1 // effectively unlimited when caps are relaxed
|
||||
if rl.caps {
|
||||
if maxPerRack = ceilDivide(typeTotal, numEligibleRacks); maxPerRack < 1 {
|
||||
maxPerRack = 1
|
||||
}
|
||||
}
|
||||
|
||||
var anti map[string]bool
|
||||
if rl.antiAffinity {
|
||||
anti = bearing[!isData] // racks already holding the opposite shard type
|
||||
}
|
||||
|
||||
if !rl.rp {
|
||||
rp = nil
|
||||
}
|
||||
// A rack is eligible only if it is under the per-rack shard cap (DiffRackCount),
|
||||
// enforced only when set (and relaxed with rp).
|
||||
withinLimit := func(r string) bool {
|
||||
if rp == nil {
|
||||
return true
|
||||
}
|
||||
if rp.DiffRackCount > 0 && rackShardCount[r] >= rp.DiffRackCount {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
destRack, ok := pickTarget(rackKeys, shardsPerRackType, maxPerRack, anti,
|
||||
func(r string) bool { return racks[r].freeSlots > 0 && rackHasFreeDisk(racks[r], eligible) },
|
||||
withinLimit)
|
||||
if !ok {
|
||||
return nil, 0, false, false
|
||||
}
|
||||
node := pickNodeInRackEligible(racks[destRack], vk, rp, eligible)
|
||||
if node == nil {
|
||||
return nil, 0, false, false
|
||||
}
|
||||
diskID, ok, spilled := pickBestDiskEligible(node, vk, eligible, prefer, sid, dataShards, maxPerDisk)
|
||||
if !ok {
|
||||
return nil, 0, false, false
|
||||
}
|
||||
return node, diskID, spilled, true
|
||||
}
|
||||
|
||||
// nodeHasFreeDisk reports whether the node has a free disk satisfying eligible.
|
||||
func nodeHasFreeDisk(n *Node, eligible func(*disk) bool) bool {
|
||||
for _, d := range n.disks {
|
||||
if d.freeSlots > 0 && eligible(d) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// rackHasFreeDisk reports whether any node in the rack has a free eligible disk.
|
||||
func rackHasFreeDisk(r *rack, eligible func(*disk) bool) bool {
|
||||
for _, n := range r.nodes {
|
||||
if n.freeSlots > 0 && nodeHasFreeDisk(n, eligible) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// pickNodeInRackEligible is pickNodeInRack restricted to nodes that have a free
|
||||
// eligible disk. FromActiveTopology keeps all disk types/tags in the snapshot, so
|
||||
// without this a node with free volume slots but no eligible disk could be chosen.
|
||||
func pickNodeInRackEligible(r *rack, vk volKey, rp *super_block.ReplicaPlacement, eligible func(*disk) bool) *Node {
|
||||
var best *Node
|
||||
bestCount := -1
|
||||
for _, id := range sortedNodeKeys(r.nodes) {
|
||||
node := r.nodes[id]
|
||||
if node.freeSlots <= 0 {
|
||||
continue
|
||||
}
|
||||
if !nodeHasFreeDisk(node, eligible) {
|
||||
continue
|
||||
}
|
||||
count := volumeShardCount(node, vk)
|
||||
if rp != nil && rp.SameRackCount > 0 && count >= rp.SameRackCount {
|
||||
continue
|
||||
}
|
||||
if best == nil || count < bestCount {
|
||||
best, bestCount = node, count
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
// pickBestDiskEligible chooses the best eligible disk on a node, ranking
|
||||
// soft-preferred disks (prefer != nil && prefer(d)) ahead of others so disk-type
|
||||
// Prefer uses the preferred type when available but spills otherwise. Returns the
|
||||
// disk id, whether one was found, and whether the chosen disk spilled off the
|
||||
// preferred type.
|
||||
func pickBestDiskEligible(node *Node, vk volKey, eligible func(*disk) bool, prefer func(*disk) bool, shardID, dataShardCount, maxPerDisk int) (uint32, bool, bool) {
|
||||
isDataShard := dataShardCount > 0 && shardID < dataShardCount
|
||||
info := node.shards[vk]
|
||||
var bestDiskID uint32
|
||||
bestScore := -1
|
||||
bestPreferred := false
|
||||
for _, diskID := range sortedDiskKeys(node.disks) {
|
||||
d := node.disks[diskID]
|
||||
if !eligible(d) || d.freeSlots <= 0 {
|
||||
continue
|
||||
}
|
||||
existingShards := 0
|
||||
hasData := false
|
||||
hasParity := false
|
||||
if info != nil {
|
||||
bits := info.diskShardBits[diskID]
|
||||
existingShards = bits.Count()
|
||||
if dataShardCount > 0 {
|
||||
for sid := range bits.All() {
|
||||
if int(sid) < dataShardCount {
|
||||
hasData = true
|
||||
} else {
|
||||
hasParity = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Durability: never put more than maxPerDisk (parityShards) shards of this
|
||||
// volume on one disk, or losing that disk would lose more than EC can
|
||||
// recover. Hard cap, enforced even under durability-first relaxation.
|
||||
if maxPerDisk > 0 && existingShards >= maxPerDisk {
|
||||
continue
|
||||
}
|
||||
score := d.shardCount*10 + existingShards*100
|
||||
if dataShardCount > 0 {
|
||||
if isDataShard && hasParity {
|
||||
score += 1000
|
||||
} else if !isDataShard && hasData {
|
||||
score += 1000
|
||||
}
|
||||
}
|
||||
preferred := prefer == nil || prefer(d)
|
||||
if !preferred {
|
||||
score += 100000 // strongly deprioritize spilling to a non-preferred type
|
||||
}
|
||||
if bestScore == -1 || score < bestScore {
|
||||
bestScore = score
|
||||
bestDiskID = diskID
|
||||
bestPreferred = preferred
|
||||
}
|
||||
}
|
||||
if bestScore == -1 {
|
||||
return 0, false, false
|
||||
}
|
||||
return bestDiskID, true, prefer != nil && !bestPreferred
|
||||
}
|
||||
|
||||
// clearShardAccounting removes one shard copy of a volume from the snapshot's
|
||||
// per-domain accounting (the volume's shard bits) WITHOUT crediting disk capacity.
|
||||
// It clears only the given physical disk's bit, then recomputes the node-level
|
||||
// union from the remaining disk bits, so a kept copy of the same shard on another
|
||||
// disk of the same node still counts toward caps / ReplicaPlacement / anti-affinity.
|
||||
//
|
||||
// Repair uses this to drop the duplicate/mismatched copies it plans to delete
|
||||
// before placing missing shards, so those copies do not inflate placement
|
||||
// accounting. Capacity is deliberately NOT credited: the deletes run only after
|
||||
// the rebuilt shards are distributed, so the slots are not free at plan time. This
|
||||
// is distinct from releaseShard, which credits freeSlots and clears the union.
|
||||
func clearShardAccounting(node *Node, vk volKey, shardID int, diskID uint32) {
|
||||
info, ok := node.shards[vk]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
sid := erasure_coding.ShardId(shardID)
|
||||
if bits, ok := info.diskShardBits[diskID]; ok {
|
||||
info.diskShardBits[diskID] = bits.Clear(sid)
|
||||
}
|
||||
var union erasure_coding.ShardBits
|
||||
for _, b := range info.diskShardBits {
|
||||
union |= b
|
||||
}
|
||||
info.shardBits = union
|
||||
}
|
||||
|
||||
// ClearShardAccounting drops one shard copy of a volume from placement accounting
|
||||
// without crediting capacity (see clearShardAccounting). Repair calls it for each
|
||||
// copy it plans to delete before placing missing shards, so those copies do not
|
||||
// inflate caps/RP/anti-affinity. No-op for an unknown node.
|
||||
func (t *Topology) ClearShardAccounting(nodeID, collection string, vid uint32, shardID int, diskID uint32) {
|
||||
n, ok := t.nodes[nodeID]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
clearShardAccounting(n, volKey{collection: collection, vid: vid}, shardID, diskID)
|
||||
}
|
||||
|
||||
// ReleaseVolumeShards removes every shard of a volume from the snapshot and
|
||||
// credits the freed disk capacity. A greenfield encode calls this so any stale
|
||||
// EC shards left by a prior failed attempt (which the encode task deletes before
|
||||
// distributing the new shards) neither occupy capacity nor skew anti-affinity /
|
||||
// per-disk caps during planning. Unlike repair's ClearShardAccounting, it credits
|
||||
// freeSlots because the deletes run before the new writes.
|
||||
func (t *Topology) ReleaseVolumeShards(collection string, vid uint32) {
|
||||
vk := volKey{collection: collection, vid: vid}
|
||||
for _, n := range t.nodes {
|
||||
info, ok := n.shards[vk]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// freed is the total disk-slots the volume occupies on this node (a shard may
|
||||
// sit on more than one disk). releaseShard credits each disk's freeSlots;
|
||||
// credit the node's freeSlots by the same total, since rack capacity is summed
|
||||
// from node freeSlots (buildRacks) and node freeSlots gates node eligibility.
|
||||
freed := 0
|
||||
for _, bits := range info.diskShardBits {
|
||||
freed += bits.Count()
|
||||
}
|
||||
sids := make([]int, 0, info.shardBits.Count())
|
||||
for sid := range info.shardBits.All() {
|
||||
sids = append(sids, int(sid))
|
||||
}
|
||||
for _, sid := range sids {
|
||||
releaseShard(n, vk, sid)
|
||||
}
|
||||
n.freeSlots += freed
|
||||
delete(n.shards, vk)
|
||||
}
|
||||
}
|
||||
|
||||
// shardsOfType returns the sorted subset of need that are data shards (id <
|
||||
// dataShards) when isData, else the parity subset.
|
||||
func shardsOfType(need []int, isData bool, dataShards int) []int {
|
||||
var out []int
|
||||
for _, s := range need {
|
||||
if (s < dataShards) == isData {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
sort.Ints(out)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
package ecbalancer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
)
|
||||
|
||||
// buildPlaceTopo makes a topology of racks x nodesPerRack, each node one disk with
|
||||
// perDiskFree free EC shard slots.
|
||||
func buildPlaceTopo(racks, nodesPerRack, perDiskFree int) *Topology {
|
||||
topo := NewTopology()
|
||||
for r := 0; r < racks; r++ {
|
||||
rackKey := fmt.Sprintf("dc1:rack%d", r)
|
||||
for n := 0; n < nodesPerRack; n++ {
|
||||
id := fmt.Sprintf("10.0.%d.%d:8080", r, n)
|
||||
node := topo.AddNode(id, "dc1", rackKey, perDiskFree)
|
||||
node.AddDisk(0, "", perDiskFree, 0)
|
||||
}
|
||||
}
|
||||
return topo
|
||||
}
|
||||
|
||||
func allShards() []int {
|
||||
out := make([]int, erasure_coding.TotalShardsCount)
|
||||
for i := range out {
|
||||
out[i] = i
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TestPlaceStrictSpreadAndCaps places a fresh 10+4 volume and checks every shard
|
||||
// lands on a distinct node and no rack exceeds the even per-type cap.
|
||||
func TestPlaceStrictSpreadAndCaps(t *testing.T) {
|
||||
const racks = 4
|
||||
topo := buildPlaceTopo(racks, 4, 50)
|
||||
|
||||
res, err := topo.Place(1, "c1", allShards(), Constraints{}, PlaceStrict)
|
||||
if err != nil {
|
||||
t.Fatalf("Place: %v", err)
|
||||
}
|
||||
if len(res.Destinations) != erasure_coding.TotalShardsCount {
|
||||
t.Fatalf("placed %d shards, want %d", len(res.Destinations), erasure_coding.TotalShardsCount)
|
||||
}
|
||||
|
||||
usedNodes := map[string]bool{}
|
||||
dataPerRack := map[string]int{}
|
||||
parityPerRack := map[string]int{}
|
||||
for sid, d := range res.Destinations {
|
||||
if usedNodes[d.Node] {
|
||||
t.Errorf("node %s reused for shard %d (expected distinct nodes with ample capacity)", d.Node, sid)
|
||||
}
|
||||
usedNodes[d.Node] = true
|
||||
if sid < erasure_coding.DataShardsCount {
|
||||
dataPerRack[d.Rack]++
|
||||
} else {
|
||||
parityPerRack[d.Rack]++
|
||||
}
|
||||
}
|
||||
dataCap := ceilDivide(erasure_coding.DataShardsCount, racks)
|
||||
parityCap := ceilDivide(erasure_coding.ParityShardsCount, racks)
|
||||
for rk, n := range dataPerRack {
|
||||
if n > dataCap {
|
||||
t.Errorf("rack %s holds %d data shards, cap %d", rk, n, dataCap)
|
||||
}
|
||||
}
|
||||
for rk, n := range parityPerRack {
|
||||
if n > parityCap {
|
||||
t.Errorf("rack %s holds %d parity shards, cap %d", rk, n, parityCap)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlaceStrictFailsAndRollsBack: a single tiny disk cannot hold 14 shards, so
|
||||
// strict Place fails and leaves the snapshot untouched.
|
||||
func TestPlaceStrictFailsAndRollsBack(t *testing.T) {
|
||||
topo := buildPlaceTopo(1, 1, 2) // one node, room for 2 shards
|
||||
node := topo.nodes["10.0.0.0:8080"]
|
||||
freeBefore := node.freeSlots
|
||||
diskFreeBefore := node.disks[0].freeSlots
|
||||
|
||||
_, err := topo.Place(1, "c1", allShards(), Constraints{}, PlaceStrict)
|
||||
if err == nil {
|
||||
t.Fatal("expected Place to fail on insufficient capacity")
|
||||
}
|
||||
if info, ok := node.shards[volKey{collection: "c1", vid: 1}]; ok && info.shardBits.Count() != 0 {
|
||||
t.Errorf("volume shard bits left on node after failed strict Place (rollback incomplete): %b", info.shardBits)
|
||||
}
|
||||
if node.freeSlots != freeBefore {
|
||||
t.Errorf("node freeSlots = %d after rollback, want %d", node.freeSlots, freeBefore)
|
||||
}
|
||||
if node.disks[0].freeSlots != diskFreeBefore {
|
||||
t.Errorf("disk freeSlots = %d after rollback, want %d", node.disks[0].freeSlots, diskFreeBefore)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlaceDurabilityFirstRelaxesRP: a ReplicaPlacement rack limit too tight for
|
||||
// the shard count makes strict fail, while durability-first relaxes RP to place
|
||||
// everything and reports the relaxation.
|
||||
func TestPlaceDurabilityFirstRelaxesRP(t *testing.T) {
|
||||
rp := &super_block.ReplicaPlacement{DiffRackCount: 3} // <=3 shards per rack
|
||||
topo := buildPlaceTopo(2, 8, 50) // 2 racks: 2*3=6 < 14 under RP
|
||||
|
||||
if _, err := topo.Place(1, "c1", allShards(), Constraints{ReplicaPlacement: rp}, PlaceStrict); err == nil {
|
||||
t.Fatal("strict Place should fail when RP rack limit cannot fit all shards")
|
||||
}
|
||||
|
||||
topo = buildPlaceTopo(2, 8, 50)
|
||||
res, err := topo.Place(1, "c1", allShards(), Constraints{ReplicaPlacement: rp}, PlaceDurabilityFirst)
|
||||
if err != nil {
|
||||
t.Fatalf("durability-first Place: %v", err)
|
||||
}
|
||||
if len(res.Destinations) != erasure_coding.TotalShardsCount {
|
||||
t.Fatalf("placed %d shards, want %d", len(res.Destinations), erasure_coding.TotalShardsCount)
|
||||
}
|
||||
relaxedRP := false
|
||||
for _, r := range res.Relaxed {
|
||||
if r == "replica-placement" {
|
||||
relaxedRP = true
|
||||
}
|
||||
}
|
||||
if !relaxedRP {
|
||||
t.Errorf("expected replica-placement relaxation, got %v", res.Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlaceSameRackCountIsDirectPerNodeCap: the 3rd ReplicaPlacement digit
|
||||
// (SameRackCount) caps shards per node directly (max == digit), matching the
|
||||
// per-rack DiffRackCount cap rather than allowing digit+1 per node.
|
||||
func TestPlaceSameRackCountIsDirectPerNodeCap(t *testing.T) {
|
||||
rp := &super_block.ReplicaPlacement{SameRackCount: 2} // <=2 shards per node
|
||||
|
||||
// 5 single-node racks: 5 nodes * 2 = 10 < 14, so a strict 10+4 placement
|
||||
// cannot satisfy the per-node cap and must fail. Under the old digit+1 reading
|
||||
// the cap would be 3/node => 15 slots and this would have wrongly succeeded.
|
||||
topo := buildPlaceTopo(5, 1, 50)
|
||||
if _, err := topo.Place(1, "c1", allShards(), Constraints{ReplicaPlacement: rp}, PlaceStrict); err == nil {
|
||||
t.Fatal("strict Place should fail: 5 nodes cannot hold 14 shards at <=2 per node")
|
||||
}
|
||||
|
||||
// Durability-first relaxes the unsatisfiable per-node cap, still places every
|
||||
// shard, and reports the relaxation so it isn't silently weakened.
|
||||
topo = buildPlaceTopo(5, 1, 50)
|
||||
res, err := topo.Place(1, "c1", allShards(), Constraints{ReplicaPlacement: rp}, PlaceDurabilityFirst)
|
||||
if err != nil {
|
||||
t.Fatalf("durability-first Place: %v", err)
|
||||
}
|
||||
if len(res.Destinations) != erasure_coding.TotalShardsCount {
|
||||
t.Fatalf("placed %d shards, want %d", len(res.Destinations), erasure_coding.TotalShardsCount)
|
||||
}
|
||||
relaxedRP := false
|
||||
for _, r := range res.Relaxed {
|
||||
if r == "replica-placement" {
|
||||
relaxedRP = true
|
||||
}
|
||||
}
|
||||
if !relaxedRP {
|
||||
t.Errorf("expected replica-placement relaxation, got %v", res.Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlaceDiskTypeHardFilter: with DiskType set, shards land only on disks of
|
||||
// that type, even though the snapshot also contains other-typed disks.
|
||||
func TestPlaceDiskTypeHardFilter(t *testing.T) {
|
||||
topo := NewTopology()
|
||||
for r := 0; r < 4; r++ {
|
||||
rackKey := fmt.Sprintf("dc1:rack%d", r)
|
||||
ssd := topo.AddNode(fmt.Sprintf("ssd-%d:8080", r), "dc1", rackKey, 50)
|
||||
ssd.AddDisk(0, "ssd", 50, 0)
|
||||
hdd := topo.AddNode(fmt.Sprintf("hdd-%d:8080", r), "dc1", rackKey, 50)
|
||||
hdd.AddDisk(0, "hdd", 50, 0)
|
||||
}
|
||||
|
||||
res, err := topo.Place(1, "c1", allShards(), Constraints{DiskType: "ssd", DiskTypePolicy: DiskTypeRequire}, PlaceStrict)
|
||||
if err != nil {
|
||||
t.Fatalf("Place ssd: %v", err)
|
||||
}
|
||||
for sid, d := range res.Destinations {
|
||||
node := topo.nodes[d.Node]
|
||||
disk := node.disks[d.DiskID]
|
||||
if disk == nil || disk.diskType != "ssd" {
|
||||
t.Errorf("shard %d placed on non-ssd disk: node=%s diskID=%d", sid, d.Node, d.DiskID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlaceDiskTypeUnavailableFails: a request for a disk type with no matching
|
||||
// disks fails rather than silently placing on the wrong tier.
|
||||
func TestPlaceDiskTypeUnavailableFails(t *testing.T) {
|
||||
topo := NewTopology()
|
||||
for r := 0; r < 4; r++ {
|
||||
n := topo.AddNode(fmt.Sprintf("hdd-%d:8080", r), "dc1", fmt.Sprintf("dc1:rack%d", r), 50)
|
||||
n.AddDisk(0, "hdd", 50, 0)
|
||||
}
|
||||
if _, err := topo.Place(1, "c1", allShards(), Constraints{DiskType: "ssd", DiskTypePolicy: DiskTypeRequire}, PlaceStrict); err == nil {
|
||||
t.Fatal("expected Place to fail when no disks of the requested type exist")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlaceHDDRequestMatchesEmptyTypeDisks: a "hdd" request normalizes to
|
||||
// HardDriveType ("") and must land on the HDD disk (reported as ""), never the SSD
|
||||
// disk, even on nodes that have both.
|
||||
func TestPlaceHDDRequestMatchesEmptyTypeDisks(t *testing.T) {
|
||||
topo := NewTopology()
|
||||
for r := 0; r < 6; r++ {
|
||||
n := topo.AddNode(fmt.Sprintf("n%d:8080", r), "dc1", fmt.Sprintf("dc1:rack%d", r), 100)
|
||||
n.AddDisk(0, "", 50, 0) // HDD (HardDriveType, reported as "")
|
||||
n.AddDisk(1, "ssd", 50, 0) // SSD
|
||||
}
|
||||
|
||||
res, err := topo.Place(1, "c1", allShards(), Constraints{DiskType: "hdd", DiskTypePolicy: DiskTypeRequire}, PlaceStrict)
|
||||
if err != nil {
|
||||
t.Fatalf("Place hdd: %v", err)
|
||||
}
|
||||
for sid, d := range res.Destinations {
|
||||
if d.DiskID != 0 { // disk 0 is the HDD disk on every node
|
||||
t.Errorf("shard %d placed on disk %d (expected HDD disk 0) on node %s", sid, d.DiskID, d.Node)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlaceDurabilityCapRejectsSkewed: in a near-full cluster where only one disk
|
||||
// has spare room, Place must not pile more than parityShards shards onto it (losing
|
||||
// it would then lose more than EC can recover). It fails instead, so the caller
|
||||
// leaves the volume unencoded rather than minting an unrecoverable layout.
|
||||
func TestPlaceDurabilityCapRejectsSkewed(t *testing.T) {
|
||||
topo := NewTopology()
|
||||
// One spacious node plus four nearly-full ones, all in a single rack.
|
||||
a := topo.AddNode("a:8080", "dc1", "dc1:rack0", 100)
|
||||
a.AddDisk(0, "", 100, 0)
|
||||
for i := 0; i < 4; i++ {
|
||||
n := topo.AddNode(fmt.Sprintf("b%d:8080", i), "dc1", "dc1:rack0", 1)
|
||||
n.AddDisk(0, "", 1, 0)
|
||||
}
|
||||
|
||||
// 14 shards, parity 4: node a is capped at 4, the others hold 1 each -> at most
|
||||
// 4+4=8 placeable without exceeding parityShards on a disk, so Place must fail.
|
||||
// (Without the per-disk cap, a would greedily absorb 10 shards and "succeed".)
|
||||
if _, err := topo.Place(1, "c1", allShards(), Constraints{}, PlaceDurabilityFirst); err == nil {
|
||||
t.Fatal("expected Place to fail rather than pile >parityShards shards on one disk")
|
||||
}
|
||||
}
|
||||
|
||||
// TestReleaseVolumeShards: removes all of a volume's shards from the snapshot and
|
||||
// credits the freed capacity at BOTH disk and node level (rack capacity sums node
|
||||
// freeSlots), mirroring how FromActiveTopology accounts stale shards.
|
||||
func TestReleaseVolumeShards(t *testing.T) {
|
||||
topo := NewTopology()
|
||||
// Node total 20 = two disks of 10. Two stale shards occupy one slot each, so the
|
||||
// snapshot would show disk0/disk1 at 9 and node at 18 (as FromActiveTopology does).
|
||||
n := topo.AddNode("n0:8080", "dc1", "dc1:rack0", 20)
|
||||
n.AddDisk(0, "", 10, 0)
|
||||
n.AddDisk(1, "", 10, 0)
|
||||
vk := volKey{collection: "c1", vid: 1}
|
||||
n.AddShards(1, "c1", 0, erasure_coding.ShardBits(uint32(1)<<3))
|
||||
n.AddShards(1, "c1", 1, erasure_coding.ShardBits(uint32(1)<<7))
|
||||
n.disks[0].freeSlots = 9
|
||||
n.disks[1].freeSlots = 9
|
||||
n.freeSlots = 18
|
||||
|
||||
topo.ReleaseVolumeShards("c1", 1)
|
||||
|
||||
if _, ok := n.shards[vk]; ok {
|
||||
t.Error("volume shards should be gone after ReleaseVolumeShards")
|
||||
}
|
||||
if n.disks[0].freeSlots != 10 || n.disks[1].freeSlots != 10 {
|
||||
t.Errorf("disk freeSlots not restored: disk0=%d, disk1=%d (want 10, 10)", n.disks[0].freeSlots, n.disks[1].freeSlots)
|
||||
}
|
||||
if n.freeSlots != 20 {
|
||||
t.Errorf("node freeSlots = %d, want 20 (must be credited at node level too)", n.freeSlots)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClearShardAccounting: dropping one disk's copy of a shard preserves a kept
|
||||
// copy of the same shard on another disk of the same node, and credits no capacity.
|
||||
func TestClearShardAccounting(t *testing.T) {
|
||||
topo := NewTopology()
|
||||
n := topo.AddNode("n0:8080", "dc1", "dc1:rack0", 50)
|
||||
n.AddDisk(0, "", 50, 0)
|
||||
n.AddDisk(1, "", 50, 0)
|
||||
vk := volKey{collection: "c1", vid: 1}
|
||||
// Shard 3 lives on disk 0 (keep) and disk 1 (duplicate to delete).
|
||||
n.AddShards(1, "c1", 0, erasure_coding.ShardBits(uint32(1)<<3))
|
||||
n.AddShards(1, "c1", 1, erasure_coding.ShardBits(uint32(1)<<3))
|
||||
if got := n.shards[vk].shardBits.Count(); got != 1 {
|
||||
t.Fatalf("union count = %d, want 1", got)
|
||||
}
|
||||
freeBefore := n.disks[1].freeSlots
|
||||
|
||||
clearShardAccounting(n, vk, 3, 1)
|
||||
|
||||
if !n.shards[vk].shardBits.Has(erasure_coding.ShardId(3)) {
|
||||
t.Error("kept copy of shard 3 (disk 0) lost from the node-level union")
|
||||
}
|
||||
if n.shards[vk].diskShardBits[1].Has(erasure_coding.ShardId(3)) {
|
||||
t.Error("disk-1 copy of shard 3 was not cleared")
|
||||
}
|
||||
if n.disks[1].freeSlots != freeBefore {
|
||||
t.Errorf("freeSlots changed %d -> %d; clearShardAccounting must not credit capacity", freeBefore, n.disks[1].freeSlots)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlaceDiskTypePreferSpills: DiskTypePrefer fills the preferred type first and
|
||||
// spills the remainder to other types, reporting SpilledToOtherDiskType. SSD is
|
||||
// scarce (one tiny SSD per node) so the volume must spill to HDD, but there are
|
||||
// enough disks to keep each within the parityShards durability cap.
|
||||
func TestPlaceDiskTypePreferSpills(t *testing.T) {
|
||||
topo := NewTopology()
|
||||
for r := 0; r < 8; r++ {
|
||||
n := topo.AddNode(fmt.Sprintf("n%d:8080", r), "dc1", fmt.Sprintf("dc1:rack%d", r), 100)
|
||||
n.AddDisk(0, "ssd", 1, 0) // tiny SSD: 1 shard
|
||||
n.AddDisk(1, "", 50, 0) // roomy HDD
|
||||
}
|
||||
|
||||
res, err := topo.Place(1, "c1", allShards(), Constraints{DiskType: "ssd", DiskTypePolicy: DiskTypePrefer}, PlaceDurabilityFirst)
|
||||
if err != nil {
|
||||
t.Fatalf("Place: %v", err)
|
||||
}
|
||||
if len(res.Destinations) != erasure_coding.TotalShardsCount {
|
||||
t.Fatalf("placed %d, want %d", len(res.Destinations), erasure_coding.TotalShardsCount)
|
||||
}
|
||||
ssd, hdd := 0, 0
|
||||
for _, d := range res.Destinations {
|
||||
if topo.nodes[d.Node].disks[d.DiskID].diskType == "ssd" {
|
||||
ssd++
|
||||
} else {
|
||||
hdd++
|
||||
}
|
||||
}
|
||||
if ssd == 0 || hdd == 0 {
|
||||
t.Errorf("expected prefer-then-spill: some shards on SSD and some on HDD, got ssd=%d hdd=%d", ssd, hdd)
|
||||
}
|
||||
if !res.SpilledToOtherDiskType {
|
||||
t.Error("expected SpilledToOtherDiskType when SSD cannot hold every shard")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlacePreferredTagsUseTaggedDisks: when tagged disks can hold the whole plan,
|
||||
// every shard lands on a tagged disk and no spill is reported.
|
||||
func TestPlacePreferredTagsUseTaggedDisks(t *testing.T) {
|
||||
topo := NewTopology()
|
||||
for r := 0; r < 4; r++ {
|
||||
rackKey := fmt.Sprintf("dc1:rack%d", r)
|
||||
fast := topo.AddNode(fmt.Sprintf("fast-%d:8080", r), "dc1", rackKey, 50)
|
||||
fast.AddDisk(0, "", 50, 0)
|
||||
fast.AddDiskTags(0, []string{"fast"})
|
||||
topo.AddNode(fmt.Sprintf("slow-%d:8080", r), "dc1", rackKey, 50).AddDisk(0, "", 50, 0)
|
||||
}
|
||||
|
||||
res, err := topo.Place(1, "c1", allShards(), Constraints{PreferredTags: []string{"fast"}}, PlaceStrict)
|
||||
if err != nil {
|
||||
t.Fatalf("Place: %v", err)
|
||||
}
|
||||
for sid, d := range res.Destinations {
|
||||
if !diskHasAnyTag(topo.nodes[d.Node].disks[d.DiskID], []string{"fast"}) {
|
||||
t.Errorf("shard %d placed on an untagged disk (node %s)", sid, d.Node)
|
||||
}
|
||||
}
|
||||
if res.SpilledOutsidePreferredTags {
|
||||
t.Error("did not expect tag spill when tagged disks suffice")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlacePreferredTagsSpillWhenInsufficient: when the tagged tier cannot hold the
|
||||
// whole plan, Place falls back to all disks and reports SpilledOutsidePreferredTags.
|
||||
func TestPlacePreferredTagsSpillWhenInsufficient(t *testing.T) {
|
||||
topo := NewTopology()
|
||||
for r := 0; r < 4; r++ {
|
||||
n := topo.AddNode(fmt.Sprintf("n-%d:8080", r), "dc1", fmt.Sprintf("dc1:rack%d", r), 50)
|
||||
if r == 0 {
|
||||
n.AddDisk(0, "", 5, 0) // the only tagged disk, too small for 14 shards
|
||||
n.AddDiskTags(0, []string{"fast"})
|
||||
} else {
|
||||
n.AddDisk(0, "", 50, 0)
|
||||
}
|
||||
}
|
||||
|
||||
res, err := topo.Place(1, "c1", allShards(), Constraints{PreferredTags: []string{"fast"}}, PlaceStrict)
|
||||
if err != nil {
|
||||
t.Fatalf("Place: %v", err)
|
||||
}
|
||||
if len(res.Destinations) != erasure_coding.TotalShardsCount {
|
||||
t.Fatalf("placed %d, want %d", len(res.Destinations), erasure_coding.TotalShardsCount)
|
||||
}
|
||||
if !res.SpilledOutsidePreferredTags {
|
||||
t.Error("expected SpilledOutsidePreferredTags when the single fast disk cannot hold the plan")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlaceStrictCapsCountEligibleRacks: with DiskTypeRequire, the even per-rack
|
||||
// cap divides by racks that have a matching disk, not all racks, so SSDs in only
|
||||
// some racks still place successfully.
|
||||
func TestPlaceStrictCapsCountEligibleRacks(t *testing.T) {
|
||||
topo := NewTopology()
|
||||
// SSDs live in only 2 of 4 racks, with several SSD nodes per rack so 14 shards
|
||||
// fit at <= parityShards per disk. The even per-rack cap must divide by the 2
|
||||
// eligible racks (ceil(10/2)=5 data/rack), not all 4 (ceil(10/4)=3 -> infeasible).
|
||||
for r := 0; r < 4; r++ {
|
||||
rackKey := fmt.Sprintf("dc1:rack%d", r)
|
||||
topo.AddNode(fmt.Sprintf("hdd-%d:8080", r), "dc1", rackKey, 50).AddDisk(0, "", 50, 0)
|
||||
if r < 2 {
|
||||
for n := 0; n < 4; n++ {
|
||||
topo.AddNode(fmt.Sprintf("ssd-%d-%d:8080", r, n), "dc1", rackKey, 50).AddDisk(0, "ssd", 50, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res, err := topo.Place(1, "c1", allShards(), Constraints{DiskType: "ssd", DiskTypePolicy: DiskTypeRequire}, PlaceStrict)
|
||||
if err != nil {
|
||||
t.Fatalf("Place ssd in 2/4 racks: %v", err)
|
||||
}
|
||||
if len(res.Destinations) != erasure_coding.TotalShardsCount {
|
||||
t.Fatalf("placed %d, want %d", len(res.Destinations), erasure_coding.TotalShardsCount)
|
||||
}
|
||||
for sid, d := range res.Destinations {
|
||||
if disk := topo.nodes[d.Node].disks[d.DiskID]; disk == nil || disk.diskType != "ssd" {
|
||||
t.Errorf("shard %d not on an SSD disk: node=%s disk=%d", sid, d.Node, d.DiskID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package ecbalancer
|
||||
|
||||
import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
)
|
||||
|
||||
// shardDataShards returns the data-shard count of the volume an EC shard belongs
|
||||
// to, used to size the shard's disk footprint. OSS uses the standard ratio for
|
||||
// every volume; custom per-volume ratios are an enterprise feature, so the
|
||||
// enterprise build overrides this to read the per-shard ratio.
|
||||
func shardDataShards(eci *master_pb.VolumeEcShardInformationMessage) int {
|
||||
return erasure_coding.DataShardsCount
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package ecbalancer
|
||||
|
||||
import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/topology"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
)
|
||||
|
||||
// FromActiveTopology builds a Topology snapshot from the cluster's ActiveTopology
|
||||
// using the reservation-aware effective-capacity view that EC encode and repair
|
||||
// rely on. It collects ALL EC-eligible disks with no hard disk-type filter;
|
||||
// disk-type preference is applied later by callers (Place). Per-disk free EC shard
|
||||
// slots come from GetEffectiveAvailableEcShardSlots (shard-granular, so in-flight
|
||||
// task reservations that are not whole-volume multiples are not lost) minus the EC
|
||||
// shards already persisted on the disk. Rack keys are composite "dc:rack".
|
||||
//
|
||||
// dataShards is the target collection's data-shard count, used to size free EC
|
||||
// shard slots correctly for custom ratios (a 4+2 volume's shards are larger, so
|
||||
// fewer fit per volume slot). Pass <= 0 for the default scheme. Because of this,
|
||||
// the snapshot is ratio-specific; build one per collection ratio being placed.
|
||||
//
|
||||
// This is the encode/repair-side constructor; balance keeps its own raw-topology
|
||||
// builder (buildBalancerTopology) until the snapshot sources are reconciled.
|
||||
func FromActiveTopology(at *topology.ActiveTopology, dataShards int) *Topology {
|
||||
topo := NewTopology()
|
||||
if at == nil {
|
||||
return topo
|
||||
}
|
||||
|
||||
disks := at.GetDisksWithEffectiveCapacity(topology.TaskTypeErasureCoding, "", 0)
|
||||
|
||||
// Accumulate node-level free slots and group the node's disks together.
|
||||
nodeFree := make(map[string]int)
|
||||
nodeDC := make(map[string]string)
|
||||
nodeRack := make(map[string]string)
|
||||
byNode := make(map[string][]*topology.DiskInfo)
|
||||
for _, d := range disks {
|
||||
if d == nil || d.DiskInfo == nil {
|
||||
continue
|
||||
}
|
||||
if free := perDiskFreeECSlots(at, d, dataShards); free > 0 {
|
||||
nodeFree[d.NodeID] += free
|
||||
}
|
||||
nodeDC[d.NodeID] = d.DataCenter
|
||||
nodeRack[d.NodeID] = d.DataCenter + ":" + d.Rack
|
||||
byNode[d.NodeID] = append(byNode[d.NodeID], d)
|
||||
}
|
||||
|
||||
for nodeID, ds := range byNode {
|
||||
node := topo.AddNode(nodeID, nodeDC[nodeID], nodeRack[nodeID], nodeFree[nodeID])
|
||||
for _, d := range ds {
|
||||
free := perDiskFreeECSlots(at, d, dataShards)
|
||||
if free < 0 {
|
||||
free = 0
|
||||
}
|
||||
node.AddDisk(d.DiskID, d.DiskType, free, ecShardCountOnDisk(d))
|
||||
node.AddDiskTags(d.DiskID, d.DiskInfo.Tags)
|
||||
for _, eci := range d.DiskInfo.EcShardInfos {
|
||||
if eci.DiskId != d.DiskID {
|
||||
continue
|
||||
}
|
||||
node.AddShards(eci.Id, eci.Collection, d.DiskID, erasure_coding.ShardBits(eci.EcIndexBits))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return topo
|
||||
}
|
||||
|
||||
// perDiskFreeECSlots returns the disk's free EC shard slots for a volume with
|
||||
// dataShards data shards: the topology's shard-granular effective availability
|
||||
// (sized by the target ratio) minus the EC shards already on the disk, also
|
||||
// expressed in the target ratio's shard slots so mixed-ratio disks are charged by
|
||||
// size rather than raw count.
|
||||
func perDiskFreeECSlots(at *topology.ActiveTopology, d *topology.DiskInfo, dataShards int) int {
|
||||
return at.GetEffectiveAvailableEcShardSlots(d.NodeID, d.DiskID, dataShards) - ecShardSlotsOnDisk(d, dataShards)
|
||||
}
|
||||
|
||||
// ecShardCountOnDisk counts the EC shards physically on this disk (matching
|
||||
// eci.DiskId), across all volumes. Used as a per-disk load metric for scoring.
|
||||
func ecShardCountOnDisk(d *topology.DiskInfo) int {
|
||||
count := 0
|
||||
for _, eci := range d.DiskInfo.EcShardInfos {
|
||||
if eci.DiskId == d.DiskID {
|
||||
count += erasure_coding.GetShardCount(eci)
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// ecShardSlotsOnDisk returns the EC shards already on the disk expressed in the
|
||||
// TARGET collection's shard slots. A shard of a collection with d data shards
|
||||
// occupies ~1/d of a volume, i.e. targetDataShards/d target slots, so a 2+1 shard
|
||||
// counted against a 10+4 snapshot consumes ~5 slots, not 1.
|
||||
func ecShardSlotsOnDisk(d *topology.DiskInfo, targetDataShards int) int {
|
||||
if targetDataShards <= 0 {
|
||||
targetDataShards = erasure_coding.DataShardsCount
|
||||
}
|
||||
total := 0
|
||||
for _, eci := range d.DiskInfo.EcShardInfos {
|
||||
if eci.DiskId != d.DiskID {
|
||||
continue
|
||||
}
|
||||
ds := shardDataShards(eci)
|
||||
if ds <= 0 {
|
||||
ds = erasure_coding.DataShardsCount
|
||||
}
|
||||
// Round up so an existing shard always consumes at least its fractional
|
||||
// footprint; flooring lets a low-data-shard volume (targetDataShards < ds)
|
||||
// count as zero target slots and overstate the disk's free capacity.
|
||||
total += (erasure_coding.GetShardCount(eci)*targetDataShards + ds - 1) / ds
|
||||
}
|
||||
return total
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package ecbalancer
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/topology"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
)
|
||||
|
||||
// TestFromActiveTopology verifies the encode/repair-side snapshot constructor maps
|
||||
// nodes, per-disk EC shard counts, per-volume shard bits, and free slots from an
|
||||
// ActiveTopology. Shard accounting is asserted exactly; free slots are asserted to
|
||||
// be positive (their exact value depends on effective-capacity internals).
|
||||
func TestFromActiveTopology(t *testing.T) {
|
||||
const vid uint32 = 7
|
||||
at := topology.NewActiveTopology(10)
|
||||
|
||||
// Node A holds one EC shard (id 3) of volume 7 on disk 0; node B is empty.
|
||||
nodeA := &master_pb.DataNodeInfo{
|
||||
Id: "10.0.0.1:8080",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"hdd": {
|
||||
DiskId: 0,
|
||||
MaxVolumeCount: 100,
|
||||
VolumeCount: 1,
|
||||
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{{
|
||||
Id: vid,
|
||||
Collection: "c1",
|
||||
EcIndexBits: uint32(1) << 3,
|
||||
DiskId: 0,
|
||||
}},
|
||||
},
|
||||
},
|
||||
}
|
||||
nodeB := &master_pb.DataNodeInfo{
|
||||
Id: "10.0.0.2:8080",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"hdd": {DiskId: 0, MaxVolumeCount: 100, VolumeCount: 0},
|
||||
},
|
||||
}
|
||||
if err := at.UpdateTopology(&master_pb.TopologyInfo{
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{{
|
||||
Id: "rack1",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{nodeA, nodeB},
|
||||
}},
|
||||
}},
|
||||
}); err != nil {
|
||||
t.Fatalf("UpdateTopology: %v", err)
|
||||
}
|
||||
|
||||
topo := FromActiveTopology(at, 0)
|
||||
|
||||
if got := len(topo.nodes); got != 2 {
|
||||
t.Fatalf("node count = %d, want 2", got)
|
||||
}
|
||||
|
||||
a := topo.nodes["10.0.0.1:8080"]
|
||||
if a == nil {
|
||||
t.Fatal("node A missing from snapshot")
|
||||
}
|
||||
if a.rack != "dc1:rack1" {
|
||||
t.Errorf("node A rack = %q, want dc1:rack1", a.rack)
|
||||
}
|
||||
diskA := a.disks[0]
|
||||
if diskA == nil {
|
||||
t.Fatal("node A disk 0 missing")
|
||||
}
|
||||
if diskA.shardCount != 1 {
|
||||
t.Errorf("node A disk 0 shardCount = %d, want 1", diskA.shardCount)
|
||||
}
|
||||
vs := a.shards[volKey{collection: "c1", vid: vid}]
|
||||
if vs == nil {
|
||||
t.Fatal("volume 7 shards not recorded on node A")
|
||||
}
|
||||
if !vs.shardBits.Has(erasure_coding.ShardId(3)) {
|
||||
t.Errorf("node A volume 7 shardBits %b missing shard 3", vs.shardBits)
|
||||
}
|
||||
if vs.shardBits.Count() != 1 {
|
||||
t.Errorf("node A volume 7 shard count = %d, want 1", vs.shardBits.Count())
|
||||
}
|
||||
|
||||
b := topo.nodes["10.0.0.2:8080"]
|
||||
if b == nil {
|
||||
t.Fatal("node B missing from snapshot")
|
||||
}
|
||||
if b.rack != "dc1:rack1" {
|
||||
t.Errorf("node B rack = %q, want dc1:rack1", b.rack)
|
||||
}
|
||||
if diskB := b.disks[0]; diskB == nil || diskB.shardCount != 0 {
|
||||
t.Errorf("node B disk 0 shardCount = %v, want 0", diskB)
|
||||
}
|
||||
if len(b.shards) != 0 {
|
||||
t.Errorf("node B should hold no volume shards, got %d", len(b.shards))
|
||||
}
|
||||
|
||||
// Free slots should be positive on both near-empty disks.
|
||||
if a.freeSlots <= 0 || b.freeSlots <= 0 {
|
||||
t.Errorf("free slots not positive: A=%d B=%d", a.freeSlots, b.freeSlots)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEcShardSlotsOnDiskRoundsUp covers the mixed-ratio (targetDataShards <
|
||||
// existingDataShards) conversion: an existing shard's fractional footprint must
|
||||
// round up so it is never floored to zero, which would overstate free capacity.
|
||||
// OSS always uses the standard ratio at runtime, but ecShardSlotsOnDisk takes the
|
||||
// target data-shard count as a parameter, so the fractional path is exercised
|
||||
// directly here; the enterprise build reaches it with real per-volume ratios.
|
||||
func TestEcShardSlotsOnDiskRoundsUp(t *testing.T) {
|
||||
// A single shard (id 3) of a standard 10-data-shard volume on disk 0.
|
||||
disk := &topology.DiskInfo{
|
||||
DiskID: 0,
|
||||
DiskInfo: &master_pb.DiskInfo{
|
||||
DiskId: 0,
|
||||
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{{
|
||||
Id: 7,
|
||||
Collection: "c1",
|
||||
EcIndexBits: uint32(1) << 3,
|
||||
DiskId: 0,
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
// Against a 2-data-shard target the shard occupies 2/10 of a slot, which must
|
||||
// round up to 1 rather than floor to 0.
|
||||
if got := ecShardSlotsOnDisk(disk, 2); got != 1 {
|
||||
t.Errorf("ecShardSlotsOnDisk(target=2) = %d, want 1 (rounded up from 0.2)", got)
|
||||
}
|
||||
|
||||
// Identity case: target equals the existing data-shard count, so the shard
|
||||
// consumes exactly its whole-number footprint.
|
||||
if got := ecShardSlotsOnDisk(disk, erasure_coding.DataShardsCount); got != 1 {
|
||||
t.Errorf("ecShardSlotsOnDisk(target=%d) = %d, want 1", erasure_coding.DataShardsCount, got)
|
||||
}
|
||||
}
|
||||
@@ -1,461 +0,0 @@
|
||||
// Package placement provides consolidated EC shard placement logic used by
|
||||
// both shell commands and worker tasks.
|
||||
//
|
||||
// This package encapsulates the algorithms for:
|
||||
// - Selecting destination nodes/disks for EC shards
|
||||
// - Ensuring proper spread across racks, servers, and disks
|
||||
// - Balancing shards across the cluster
|
||||
package placement
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// DiskCandidate represents a disk that can receive EC shards
|
||||
type DiskCandidate struct {
|
||||
NodeID string
|
||||
DiskID uint32
|
||||
DataCenter string
|
||||
Rack string
|
||||
DiskType string // disk type (hdd/ssd/...) — empty means HardDrive
|
||||
|
||||
// Capacity information
|
||||
VolumeCount int64
|
||||
MaxVolumeCount int64
|
||||
ShardCount int // Current number of EC shards on this disk
|
||||
FreeSlots int // Available slots for new shards
|
||||
|
||||
// Load information
|
||||
LoadCount int // Number of active tasks on this disk
|
||||
}
|
||||
|
||||
// NodeCandidate represents a server node that can receive EC shards
|
||||
type NodeCandidate struct {
|
||||
NodeID string
|
||||
DataCenter string
|
||||
Rack string
|
||||
FreeSlots int
|
||||
ShardCount int // Total shards across all disks
|
||||
Disks []*DiskCandidate // All disks on this node
|
||||
}
|
||||
|
||||
// PlacementRequest configures EC shard placement behavior
|
||||
type PlacementRequest struct {
|
||||
// ShardsNeeded is the total number of shards to place
|
||||
ShardsNeeded int
|
||||
|
||||
// MaxShardsPerServer limits how many shards can be placed on a single server
|
||||
// 0 means no limit (but prefer spreading when possible)
|
||||
MaxShardsPerServer int
|
||||
|
||||
// MaxShardsPerRack limits how many shards can be placed in a single rack
|
||||
// 0 means no limit
|
||||
MaxShardsPerRack int
|
||||
|
||||
// MaxTaskLoad is the maximum task load count for a disk to be considered
|
||||
MaxTaskLoad int
|
||||
|
||||
// PreferDifferentServers when true, spreads shards across different servers
|
||||
// before using multiple disks on the same server
|
||||
PreferDifferentServers bool
|
||||
|
||||
// PreferDifferentRacks when true, spreads shards across different racks
|
||||
// before using multiple servers in the same rack
|
||||
PreferDifferentRacks bool
|
||||
|
||||
// PreferredDiskType, when non-empty, biases placement toward disks of
|
||||
// this type. Disks of the preferred type are exhausted (subject to the
|
||||
// other diversity preferences) before disks of any other type are
|
||||
// considered. Empty means no disk-type bias — all suitable disks form a
|
||||
// single pool, matching pre-#9423 behavior.
|
||||
PreferredDiskType string
|
||||
}
|
||||
|
||||
// PlacementResult contains the selected destinations for EC shards
|
||||
type PlacementResult struct {
|
||||
SelectedDisks []*DiskCandidate
|
||||
|
||||
// Statistics
|
||||
ServersUsed int
|
||||
RacksUsed int
|
||||
DCsUsed int
|
||||
|
||||
// Distribution maps
|
||||
ShardsPerServer map[string]int
|
||||
ShardsPerRack map[string]int
|
||||
ShardsPerDC map[string]int
|
||||
|
||||
// SpilledToOtherDiskType is set when PlacementRequest.PreferredDiskType
|
||||
// was non-empty but the preferred-type pool could not satisfy
|
||||
// ShardsNeeded, so placement had to spill onto disks of other types.
|
||||
// Callers can log a warning when this is true.
|
||||
SpilledToOtherDiskType bool
|
||||
}
|
||||
|
||||
// SelectDestinations selects the best disks for EC shard placement.
|
||||
// This is the main entry point for EC placement logic.
|
||||
//
|
||||
// Disk-type preference (#9423): when config.PreferredDiskType is non-empty,
|
||||
// suitable disks are partitioned into a matching-type tier and a
|
||||
// fallback tier. Each tier is run through the diversity passes below;
|
||||
// the fallback tier is only consulted if the matching tier runs out of
|
||||
// candidates before ShardsNeeded is satisfied. Empty PreferredDiskType
|
||||
// processes all suitable disks as one tier, preserving prior behavior.
|
||||
//
|
||||
// Within each tier, the algorithm works in multiple passes:
|
||||
// 1. First pass: Select one disk from each rack (maximize rack diversity)
|
||||
// 2. Second pass: Select one disk from each unused server in used racks (maximize server diversity)
|
||||
// 3. Third pass: Select additional disks from servers already used (maximize disk diversity)
|
||||
func SelectDestinations(disks []*DiskCandidate, config PlacementRequest) (*PlacementResult, error) {
|
||||
if len(disks) == 0 {
|
||||
return nil, fmt.Errorf("no disk candidates provided")
|
||||
}
|
||||
if config.ShardsNeeded <= 0 {
|
||||
return nil, fmt.Errorf("shardsNeeded must be positive, got %d", config.ShardsNeeded)
|
||||
}
|
||||
|
||||
// Filter suitable disks
|
||||
suitable := filterSuitableDisks(disks, config)
|
||||
if len(suitable) == 0 {
|
||||
return nil, fmt.Errorf("no suitable disks found after filtering")
|
||||
}
|
||||
|
||||
result := &PlacementResult{
|
||||
SelectedDisks: make([]*DiskCandidate, 0, config.ShardsNeeded),
|
||||
ShardsPerServer: make(map[string]int),
|
||||
ShardsPerRack: make(map[string]int),
|
||||
ShardsPerDC: make(map[string]int),
|
||||
}
|
||||
|
||||
usedDisks := make(map[string]bool) // "nodeID:diskID" -> bool
|
||||
usedServers := make(map[string]bool) // nodeID -> bool
|
||||
usedRacks := make(map[string]bool) // "dc:rack" -> bool
|
||||
|
||||
// Partition suitable into preferred-disk-type / fallback tiers.
|
||||
// Process the preferred tier first; only spill to fallback when the
|
||||
// preferred pool can't satisfy ShardsNeeded.
|
||||
preferredTier, fallbackTier := partitionByDiskType(suitable, config.PreferredDiskType)
|
||||
selectFromTier(preferredTier, result, usedDisks, usedServers, usedRacks, config)
|
||||
if config.PreferredDiskType != "" && len(result.SelectedDisks) < config.ShardsNeeded && len(fallbackTier) > 0 {
|
||||
before := len(result.SelectedDisks)
|
||||
selectFromTier(fallbackTier, result, usedDisks, usedServers, usedRacks, config)
|
||||
if len(result.SelectedDisks) > before {
|
||||
result.SpilledToOtherDiskType = true
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate final statistics
|
||||
result.ServersUsed = len(usedServers)
|
||||
result.RacksUsed = len(usedRacks)
|
||||
dcSet := make(map[string]bool)
|
||||
for _, disk := range result.SelectedDisks {
|
||||
dcSet[disk.DataCenter] = true
|
||||
}
|
||||
result.DCsUsed = len(dcSet)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// partitionByDiskType splits disks into (matching, fallback) based on the
|
||||
// preferred disk type. If preferred is empty, everything goes into the
|
||||
// matching tier and fallback is empty — i.e. existing single-pool behavior.
|
||||
//
|
||||
// Empty DiskCandidate.DiskType is treated as HardDriveType ("hdd") to
|
||||
// mirror weed/storage/types.ToDiskType's normalization, so a
|
||||
// PreferredDiskType of "hdd" matches disks reporting "" — otherwise EC
|
||||
// shards from an HDD source would always spill onto disks that happen to
|
||||
// report their type as "" (HardDriveType).
|
||||
func partitionByDiskType(disks []*DiskCandidate, preferred string) (matching, fallback []*DiskCandidate) {
|
||||
if preferred == "" {
|
||||
return disks, nil
|
||||
}
|
||||
pref := normalizeDiskType(preferred)
|
||||
for _, d := range disks {
|
||||
if normalizeDiskType(d.DiskType) == pref {
|
||||
matching = append(matching, d)
|
||||
} else {
|
||||
fallback = append(fallback, d)
|
||||
}
|
||||
}
|
||||
return matching, fallback
|
||||
}
|
||||
|
||||
// normalizeDiskType lower-cases the input and folds "" to "hdd" so the
|
||||
// HardDriveType sentinel ("") and explicit "hdd"/"HDD" all compare equal.
|
||||
func normalizeDiskType(t string) string {
|
||||
t = strings.ToLower(t)
|
||||
if t == "" {
|
||||
return "hdd"
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// selectFromTier runs the three diversity passes against `tier`, mutating
|
||||
// `result` and the used* maps in place. Passes stop as soon as ShardsNeeded
|
||||
// is reached. The function is a no-op when the tier is empty or the result
|
||||
// already has enough shards, so it is safe to call once per tier.
|
||||
func selectFromTier(tier []*DiskCandidate, result *PlacementResult,
|
||||
usedDisks, usedServers, usedRacks map[string]bool,
|
||||
config PlacementRequest) {
|
||||
|
||||
if len(tier) == 0 || len(result.SelectedDisks) >= config.ShardsNeeded {
|
||||
return
|
||||
}
|
||||
|
||||
rackToDisks := groupDisksByRack(tier)
|
||||
|
||||
// Pass 1: Select one disk from each rack (maximize rack diversity).
|
||||
// When this is the fallback tier (preferred tier already populated
|
||||
// usedRacks), skip those racks so the spillover still spreads onto
|
||||
// new racks instead of doubling up on ones already picked.
|
||||
if config.PreferDifferentRacks {
|
||||
// Sort racks by number of available servers (descending) to prioritize racks with more options
|
||||
sortedRacks := sortRacksByServerCount(rackToDisks)
|
||||
for _, rackKey := range sortedRacks {
|
||||
if len(result.SelectedDisks) >= config.ShardsNeeded {
|
||||
break
|
||||
}
|
||||
if usedRacks[rackKey] {
|
||||
continue
|
||||
}
|
||||
rackDisks := rackToDisks[rackKey]
|
||||
// Select best disk from this rack, preferring a new server
|
||||
disk := selectBestDiskFromRack(rackDisks, usedServers, usedDisks, config)
|
||||
if disk != nil {
|
||||
addDiskToResult(result, disk, usedDisks, usedServers, usedRacks)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 2: Select disks from unused servers in already-used racks
|
||||
if config.PreferDifferentServers && len(result.SelectedDisks) < config.ShardsNeeded {
|
||||
for _, rackKey := range getSortedRackKeys(rackToDisks) {
|
||||
if len(result.SelectedDisks) >= config.ShardsNeeded {
|
||||
break
|
||||
}
|
||||
rackDisks := rackToDisks[rackKey]
|
||||
for _, disk := range sortDisksByScore(rackDisks) {
|
||||
if len(result.SelectedDisks) >= config.ShardsNeeded {
|
||||
break
|
||||
}
|
||||
diskKey := getDiskKey(disk)
|
||||
if usedDisks[diskKey] {
|
||||
continue
|
||||
}
|
||||
// Skip if server already used (we want different servers in this pass)
|
||||
if usedServers[disk.NodeID] {
|
||||
continue
|
||||
}
|
||||
// Check server limit
|
||||
if config.MaxShardsPerServer > 0 && result.ShardsPerServer[disk.NodeID] >= config.MaxShardsPerServer {
|
||||
continue
|
||||
}
|
||||
// Check rack limit
|
||||
if config.MaxShardsPerRack > 0 && result.ShardsPerRack[getRackKey(disk)] >= config.MaxShardsPerRack {
|
||||
continue
|
||||
}
|
||||
addDiskToResult(result, disk, usedDisks, usedServers, usedRacks)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 3: Fill remaining slots from already-used servers (different disks)
|
||||
// Use round-robin across servers to balance shards evenly
|
||||
if len(result.SelectedDisks) < config.ShardsNeeded {
|
||||
// Group remaining disks by server (within this tier)
|
||||
serverToRemainingDisks := make(map[string][]*DiskCandidate)
|
||||
for _, disk := range tier {
|
||||
if !usedDisks[getDiskKey(disk)] {
|
||||
serverToRemainingDisks[disk.NodeID] = append(serverToRemainingDisks[disk.NodeID], disk)
|
||||
}
|
||||
}
|
||||
|
||||
// Sort each server's disks by score
|
||||
for serverID := range serverToRemainingDisks {
|
||||
serverToRemainingDisks[serverID] = sortDisksByScore(serverToRemainingDisks[serverID])
|
||||
}
|
||||
|
||||
// Round-robin: repeatedly select from the server with the fewest shards
|
||||
for len(result.SelectedDisks) < config.ShardsNeeded {
|
||||
// Find server with fewest shards that still has available disks
|
||||
var bestServer string
|
||||
minShards := -1
|
||||
for serverID, disks := range serverToRemainingDisks {
|
||||
if len(disks) == 0 {
|
||||
continue
|
||||
}
|
||||
// Check server limit
|
||||
if config.MaxShardsPerServer > 0 && result.ShardsPerServer[serverID] >= config.MaxShardsPerServer {
|
||||
continue
|
||||
}
|
||||
shardCount := result.ShardsPerServer[serverID]
|
||||
if minShards == -1 || shardCount < minShards {
|
||||
minShards = shardCount
|
||||
bestServer = serverID
|
||||
} else if shardCount == minShards && serverID < bestServer {
|
||||
// Tie-break by server name for determinism
|
||||
bestServer = serverID
|
||||
}
|
||||
}
|
||||
|
||||
if bestServer == "" {
|
||||
// No more servers with available disks
|
||||
break
|
||||
}
|
||||
|
||||
// Pop the best disk from this server
|
||||
disks := serverToRemainingDisks[bestServer]
|
||||
disk := disks[0]
|
||||
serverToRemainingDisks[bestServer] = disks[1:]
|
||||
|
||||
// Check rack limit
|
||||
if config.MaxShardsPerRack > 0 && result.ShardsPerRack[getRackKey(disk)] >= config.MaxShardsPerRack {
|
||||
continue
|
||||
}
|
||||
|
||||
addDiskToResult(result, disk, usedDisks, usedServers, usedRacks)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// filterSuitableDisks filters disks that are suitable for EC placement
|
||||
func filterSuitableDisks(disks []*DiskCandidate, config PlacementRequest) []*DiskCandidate {
|
||||
var suitable []*DiskCandidate
|
||||
for _, disk := range disks {
|
||||
if disk.FreeSlots <= 0 {
|
||||
continue
|
||||
}
|
||||
if config.MaxTaskLoad > 0 && disk.LoadCount > config.MaxTaskLoad {
|
||||
continue
|
||||
}
|
||||
suitable = append(suitable, disk)
|
||||
}
|
||||
return suitable
|
||||
}
|
||||
|
||||
// groupDisksByRack groups disks by their rack (dc:rack key)
|
||||
func groupDisksByRack(disks []*DiskCandidate) map[string][]*DiskCandidate {
|
||||
result := make(map[string][]*DiskCandidate)
|
||||
for _, disk := range disks {
|
||||
key := getRackKey(disk)
|
||||
result[key] = append(result[key], disk)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// getRackKey returns the unique key for a rack (dc:rack)
|
||||
func getRackKey(disk *DiskCandidate) string {
|
||||
return fmt.Sprintf("%s:%s", disk.DataCenter, disk.Rack)
|
||||
}
|
||||
|
||||
// getDiskKey returns the unique key for a disk (nodeID:diskID)
|
||||
func getDiskKey(disk *DiskCandidate) string {
|
||||
return fmt.Sprintf("%s:%d", disk.NodeID, disk.DiskID)
|
||||
}
|
||||
|
||||
// sortRacksByServerCount returns rack keys sorted by number of servers (ascending)
|
||||
func sortRacksByServerCount(rackToDisks map[string][]*DiskCandidate) []string {
|
||||
// Count unique servers per rack
|
||||
rackServerCount := make(map[string]int)
|
||||
for rackKey, disks := range rackToDisks {
|
||||
servers := make(map[string]bool)
|
||||
for _, disk := range disks {
|
||||
servers[disk.NodeID] = true
|
||||
}
|
||||
rackServerCount[rackKey] = len(servers)
|
||||
}
|
||||
|
||||
keys := getSortedRackKeys(rackToDisks)
|
||||
sort.Slice(keys, func(i, j int) bool {
|
||||
// Sort by server count (descending) to pick from racks with more options first
|
||||
return rackServerCount[keys[i]] > rackServerCount[keys[j]]
|
||||
})
|
||||
return keys
|
||||
}
|
||||
|
||||
// getSortedRackKeys returns rack keys in a deterministic order
|
||||
func getSortedRackKeys(rackToDisks map[string][]*DiskCandidate) []string {
|
||||
keys := make([]string, 0, len(rackToDisks))
|
||||
for k := range rackToDisks {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
|
||||
// selectBestDiskFromRack selects the best disk from a rack for EC placement
|
||||
// It prefers servers that haven't been used yet
|
||||
func selectBestDiskFromRack(disks []*DiskCandidate, usedServers, usedDisks map[string]bool, config PlacementRequest) *DiskCandidate {
|
||||
var bestDisk *DiskCandidate
|
||||
bestScore := -1.0
|
||||
bestIsFromUnusedServer := false
|
||||
|
||||
for _, disk := range disks {
|
||||
if usedDisks[getDiskKey(disk)] {
|
||||
continue
|
||||
}
|
||||
isFromUnusedServer := !usedServers[disk.NodeID]
|
||||
score := calculateDiskScore(disk)
|
||||
|
||||
// Prefer unused servers
|
||||
if isFromUnusedServer && !bestIsFromUnusedServer {
|
||||
bestDisk = disk
|
||||
bestScore = score
|
||||
bestIsFromUnusedServer = true
|
||||
} else if isFromUnusedServer == bestIsFromUnusedServer && score > bestScore {
|
||||
bestDisk = disk
|
||||
bestScore = score
|
||||
}
|
||||
}
|
||||
|
||||
return bestDisk
|
||||
}
|
||||
|
||||
// sortDisksByScore returns disks sorted by score (best first)
|
||||
func sortDisksByScore(disks []*DiskCandidate) []*DiskCandidate {
|
||||
sorted := make([]*DiskCandidate, len(disks))
|
||||
copy(sorted, disks)
|
||||
sort.Slice(sorted, func(i, j int) bool {
|
||||
return calculateDiskScore(sorted[i]) > calculateDiskScore(sorted[j])
|
||||
})
|
||||
return sorted
|
||||
}
|
||||
|
||||
// calculateDiskScore calculates a score for a disk candidate
|
||||
// Higher score is better
|
||||
func calculateDiskScore(disk *DiskCandidate) float64 {
|
||||
score := 0.0
|
||||
|
||||
// Primary factor: available capacity (lower utilization is better)
|
||||
if disk.MaxVolumeCount > 0 {
|
||||
utilization := float64(disk.VolumeCount) / float64(disk.MaxVolumeCount)
|
||||
score += (1.0 - utilization) * 60.0 // Up to 60 points
|
||||
} else {
|
||||
score += 30.0 // Default if no max count
|
||||
}
|
||||
|
||||
// Secondary factor: fewer shards already on this disk is better
|
||||
score += float64(10-disk.ShardCount) * 2.0 // Up to 20 points
|
||||
|
||||
// Tertiary factor: lower load is better
|
||||
score += float64(10 - disk.LoadCount) // Up to 10 points
|
||||
|
||||
return score
|
||||
}
|
||||
|
||||
// addDiskToResult adds a disk to the result and updates tracking maps
|
||||
func addDiskToResult(result *PlacementResult, disk *DiskCandidate,
|
||||
usedDisks, usedServers, usedRacks map[string]bool) {
|
||||
diskKey := getDiskKey(disk)
|
||||
rackKey := getRackKey(disk)
|
||||
|
||||
result.SelectedDisks = append(result.SelectedDisks, disk)
|
||||
usedDisks[diskKey] = true
|
||||
usedServers[disk.NodeID] = true
|
||||
usedRacks[rackKey] = true
|
||||
result.ShardsPerServer[disk.NodeID]++
|
||||
result.ShardsPerRack[rackKey]++
|
||||
result.ShardsPerDC[disk.DataCenter]++
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
package placement
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// makeDisk builds a DiskCandidate with sensible defaults; tests override
|
||||
// only the fields they care about.
|
||||
func makeDisk(node, rack, diskType string, diskID uint32) *DiskCandidate {
|
||||
return &DiskCandidate{
|
||||
NodeID: node,
|
||||
DiskID: diskID,
|
||||
DataCenter: "dc1",
|
||||
Rack: rack,
|
||||
DiskType: diskType,
|
||||
VolumeCount: 0,
|
||||
MaxVolumeCount: 100,
|
||||
FreeSlots: 100,
|
||||
}
|
||||
}
|
||||
|
||||
func disksByType(disks []*DiskCandidate) map[string]int {
|
||||
out := map[string]int{}
|
||||
for _, d := range disks {
|
||||
out[d.DiskType]++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func newRequest(shards int, preferred string) PlacementRequest {
|
||||
return PlacementRequest{
|
||||
ShardsNeeded: shards,
|
||||
PreferDifferentServers: true,
|
||||
PreferDifferentRacks: true,
|
||||
PreferredDiskType: preferred,
|
||||
}
|
||||
}
|
||||
|
||||
// Plenty of SSD disks available: placement should fill entirely from SSD
|
||||
// when PreferredDiskType="ssd", leaving HDDs untouched and not flagging
|
||||
// spillover.
|
||||
func TestSelectDestinations_PrefersMatchingDiskType(t *testing.T) {
|
||||
var disks []*DiskCandidate
|
||||
for i := 0; i < 6; i++ {
|
||||
disks = append(disks, makeDisk("ssd-"+strconv.Itoa(i), "r"+strconv.Itoa(i%3), "ssd", uint32(i)))
|
||||
}
|
||||
for i := 0; i < 6; i++ {
|
||||
disks = append(disks, makeDisk("hdd-"+strconv.Itoa(i), "r"+strconv.Itoa(i%3), "", uint32(i)))
|
||||
}
|
||||
|
||||
result, err := SelectDestinations(disks, newRequest(4, "ssd"))
|
||||
if err != nil {
|
||||
t.Fatalf("SelectDestinations: %v", err)
|
||||
}
|
||||
if got := len(result.SelectedDisks); got != 4 {
|
||||
t.Fatalf("selected %d disks, want 4", got)
|
||||
}
|
||||
if counts := disksByType(result.SelectedDisks); counts["ssd"] != 4 {
|
||||
t.Fatalf("disk-type counts = %v, want ssd=4", counts)
|
||||
}
|
||||
if result.SpilledToOtherDiskType {
|
||||
t.Fatalf("SpilledToOtherDiskType should be false when preferred pool was sufficient")
|
||||
}
|
||||
}
|
||||
|
||||
// Only one SSD disk available but 4 shards needed: placement must consume
|
||||
// the SSD first, then spill to HDD for the remainder, and report spillover.
|
||||
func TestSelectDestinations_SpillsWhenPreferredScarce(t *testing.T) {
|
||||
disks := []*DiskCandidate{
|
||||
makeDisk("ssd-0", "r0", "ssd", 0),
|
||||
makeDisk("hdd-0", "r1", "", 0),
|
||||
makeDisk("hdd-1", "r2", "", 0),
|
||||
makeDisk("hdd-2", "r3", "", 0),
|
||||
}
|
||||
|
||||
result, err := SelectDestinations(disks, newRequest(4, "ssd"))
|
||||
if err != nil {
|
||||
t.Fatalf("SelectDestinations: %v", err)
|
||||
}
|
||||
if got := len(result.SelectedDisks); got != 4 {
|
||||
t.Fatalf("selected %d disks, want 4", got)
|
||||
}
|
||||
counts := disksByType(result.SelectedDisks)
|
||||
if counts["ssd"] != 1 || counts[""] != 3 {
|
||||
t.Fatalf("disk-type counts = %v, want ssd=1 hdd=3", counts)
|
||||
}
|
||||
if !result.SpilledToOtherDiskType {
|
||||
t.Fatalf("SpilledToOtherDiskType should be true after falling back to HDD")
|
||||
}
|
||||
}
|
||||
|
||||
// PreferredDiskType="hdd" must match disks whose DiskType is "" (the
|
||||
// HardDriveType sentinel) — otherwise EC encoding of an HDD source would
|
||||
// always spill onto HDDs that happen to report disk_type="" even though
|
||||
// the cluster has plenty of matching capacity.
|
||||
func TestSelectDestinations_PreferredHddMatchesEmptyDiskType(t *testing.T) {
|
||||
disks := []*DiskCandidate{
|
||||
makeDisk("hdd-0", "r0", "", 0), // HardDriveType sentinel
|
||||
makeDisk("hdd-1", "r1", "", 0), // HardDriveType sentinel
|
||||
makeDisk("ssd-0", "r2", "ssd", 0),
|
||||
}
|
||||
|
||||
result, err := SelectDestinations(disks, newRequest(2, "hdd"))
|
||||
if err != nil {
|
||||
t.Fatalf("SelectDestinations: %v", err)
|
||||
}
|
||||
if got := len(result.SelectedDisks); got != 2 {
|
||||
t.Fatalf("selected %d disks, want 2", got)
|
||||
}
|
||||
// Both selected disks must be HDD-reporting (i.e. DiskType == ""),
|
||||
// and no spillover should have been required.
|
||||
for _, d := range result.SelectedDisks {
|
||||
if d.DiskType != "" {
|
||||
t.Errorf("selected disk %s has DiskType=%q, want \"\" (HardDriveType)", d.NodeID, d.DiskType)
|
||||
}
|
||||
}
|
||||
if result.SpilledToOtherDiskType {
|
||||
t.Fatalf("SpilledToOtherDiskType should be false when HDD pool matches preferred=hdd")
|
||||
}
|
||||
}
|
||||
|
||||
// Empty PreferredDiskType: pre-#9423 behavior, single pool, no spillover
|
||||
// flag regardless of disk-type mix.
|
||||
func TestSelectDestinations_EmptyPreferredDiskTypeKeepsPriorBehavior(t *testing.T) {
|
||||
disks := []*DiskCandidate{
|
||||
makeDisk("ssd-0", "r0", "ssd", 0),
|
||||
makeDisk("hdd-0", "r1", "", 0),
|
||||
makeDisk("hdd-1", "r2", "", 0),
|
||||
makeDisk("ssd-1", "r3", "ssd", 0),
|
||||
}
|
||||
|
||||
result, err := SelectDestinations(disks, newRequest(3, ""))
|
||||
if err != nil {
|
||||
t.Fatalf("SelectDestinations: %v", err)
|
||||
}
|
||||
if got := len(result.SelectedDisks); got != 3 {
|
||||
t.Fatalf("selected %d disks, want 3", got)
|
||||
}
|
||||
if result.SpilledToOtherDiskType {
|
||||
t.Fatalf("SpilledToOtherDiskType should never be set when PreferredDiskType is empty")
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package super_block
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
)
|
||||
|
||||
type ReplicaPlacement struct {
|
||||
@@ -77,3 +79,27 @@ func (rp *ReplicaPlacement) String() string {
|
||||
func (rp *ReplicaPlacement) GetCopyCount() int {
|
||||
return rp.DiffDataCenterCount + rp.DiffRackCount + rp.SameRackCount + 1
|
||||
}
|
||||
|
||||
// ResolveReplicaPlacement picks the EC shard replica placement constraint: an
|
||||
// explicit spec wins; otherwise the cluster default (typically the master's
|
||||
// configured default replication). A missing, invalid, or zero-replication value
|
||||
// yields nil, meaning even spread / no constraint. Shared by EC encode, repair,
|
||||
// and balance so the three resolve replica placement identically.
|
||||
func ResolveReplicaPlacement(explicitSpec, clusterDefault string) *ReplicaPlacement {
|
||||
spec := explicitSpec
|
||||
if spec == "" {
|
||||
spec = clusterDefault
|
||||
}
|
||||
if spec == "" {
|
||||
return nil
|
||||
}
|
||||
rp, err := NewReplicaPlacementFromString(spec)
|
||||
if err != nil {
|
||||
glog.Warningf("ignoring invalid replica placement %q: %v", spec, err)
|
||||
return nil
|
||||
}
|
||||
if !rp.HasReplication() {
|
||||
return nil
|
||||
}
|
||||
return rp
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
var (
|
||||
MAJOR_VERSION = int32(4)
|
||||
MINOR_VERSION = int32(27)
|
||||
MINOR_VERSION = int32(28)
|
||||
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
|
||||
VERSION = util.SizeLimit + " " + VERSION_NUMBER
|
||||
COMMIT = ""
|
||||
|
||||
@@ -242,22 +242,11 @@ func resolveECRatio(_ *types.ClusterInfo, _ string) (int, int) {
|
||||
// replication (matching the shell ec.balance default). A missing, invalid, or
|
||||
// zero-replication value yields nil, meaning even spread / no constraint.
|
||||
func resolveReplicaPlacement(ecConfig *Config, clusterInfo *types.ClusterInfo) *super_block.ReplicaPlacement {
|
||||
spec := ecConfig.ReplicaPlacement
|
||||
if spec == "" && clusterInfo != nil {
|
||||
spec = clusterInfo.DefaultReplicaPlacement
|
||||
clusterDefault := ""
|
||||
if clusterInfo != nil {
|
||||
clusterDefault = clusterInfo.DefaultReplicaPlacement
|
||||
}
|
||||
if spec == "" {
|
||||
return nil
|
||||
}
|
||||
rp, err := super_block.NewReplicaPlacementFromString(spec)
|
||||
if err != nil {
|
||||
glog.Warningf("EC balance: ignoring invalid replica placement %q: %v", spec, err)
|
||||
return nil
|
||||
}
|
||||
if !rp.HasReplication() {
|
||||
return nil
|
||||
}
|
||||
return rp
|
||||
return super_block.ResolveReplicaPlacement(ecConfig.ReplicaPlacement, clusterDefault)
|
||||
}
|
||||
|
||||
func normalizeECShardCounts(dataShards, parityShards int) (int, int) {
|
||||
|
||||
@@ -17,6 +17,7 @@ type Config struct {
|
||||
CollectionFilter string `json:"collection_filter"`
|
||||
MinSizeMB int `json:"min_size_mb"`
|
||||
PreferredTags []string `json:"preferred_tags"`
|
||||
ReplicaPlacement string `json:"replica_placement"` // e.g. "020"; empty falls back to the master default replication
|
||||
}
|
||||
|
||||
// NewDefaultConfig creates a new default erasure coding configuration
|
||||
@@ -157,6 +158,19 @@ func GetConfigSpec() base.ConfigSpec {
|
||||
InputType: "text",
|
||||
CSSClasses: "form-control",
|
||||
},
|
||||
{
|
||||
Name: "replica_placement",
|
||||
JSONName: "replica_placement",
|
||||
Type: config.FieldTypeString,
|
||||
DefaultValue: "",
|
||||
Required: false,
|
||||
DisplayName: "Replica Placement",
|
||||
Description: "EC shard replica placement constraint (e.g. 020)",
|
||||
HelpText: "Leave empty to use the master default replication. When set, the 2nd/3rd digits cap EC shards per rack and per node (best-effort during encode: relaxed rather than failing if the cluster can't satisfy them, then enforced by rebalancing). The 1st (data-center) digit is ignored for EC placement",
|
||||
Placeholder: "020",
|
||||
InputType: "text",
|
||||
CSSClasses: "form-control",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -177,6 +191,7 @@ func (c *Config) ToTaskPolicy() *worker_pb.TaskPolicy {
|
||||
MinVolumeSizeMb: int32(c.MinSizeMB),
|
||||
CollectionFilter: c.CollectionFilter,
|
||||
PreferredTags: preferredTagsCopy,
|
||||
ReplicaPlacement: c.ReplicaPlacement,
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -200,6 +215,7 @@ func (c *Config) FromTaskPolicy(policy *worker_pb.TaskPolicy) error {
|
||||
c.MinSizeMB = int(ecConfig.MinVolumeSizeMb)
|
||||
c.CollectionFilter = ecConfig.CollectionFilter
|
||||
c.PreferredTags = append([]string(nil), ecConfig.PreferredTags...)
|
||||
c.ReplicaPlacement = ecConfig.ReplicaPlacement
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -14,8 +14,8 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding/placement"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding/ecbalancer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/wildcard"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/base"
|
||||
workerutil "github.com/seaweedfs/seaweedfs/weed/worker/tasks/util"
|
||||
@@ -56,7 +56,17 @@ func Detection(ctx context.Context, metrics []*types.VolumeHealthMetrics, cluste
|
||||
skippedTooFewNodes := 0
|
||||
consecutivePlanningFailures := 0
|
||||
|
||||
var planner *ecPlacementPlanner
|
||||
// EC shard replica placement: explicit config wins, else the master default.
|
||||
var replicaPlacement *super_block.ReplicaPlacement
|
||||
if clusterInfo != nil {
|
||||
replicaPlacement = super_block.ResolveReplicaPlacement(ecConfig.ReplicaPlacement, clusterInfo.DefaultReplicaPlacement)
|
||||
}
|
||||
// EC placement honors only the rack/node digits; the data-center digit can't
|
||||
// express a useful per-DC EC shard cap (it maxes at 2). Warn once per cycle so a
|
||||
// 1xx/2xx setting isn't silently ineffective.
|
||||
if replicaPlacement != nil && replicaPlacement.DiffDataCenterCount > 0 {
|
||||
glog.Warningf("EC Detection: replica placement data-center digit (%d) is ignored for EC; only rack/node digits are honored", replicaPlacement.DiffDataCenterCount)
|
||||
}
|
||||
|
||||
allowedCollections := wildcard.CompileWildcardMatchers(ecConfig.CollectionFilter)
|
||||
|
||||
@@ -219,12 +229,9 @@ func Detection(ctx context.Context, metrics []*types.VolumeHealthMetrics, cluste
|
||||
}
|
||||
|
||||
glog.Infof("EC Detection: ActiveTopology available, planning destinations for volume %d", metric.VolumeID)
|
||||
if planner == nil {
|
||||
planner = newECPlacementPlanner(clusterInfo.ActiveTopology, ecConfig.PreferredTags)
|
||||
}
|
||||
dataShards := erasure_coding.DataShardsCount
|
||||
parityShards := erasure_coding.ParityShardsCount
|
||||
multiPlan, err := planECDestinations(planner, metric, ecConfig, dataShards, parityShards)
|
||||
multiPlan, shardsPerPlan, err := planECDestinations(clusterInfo.ActiveTopology, metric, ecConfig, replicaPlacement, dataShards, parityShards)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("Failed to plan EC destinations for volume %d: %v", metric.VolumeID, err)
|
||||
consecutivePlanningFailures++
|
||||
@@ -304,14 +311,13 @@ func Detection(ctx context.Context, metrics []*types.VolumeHealthMetrics, cluste
|
||||
glog.V(2).Infof("Found %d volume replicas and %d existing EC shards for volume %d (total %d cleanup sources)",
|
||||
len(replicaLocations), len(existingECShards), metric.VolumeID, len(sources))
|
||||
|
||||
// Convert shard destinations to TaskDestinationSpec. With fewer
|
||||
// disks than shards a destination holds several shards, so reserve
|
||||
// capacity for the actual per-disk shard count (round-robin matches
|
||||
// createECTargets) rather than assuming one shard each.
|
||||
// Convert shard destinations to TaskDestinationSpec. A destination may
|
||||
// hold several shards (small clusters), so reserve capacity for the
|
||||
// actual per-disk shard count that Place assigned (shardsPerPlan),
|
||||
// which is exactly what createECTargets writes.
|
||||
destinations := make([]topology.TaskDestinationSpec, len(shardDestinations))
|
||||
shardsPerDest := distributeECShards(dataShards+parityShards, len(shardDestinations))
|
||||
for i, dest := range shardDestinations {
|
||||
shardCount := len(shardsPerDest[i])
|
||||
shardCount := len(shardsPerPlan[i])
|
||||
shardImpact := topology.CalculateECShardStorageImpact(int32(shardCount), int64(expectedShardSize))
|
||||
destSize := int64(expectedShardSize) * int64(shardCount)
|
||||
destinations[i] = topology.TaskDestinationSpec{
|
||||
@@ -342,9 +348,9 @@ func Detection(ctx context.Context, metrics []*types.VolumeHealthMetrics, cluste
|
||||
continue // Skip this volume if topology task addition fails
|
||||
}
|
||||
|
||||
if planner != nil {
|
||||
planner.applyTaskReservations(int64(metric.Size), sources, destinations)
|
||||
}
|
||||
// Cross-volume in-cycle capacity is tracked by ActiveTopology via the
|
||||
// pending task above, which the next volume's FromActiveTopology snapshot
|
||||
// reflects; no separate planner reservation is needed.
|
||||
|
||||
glog.V(2).Infof("Added pending EC shard task %s to ActiveTopology for volume %d with %d cleanup sources and %d shard destinations",
|
||||
taskID, metric.VolumeID, len(sources), len(multiPlan.Plans))
|
||||
@@ -360,7 +366,7 @@ func Detection(ctx context.Context, metrics []*types.VolumeHealthMetrics, cluste
|
||||
Sources: sourcesProto,
|
||||
|
||||
// Unified targets - all EC shard destinations
|
||||
Targets: createECTargets(multiPlan, dataShards, parityShards),
|
||||
Targets: createECTargets(multiPlan, shardsPerPlan),
|
||||
|
||||
TaskParams: &worker_pb.TaskParams_ErasureCodingParams{
|
||||
ErasureCodingParams: createECTaskParams(dataShards, parityShards, metric.DiskType),
|
||||
@@ -413,273 +419,6 @@ func Detection(ctx context.Context, metrics []*types.VolumeHealthMetrics, cluste
|
||||
return results, hasMore, nil
|
||||
}
|
||||
|
||||
type ecDiskState struct {
|
||||
baseAvailable int64
|
||||
reservedVolumes int32
|
||||
reservedShardSlots int32
|
||||
}
|
||||
|
||||
type ecPlacementPlanner struct {
|
||||
activeTopology *topology.ActiveTopology
|
||||
candidates []*placement.DiskCandidate
|
||||
candidateByKey map[string]*placement.DiskCandidate
|
||||
diskStates map[string]*ecDiskState
|
||||
diskTags map[string][]string
|
||||
preferredTags []string
|
||||
}
|
||||
|
||||
func newECPlacementPlanner(activeTopology *topology.ActiveTopology, preferredTags []string) *ecPlacementPlanner {
|
||||
if activeTopology == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
disks := activeTopology.GetDisksWithEffectiveCapacity(topology.TaskTypeErasureCoding, "", 0)
|
||||
candidates := diskInfosToCandidates(disks)
|
||||
tagsByKey := collectDiskTags(disks)
|
||||
normalizedPreferredTags := util.NormalizeTagList(preferredTags)
|
||||
if len(candidates) == 0 {
|
||||
return &ecPlacementPlanner{
|
||||
activeTopology: activeTopology,
|
||||
candidates: candidates,
|
||||
candidateByKey: map[string]*placement.DiskCandidate{},
|
||||
diskStates: map[string]*ecDiskState{},
|
||||
diskTags: tagsByKey,
|
||||
preferredTags: normalizedPreferredTags,
|
||||
}
|
||||
}
|
||||
|
||||
candidateByKey := make(map[string]*placement.DiskCandidate, len(candidates))
|
||||
diskStates := make(map[string]*ecDiskState, len(candidates))
|
||||
for _, candidate := range candidates {
|
||||
key := ecDiskKey(candidate.NodeID, candidate.DiskID)
|
||||
candidateByKey[key] = candidate
|
||||
diskStates[key] = &ecDiskState{
|
||||
baseAvailable: int64(candidate.FreeSlots),
|
||||
}
|
||||
}
|
||||
|
||||
return &ecPlacementPlanner{
|
||||
activeTopology: activeTopology,
|
||||
candidates: candidates,
|
||||
candidateByKey: candidateByKey,
|
||||
diskStates: diskStates,
|
||||
diskTags: tagsByKey,
|
||||
preferredTags: normalizedPreferredTags,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *ecPlacementPlanner) selectDestinations(sourceRack, sourceDC, sourceDiskType string, shardsNeeded int) ([]*placement.DiskCandidate, error) {
|
||||
if p == nil || p.activeTopology == nil {
|
||||
return nil, fmt.Errorf("ec placement planner is not initialized")
|
||||
}
|
||||
if shardsNeeded <= 0 {
|
||||
return nil, fmt.Errorf("invalid shardsNeeded %d", shardsNeeded)
|
||||
}
|
||||
|
||||
config := placement.PlacementRequest{
|
||||
ShardsNeeded: shardsNeeded,
|
||||
MaxShardsPerServer: 0,
|
||||
MaxShardsPerRack: 0,
|
||||
MaxTaskLoad: topology.MaxTaskLoadForECPlacement,
|
||||
PreferDifferentServers: true,
|
||||
PreferDifferentRacks: true,
|
||||
// Bias placement toward disks matching the source volume's disk
|
||||
// type; placement spills to other types only if the preferred
|
||||
// pool can't satisfy ShardsNeeded (#9423).
|
||||
PreferredDiskType: sourceDiskType,
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
for _, candidates := range p.buildCandidateSets(shardsNeeded) {
|
||||
if len(candidates) == 0 {
|
||||
continue
|
||||
}
|
||||
result, err := placement.SelectDestinations(candidates, config)
|
||||
if err == nil {
|
||||
if result.SpilledToOtherDiskType {
|
||||
glog.Warningf("EC placement spilled to disks outside preferred disk type %q to reach %d shards (source rack=%s dc=%s)",
|
||||
sourceDiskType, shardsNeeded, sourceRack, sourceDC)
|
||||
}
|
||||
return result.SelectedDisks, nil
|
||||
}
|
||||
lastErr = err
|
||||
}
|
||||
if lastErr == nil {
|
||||
lastErr = fmt.Errorf("no EC placement candidates available")
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
func (p *ecPlacementPlanner) applyTaskReservations(volumeSize int64, sources []topology.TaskSourceSpec, destinations []topology.TaskDestinationSpec) {
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
|
||||
touched := make(map[string]bool)
|
||||
|
||||
for _, source := range sources {
|
||||
impact := p.sourceImpact(source, volumeSize)
|
||||
p.applyImpact(source.ServerID, source.DiskID, impact)
|
||||
p.bumpShardCount(source.ServerID, source.DiskID, impact.ShardSlots)
|
||||
key := ecDiskKey(source.ServerID, source.DiskID)
|
||||
if !touched[key] {
|
||||
p.bumpLoad(source.ServerID, source.DiskID)
|
||||
touched[key] = true
|
||||
}
|
||||
}
|
||||
|
||||
for _, dest := range destinations {
|
||||
impact := p.destinationImpact(dest, volumeSize)
|
||||
p.applyImpact(dest.ServerID, dest.DiskID, impact)
|
||||
p.bumpShardCount(dest.ServerID, dest.DiskID, impact.ShardSlots)
|
||||
key := ecDiskKey(dest.ServerID, dest.DiskID)
|
||||
if !touched[key] {
|
||||
p.bumpLoad(dest.ServerID, dest.DiskID)
|
||||
touched[key] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *ecPlacementPlanner) sourceImpact(source topology.TaskSourceSpec, volumeSize int64) topology.StorageSlotChange {
|
||||
if source.StorageImpact != nil {
|
||||
return *source.StorageImpact
|
||||
}
|
||||
if source.CleanupType == topology.CleanupECShards {
|
||||
return topology.CalculateECShardCleanupImpact(volumeSize)
|
||||
}
|
||||
impact, _ := topology.CalculateTaskStorageImpact(topology.TaskTypeErasureCoding, volumeSize)
|
||||
return impact
|
||||
}
|
||||
|
||||
func (p *ecPlacementPlanner) destinationImpact(dest topology.TaskDestinationSpec, volumeSize int64) topology.StorageSlotChange {
|
||||
if dest.StorageImpact != nil {
|
||||
return *dest.StorageImpact
|
||||
}
|
||||
_, impact := topology.CalculateTaskStorageImpact(topology.TaskTypeErasureCoding, volumeSize)
|
||||
return impact
|
||||
}
|
||||
|
||||
func (p *ecPlacementPlanner) applyImpact(nodeID string, diskID uint32, impact topology.StorageSlotChange) {
|
||||
if impact.IsZero() {
|
||||
return
|
||||
}
|
||||
key := ecDiskKey(nodeID, diskID)
|
||||
state, ok := p.diskStates[key]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
state.reservedVolumes += impact.VolumeSlots
|
||||
state.reservedShardSlots += impact.ShardSlots
|
||||
|
||||
available := state.baseAvailable - int64(state.reservedVolumes) - int64(state.reservedShardSlots)/int64(topology.ShardsPerVolumeSlot)
|
||||
if available < 0 {
|
||||
available = 0
|
||||
}
|
||||
|
||||
if candidate, ok := p.candidateByKey[key]; ok {
|
||||
candidate.FreeSlots = int(available)
|
||||
candidate.VolumeCount = candidate.MaxVolumeCount - available
|
||||
}
|
||||
}
|
||||
|
||||
func (p *ecPlacementPlanner) bumpLoad(nodeID string, diskID uint32) {
|
||||
key := ecDiskKey(nodeID, diskID)
|
||||
if candidate, ok := p.candidateByKey[key]; ok {
|
||||
candidate.LoadCount++
|
||||
}
|
||||
}
|
||||
|
||||
func (p *ecPlacementPlanner) bumpShardCount(nodeID string, diskID uint32, delta int32) {
|
||||
if delta == 0 {
|
||||
return
|
||||
}
|
||||
key := ecDiskKey(nodeID, diskID)
|
||||
if candidate, ok := p.candidateByKey[key]; ok {
|
||||
candidate.ShardCount += int(delta)
|
||||
if candidate.ShardCount < 0 {
|
||||
candidate.ShardCount = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ecDiskKey(nodeID string, diskID uint32) string {
|
||||
return fmt.Sprintf("%s:%d", nodeID, diskID)
|
||||
}
|
||||
|
||||
func collectDiskTags(disks []*topology.DiskInfo) map[string][]string {
|
||||
tagMap := make(map[string][]string, len(disks))
|
||||
for _, disk := range disks {
|
||||
if disk == nil || disk.DiskInfo == nil {
|
||||
continue
|
||||
}
|
||||
key := ecDiskKey(disk.NodeID, disk.DiskID)
|
||||
tags := util.NormalizeTagList(disk.DiskInfo.Tags)
|
||||
if len(tags) > 0 {
|
||||
tagMap[key] = tags
|
||||
}
|
||||
}
|
||||
return tagMap
|
||||
}
|
||||
|
||||
func diskHasTag(tags []string, tag string) bool {
|
||||
if tag == "" || len(tags) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, candidate := range tags {
|
||||
if candidate == tag {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// buildCandidateSets builds tiered candidate sets for preferred-tag prioritized placement.
|
||||
// For a planner with preferredTags, it accumulates disks matching each tag in order into
|
||||
// progressively larger tiers. It emits a candidate set once a tier reaches shardsNeeded,
|
||||
// then continues accumulating for subsequent tags. Finally, it falls back to the full
|
||||
// p.candidates set if preferred-tag tiers are insufficient. This ensures tagged disks
|
||||
// are selected first before falling back to all available candidates.
|
||||
func (p *ecPlacementPlanner) buildCandidateSets(shardsNeeded int) [][]*placement.DiskCandidate {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
if len(p.preferredTags) == 0 {
|
||||
return [][]*placement.DiskCandidate{p.candidates}
|
||||
}
|
||||
selected := make(map[string]bool, len(p.candidates))
|
||||
var tier []*placement.DiskCandidate
|
||||
var candidateSets [][]*placement.DiskCandidate
|
||||
for _, tag := range p.preferredTags {
|
||||
for _, candidate := range p.candidates {
|
||||
key := ecDiskKey(candidate.NodeID, candidate.DiskID)
|
||||
if selected[key] {
|
||||
continue
|
||||
}
|
||||
if diskHasTag(p.diskTags[key], tag) {
|
||||
selected[key] = true
|
||||
tier = append(tier, candidate)
|
||||
}
|
||||
}
|
||||
if shardsNeeded > 0 && len(tier) >= shardsNeeded {
|
||||
candidateSets = append(candidateSets, append([]*placement.DiskCandidate(nil), tier...))
|
||||
}
|
||||
}
|
||||
// Defensive check: selectDestinations always ensures shardsNeeded > 0 before calling
|
||||
// buildCandidateSets, but this branch handles direct callers and edge cases.
|
||||
if shardsNeeded <= 0 && len(tier) > 0 {
|
||||
candidateSets = append(candidateSets, append([]*placement.DiskCandidate(nil), tier...))
|
||||
}
|
||||
if len(tier) < len(p.candidates) {
|
||||
candidateSets = append(candidateSets, p.candidates)
|
||||
} else if len(candidateSets) == 0 {
|
||||
candidateSets = append(candidateSets, p.candidates)
|
||||
}
|
||||
return candidateSets
|
||||
}
|
||||
|
||||
// planECDestinations plans the destinations for erasure coding operation.
|
||||
// dataShards/parityShards are parameters so callers can drive non-10+4 ratios.
|
||||
// countTopologyNodes counts volume-server nodes in the active topology, used by
|
||||
// the min-node safety gate.
|
||||
func countTopologyNodes(at *topology.ActiveTopology) int {
|
||||
@@ -699,12 +438,20 @@ func countTopologyNodes(at *topology.ActiveTopology) int {
|
||||
return n
|
||||
}
|
||||
|
||||
func planECDestinations(planner *ecPlacementPlanner, metric *types.VolumeHealthMetrics, ecConfig *Config, dataShards, parityShards int) (*topology.MultiDestinationPlan, error) {
|
||||
if planner == nil || planner.activeTopology == nil {
|
||||
return nil, fmt.Errorf("active topology not available for EC placement")
|
||||
// planECDestinations places all shards of the volume via the shared ecbalancer
|
||||
// policy and returns the per-disk destination plans plus, parallel to them, the
|
||||
// shard ids ecbalancer.Place assigned to each disk (so createECTargets and the
|
||||
// capacity reservations use the real assignment, not a round-robin guess).
|
||||
//
|
||||
// Encode is lenient (PlaceDurabilityFirst): it relaxes caps/anti-affinity/RP as
|
||||
// needed rather than fail, and prefers the source disk type but spills if that
|
||||
// type can't hold every shard. rp is the resolved replica placement (may be nil).
|
||||
func planECDestinations(at *topology.ActiveTopology, metric *types.VolumeHealthMetrics, ecConfig *Config, rp *super_block.ReplicaPlacement, dataShards, parityShards int) (*topology.MultiDestinationPlan, [][]uint32, error) {
|
||||
if at == nil {
|
||||
return nil, nil, fmt.Errorf("active topology not available for EC placement")
|
||||
}
|
||||
if dataShards <= 0 || parityShards <= 0 {
|
||||
return nil, fmt.Errorf("invalid EC ratio: dataShards=%d parityShards=%d", dataShards, parityShards)
|
||||
return nil, nil, fmt.Errorf("invalid EC ratio: dataShards=%d parityShards=%d", dataShards, parityShards)
|
||||
}
|
||||
totalShards := dataShards + parityShards
|
||||
// Survive losing one disk: each disk holds at most parityShards shards,
|
||||
@@ -712,159 +459,121 @@ func planECDestinations(planner *ecPlacementPlanner, metric *types.VolumeHealthM
|
||||
minTotalDisks := (totalShards + parityShards - 1) / parityShards
|
||||
expectedShardSize := uint64(metric.Size) / uint64(dataShards)
|
||||
|
||||
// Get source node information from topology
|
||||
var sourceRack, sourceDC string
|
||||
|
||||
// Extract rack and DC from topology info
|
||||
topologyInfo := planner.activeTopology.GetTopologyInfo()
|
||||
if topologyInfo != nil {
|
||||
for _, dc := range topologyInfo.DataCenterInfos {
|
||||
for _, rack := range dc.RackInfos {
|
||||
for _, dataNodeInfo := range rack.DataNodeInfos {
|
||||
if dataNodeInfo.Id == metric.Server {
|
||||
sourceDC = dc.Id
|
||||
sourceRack = rack.Id
|
||||
break
|
||||
}
|
||||
}
|
||||
if sourceRack != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
if sourceDC != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
snap := ecbalancer.FromActiveTopology(at, dataShards)
|
||||
// Encode is greenfield: any EC shards already present for this volume are stale
|
||||
// leftovers from a prior failed attempt, which the task deletes
|
||||
// (cleanupStaleEcShards) before distributing the new shards. Release them so they
|
||||
// don't occupy capacity or skew anti-affinity / per-disk caps during planning.
|
||||
snap.ReleaseVolumeShards(metric.Collection, metric.VolumeID)
|
||||
need := make([]int, totalShards)
|
||||
for i := range need {
|
||||
need[i] = i
|
||||
}
|
||||
|
||||
// Select best disks for EC placement with rack/DC diversity using the cached planner.
|
||||
// Pass source disk type so placement prefers matching-type disks (#9423).
|
||||
selectedDisks, err := planner.selectDestinations(sourceRack, sourceDC, metric.DiskType, totalShards)
|
||||
res, err := snap.Place(metric.VolumeID, metric.Collection, need, ecbalancer.Constraints{
|
||||
DiskType: metric.DiskType,
|
||||
DiskTypePolicy: ecbalancer.DiskTypePrefer,
|
||||
PreferredTags: ecConfig.PreferredTags,
|
||||
ReplicaPlacement: rp,
|
||||
Ratio: func(string) (int, int) { return dataShards, parityShards },
|
||||
}, ecbalancer.PlaceDurabilityFirst)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(selectedDisks) < minTotalDisks {
|
||||
return nil, fmt.Errorf("found %d disks, but EC %d+%d needs at least %d disks so no disk holds more than %d shards",
|
||||
len(selectedDisks), dataShards, parityShards, minTotalDisks, parityShards)
|
||||
if res.SpilledToOtherDiskType {
|
||||
glog.Warningf("EC volume %d: placed shards outside preferred disk type %q", metric.VolumeID, metric.DiskType)
|
||||
}
|
||||
// Fewer than totalShards disks is fine: createECTargets round-robins the
|
||||
// shards across the available disks, packing several distinct shards onto a
|
||||
// disk when needed (matching ec.encode's "spread as 4,4,3,3" fallback for
|
||||
// small clusters). A disk holding several shards of one volume is safe —
|
||||
// each is a separate .ecNN file and ReceiveFile keys by that extension. The
|
||||
// minTotalDisks floor above keeps any single disk under parityShards shards,
|
||||
// so the volume still survives losing any one disk.
|
||||
if len(selectedDisks) < totalShards {
|
||||
glog.V(1).Infof("EC volume %d: only %d disks for %d shards, packing up to %d shards per disk",
|
||||
metric.VolumeID, len(selectedDisks), totalShards, (totalShards+len(selectedDisks)-1)/len(selectedDisks))
|
||||
if res.SpilledOutsidePreferredTags {
|
||||
glog.Warningf("EC volume %d: placed shards outside preferred tags %v", metric.VolumeID, ecConfig.PreferredTags)
|
||||
}
|
||||
if len(res.Relaxed) > 0 {
|
||||
// Encode is best-effort (PlaceDurabilityFirst): it relaxes these constraints
|
||||
// rather than defer when the cluster can't satisfy them. Surface it so a tight
|
||||
// replica placement isn't silently weakened; rebalancing tightens the spread.
|
||||
glog.Warningf("EC volume %d: placed with relaxed constraints %v; replica placement not fully satisfied (rebalancing will adjust)", metric.VolumeID, res.Relaxed)
|
||||
}
|
||||
|
||||
// Group the per-shard destinations into one plan per (node,disk), iterating
|
||||
// shard ids in order for determinism.
|
||||
type diskGroup struct {
|
||||
node, rack, dc string
|
||||
diskID uint32
|
||||
shards []uint32
|
||||
}
|
||||
type diskKey struct {
|
||||
node string
|
||||
diskID uint32
|
||||
}
|
||||
groups := make(map[diskKey]*diskGroup, totalShards)
|
||||
order := make([]diskKey, 0, totalShards)
|
||||
for sid := 0; sid < totalShards; sid++ {
|
||||
d, ok := res.Destinations[sid]
|
||||
if !ok {
|
||||
return nil, nil, fmt.Errorf("EC volume %d: shard %d was not placed", metric.VolumeID, sid)
|
||||
}
|
||||
key := diskKey{node: d.Node, diskID: d.DiskID}
|
||||
g := groups[key]
|
||||
if g == nil {
|
||||
g = &diskGroup{node: d.Node, rack: d.Rack, dc: d.DataCenter, diskID: d.DiskID}
|
||||
groups[key] = g
|
||||
order = append(order, key)
|
||||
}
|
||||
g.shards = append(g.shards, uint32(sid))
|
||||
}
|
||||
if len(order) < minTotalDisks {
|
||||
return nil, nil, fmt.Errorf("placed onto %d disks, but EC %d+%d needs at least %d so no disk holds more than %d shards",
|
||||
len(order), dataShards, parityShards, minTotalDisks, parityShards)
|
||||
}
|
||||
|
||||
var plans []*topology.DestinationPlan
|
||||
shardsPerPlan := make([][]uint32, 0, len(order))
|
||||
rackCount := make(map[string]int)
|
||||
dcCount := make(map[string]int)
|
||||
|
||||
for _, disk := range selectedDisks {
|
||||
// Get the target server address
|
||||
targetAddress, err := workerutil.ResolveServerAddress(disk.NodeID, planner.activeTopology)
|
||||
for _, key := range order {
|
||||
g := groups[key]
|
||||
targetAddress, err := workerutil.ResolveServerAddress(g.node, at)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to resolve address for target server %s: %v", disk.NodeID, err)
|
||||
return nil, nil, fmt.Errorf("failed to resolve address for target server %s: %v", g.node, err)
|
||||
}
|
||||
|
||||
plan := &topology.DestinationPlan{
|
||||
TargetNode: disk.NodeID,
|
||||
TargetAddress: targetAddress,
|
||||
TargetDisk: disk.DiskID,
|
||||
TargetRack: disk.Rack,
|
||||
TargetDC: disk.DataCenter,
|
||||
ExpectedSize: expectedShardSize, // Set calculated EC shard size
|
||||
PlacementScore: calculateECScoreCandidate(disk, sourceRack, sourceDC),
|
||||
}
|
||||
plans = append(plans, plan)
|
||||
|
||||
// Count rack and DC diversity
|
||||
rackKey := fmt.Sprintf("%s:%s", disk.DataCenter, disk.Rack)
|
||||
rackCount[rackKey]++
|
||||
dcCount[disk.DataCenter]++
|
||||
plans = append(plans, &topology.DestinationPlan{
|
||||
TargetNode: g.node,
|
||||
TargetAddress: targetAddress,
|
||||
TargetDisk: g.diskID,
|
||||
TargetRack: g.rack,
|
||||
TargetDC: g.dc,
|
||||
ExpectedSize: expectedShardSize,
|
||||
})
|
||||
shardsPerPlan = append(shardsPerPlan, g.shards)
|
||||
rackCount[fmt.Sprintf("%s:%s", g.dc, g.rack)]++
|
||||
dcCount[g.dc]++
|
||||
}
|
||||
|
||||
// Log capacity utilization information using ActiveTopology's encapsulated logic
|
||||
totalEffectiveCapacity := int64(0)
|
||||
for _, plan := range plans {
|
||||
key := ecDiskKey(plan.TargetNode, plan.TargetDisk)
|
||||
if candidate, ok := planner.candidateByKey[key]; ok {
|
||||
totalEffectiveCapacity += int64(candidate.FreeSlots)
|
||||
}
|
||||
}
|
||||
|
||||
glog.V(1).Infof("Planned EC destinations for volume %d (size=%d bytes): expected shard size=%d bytes, %d shards across %d racks, %d DCs, total effective capacity=%d slots",
|
||||
metric.VolumeID, metric.Size, expectedShardSize, len(plans), len(rackCount), len(dcCount), totalEffectiveCapacity)
|
||||
|
||||
// Log storage impact for EC task (source only - EC has multiple targets handled individually)
|
||||
sourceChange, _ := topology.CalculateTaskStorageImpact(topology.TaskTypeErasureCoding, int64(metric.Size))
|
||||
glog.V(2).Infof("EC task capacity management: source_reserves_with_zero_impact={VolumeSlots:%d, ShardSlots:%d}, %d_targets_will_receive_shards, estimated_size=%d",
|
||||
sourceChange.VolumeSlots, sourceChange.ShardSlots, len(plans), metric.Size)
|
||||
glog.V(2).Infof("EC source reserves capacity but with zero StorageSlotChange impact")
|
||||
glog.V(1).Infof("Planned EC destinations for volume %d (size=%d bytes): expected shard size=%d bytes, %d shards across %d disks, %d racks, %d DCs",
|
||||
metric.VolumeID, metric.Size, expectedShardSize, totalShards, len(plans), len(rackCount), len(dcCount))
|
||||
|
||||
return &topology.MultiDestinationPlan{
|
||||
Plans: plans,
|
||||
TotalShards: len(plans),
|
||||
TotalShards: totalShards,
|
||||
SuccessfulRack: len(rackCount),
|
||||
SuccessfulDCs: len(dcCount),
|
||||
}, nil
|
||||
}, shardsPerPlan, nil
|
||||
}
|
||||
|
||||
// distributeECShards assigns shard ids 0..totalShards-1 across numTargets
|
||||
// targets round-robin, so each target holds either floor or ceil of
|
||||
// totalShards/numTargets shards. When numTargets < totalShards this packs
|
||||
// several shards onto a target; planECDestinations guarantees numTargets is at
|
||||
// least ceil(totalShards/parityShards), so no target exceeds parityShards shards.
|
||||
func distributeECShards(totalShards, numTargets int) [][]uint32 {
|
||||
targetShards := make([][]uint32, numTargets)
|
||||
for i := range targetShards {
|
||||
targetShards[i] = make([]uint32, 0)
|
||||
}
|
||||
for shardId := 0; shardId < totalShards; shardId++ {
|
||||
targetIndex := shardId % numTargets
|
||||
targetShards[targetIndex] = append(targetShards[targetIndex], uint32(shardId))
|
||||
}
|
||||
return targetShards
|
||||
}
|
||||
|
||||
// createECTargets builds TaskTargets, round-robining shards across the plan
|
||||
// entries. With fewer disks than shards a target receives several shard ids.
|
||||
func createECTargets(multiPlan *topology.MultiDestinationPlan, dataShards, parityShards int) []*worker_pb.TaskTarget {
|
||||
var targets []*worker_pb.TaskTarget
|
||||
numTargets := len(multiPlan.Plans)
|
||||
totalShards := dataShards + parityShards
|
||||
|
||||
targetShards := distributeECShards(totalShards, numTargets)
|
||||
|
||||
// createECTargets builds TaskTargets from the per-disk plans and the shard ids
|
||||
// ecbalancer.Place assigned to each (shardsPerPlan is parallel to multiPlan.Plans).
|
||||
func createECTargets(multiPlan *topology.MultiDestinationPlan, shardsPerPlan [][]uint32) []*worker_pb.TaskTarget {
|
||||
targets := make([]*worker_pb.TaskTarget, 0, len(multiPlan.Plans))
|
||||
for i, plan := range multiPlan.Plans {
|
||||
target := &worker_pb.TaskTarget{
|
||||
shardIDs := shardsPerPlan[i]
|
||||
targets = append(targets, &worker_pb.TaskTarget{
|
||||
Node: plan.TargetAddress,
|
||||
DiskId: plan.TargetDisk,
|
||||
Rack: plan.TargetRack,
|
||||
DataCenter: plan.TargetDC,
|
||||
ShardIds: targetShards[i],
|
||||
ShardIds: shardIDs,
|
||||
EstimatedSize: plan.ExpectedSize,
|
||||
}
|
||||
targets = append(targets, target)
|
||||
|
||||
assignedData := make([]uint32, 0)
|
||||
assignedParity := make([]uint32, 0)
|
||||
for _, shardId := range targetShards[i] {
|
||||
if int(shardId) < dataShards {
|
||||
assignedData = append(assignedData, shardId)
|
||||
} else {
|
||||
assignedParity = append(assignedParity, shardId)
|
||||
}
|
||||
}
|
||||
glog.V(2).Infof("EC planning: target %s assigned shards %v (data: %v, parity: %v)",
|
||||
plan.TargetNode, targetShards[i], assignedData, assignedParity)
|
||||
})
|
||||
glog.V(2).Infof("EC planning: target %s disk %d assigned shards %v", plan.TargetNode, plan.TargetDisk, shardIDs)
|
||||
}
|
||||
|
||||
glog.V(1).Infof("EC planning: distributed %d shards across %d targets using round-robin (data shards 0-%d, parity shards %d-%d)",
|
||||
totalShards, numTargets, dataShards-1, dataShards, totalShards-1)
|
||||
return targets
|
||||
}
|
||||
|
||||
@@ -918,68 +627,6 @@ func createECTaskParams(dataShards, parityShards int, sourceDiskType string) *wo
|
||||
}
|
||||
}
|
||||
|
||||
// diskInfosToCandidates converts topology.DiskInfo slice to placement.DiskCandidate slice
|
||||
func diskInfosToCandidates(disks []*topology.DiskInfo) []*placement.DiskCandidate {
|
||||
var candidates []*placement.DiskCandidate
|
||||
for _, disk := range disks {
|
||||
if disk.DiskInfo == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Calculate free slots (using default max if not set)
|
||||
freeSlots := int(disk.DiskInfo.MaxVolumeCount - disk.DiskInfo.VolumeCount)
|
||||
if freeSlots < 0 {
|
||||
freeSlots = 0
|
||||
}
|
||||
|
||||
// Calculate EC shard count for this specific disk
|
||||
// EcShardInfos contains all shards, so we need to filter by DiskId and sum actual shard counts
|
||||
ecShardCount := 0
|
||||
if disk.DiskInfo.EcShardInfos != nil {
|
||||
for _, shardInfo := range disk.DiskInfo.EcShardInfos {
|
||||
if shardInfo.DiskId == disk.DiskID {
|
||||
ecShardCount += erasure_coding.GetShardCount(shardInfo)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
candidates = append(candidates, &placement.DiskCandidate{
|
||||
NodeID: disk.NodeID,
|
||||
DiskID: disk.DiskID,
|
||||
DataCenter: disk.DataCenter,
|
||||
Rack: disk.Rack,
|
||||
DiskType: disk.DiskType,
|
||||
VolumeCount: disk.DiskInfo.VolumeCount,
|
||||
MaxVolumeCount: disk.DiskInfo.MaxVolumeCount,
|
||||
ShardCount: ecShardCount,
|
||||
FreeSlots: freeSlots,
|
||||
LoadCount: disk.LoadCount,
|
||||
})
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
// calculateECScoreCandidate calculates placement score for EC operations.
|
||||
// Used for logging and plan metadata.
|
||||
func calculateECScoreCandidate(disk *placement.DiskCandidate, sourceRack, sourceDC string) float64 {
|
||||
if disk == nil {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
score := 0.0
|
||||
|
||||
// Prefer disks with available capacity (primary factor)
|
||||
if disk.MaxVolumeCount > 0 {
|
||||
utilization := float64(disk.VolumeCount) / float64(disk.MaxVolumeCount)
|
||||
score += (1.0 - utilization) * 60.0 // Up to 60 points for available capacity
|
||||
}
|
||||
|
||||
// Consider current load (secondary factor)
|
||||
score += (10.0 - float64(disk.LoadCount)) // Up to 10 points for low load
|
||||
|
||||
return score
|
||||
}
|
||||
|
||||
// findVolumeReplicaLocations finds all replica locations (server + disk) for the specified volume
|
||||
// Uses O(1) indexed lookup for optimal performance on large clusters.
|
||||
func findVolumeReplicaLocations(activeTopology *topology.ActiveTopology, volumeID uint32, collection string) []topology.VolumeReplica {
|
||||
|
||||
@@ -19,9 +19,6 @@ func TestPlanECDestinationsPrefersSourceDiskType_FullCluster(t *testing.T) {
|
||||
// for a 10+4 layout with one-shard-per-(server,disk) diversity.
|
||||
activeTopology := buildActiveTopology(t, erasure_coding.TotalShardsCount, []string{"hdd", "ssd"}, 100, 0)
|
||||
|
||||
planner := newECPlacementPlanner(activeTopology, nil)
|
||||
require.NotNil(t, planner)
|
||||
|
||||
metric := &types.VolumeHealthMetrics{
|
||||
VolumeID: 1,
|
||||
Server: "10.0.0.1:8080",
|
||||
@@ -30,7 +27,7 @@ func TestPlanECDestinationsPrefersSourceDiskType_FullCluster(t *testing.T) {
|
||||
DiskType: "ssd", // the property being plumbed end-to-end
|
||||
}
|
||||
|
||||
plan, err := planECDestinations(planner, metric, NewDefaultConfig(), erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
|
||||
plan, _, err := planECDestinations(activeTopology, metric, NewDefaultConfig(), nil, erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, plan.Plans, erasure_coding.TotalShardsCount)
|
||||
|
||||
@@ -67,9 +64,6 @@ func TestPlanECDestinationsSpillsToOtherDiskType_WhenPreferredScarce(t *testing.
|
||||
}
|
||||
require.NoError(t, activeTopology.UpdateTopology(topo))
|
||||
|
||||
planner := newECPlacementPlanner(activeTopology, nil)
|
||||
require.NotNil(t, planner)
|
||||
|
||||
metric := &types.VolumeHealthMetrics{
|
||||
VolumeID: 2,
|
||||
Server: "10.0.0.1:8080",
|
||||
@@ -78,7 +72,7 @@ func TestPlanECDestinationsSpillsToOtherDiskType_WhenPreferredScarce(t *testing.
|
||||
DiskType: "ssd",
|
||||
}
|
||||
|
||||
plan, err := planECDestinations(planner, metric, NewDefaultConfig(), erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
|
||||
plan, _, err := planECDestinations(activeTopology, metric, NewDefaultConfig(), nil, erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, plan.Plans, erasure_coding.TotalShardsCount)
|
||||
|
||||
|
||||
@@ -14,41 +14,8 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestECPlacementPlannerApplyReservations(t *testing.T) {
|
||||
activeTopology := buildActiveTopology(t, 1, []string{"hdd"}, 10, 0)
|
||||
|
||||
planner := newECPlacementPlanner(activeTopology, nil)
|
||||
require.NotNil(t, planner)
|
||||
|
||||
key := ecDiskKey("10.0.0.1:8080", 0)
|
||||
candidate, ok := planner.candidateByKey[key]
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, 10, candidate.FreeSlots)
|
||||
assert.Equal(t, 0, candidate.ShardCount)
|
||||
assert.Equal(t, 0, candidate.LoadCount)
|
||||
|
||||
shardImpact := topology.CalculateECShardStorageImpact(1, 1)
|
||||
destinations := make([]topology.TaskDestinationSpec, 10)
|
||||
for i := 0; i < 10; i++ {
|
||||
destinations[i] = topology.TaskDestinationSpec{
|
||||
ServerID: "10.0.0.1:8080",
|
||||
DiskID: 0,
|
||||
StorageImpact: &shardImpact,
|
||||
}
|
||||
}
|
||||
|
||||
planner.applyTaskReservations(1024, nil, destinations)
|
||||
|
||||
candidate = planner.candidateByKey[key]
|
||||
assert.Equal(t, 9, candidate.FreeSlots, "10 shard slots should reduce available volume slots by 1")
|
||||
assert.Equal(t, 10, candidate.ShardCount)
|
||||
assert.Equal(t, 1, candidate.LoadCount, "load should only be incremented once per disk")
|
||||
}
|
||||
|
||||
func TestPlanECDestinationsUsesPlanner(t *testing.T) {
|
||||
activeTopology := buildActiveTopology(t, 7, []string{"hdd", "ssd"}, 100, 0)
|
||||
planner := newECPlacementPlanner(activeTopology, nil)
|
||||
require.NotNil(t, planner)
|
||||
|
||||
metric := &types.VolumeHealthMetrics{
|
||||
VolumeID: 1,
|
||||
@@ -57,74 +24,10 @@ func TestPlanECDestinationsUsesPlanner(t *testing.T) {
|
||||
Collection: "",
|
||||
}
|
||||
|
||||
plan, err := planECDestinations(planner, metric, NewDefaultConfig(), erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
|
||||
plan, shardsPerPlan, err := planECDestinations(activeTopology, metric, NewDefaultConfig(), nil, erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, plan)
|
||||
assert.Equal(t, erasure_coding.TotalShardsCount, len(plan.Plans))
|
||||
}
|
||||
|
||||
func TestECPlacementPlannerPrefersTaggedDisks(t *testing.T) {
|
||||
activeTopology := buildActiveTopology(t, 3, []string{"hdd"}, 10, 0)
|
||||
topo := activeTopology.GetTopologyInfo()
|
||||
for _, dc := range topo.DataCenterInfos {
|
||||
for _, rack := range dc.RackInfos {
|
||||
for k, node := range rack.DataNodeInfos {
|
||||
for diskType := range node.DiskInfos {
|
||||
if k < 2 {
|
||||
node.DiskInfos[diskType].Tags = []string{"fast"}
|
||||
} else {
|
||||
node.DiskInfos[diskType].Tags = []string{"slow"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
require.NoError(t, activeTopology.UpdateTopology(topo))
|
||||
|
||||
planner := newECPlacementPlanner(activeTopology, []string{"fast"})
|
||||
require.NotNil(t, planner)
|
||||
|
||||
selected, err := planner.selectDestinations("", "", "", 2)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, selected, 2)
|
||||
|
||||
for _, candidate := range selected {
|
||||
key := ecDiskKey(candidate.NodeID, candidate.DiskID)
|
||||
assert.True(t, diskHasTag(planner.diskTags[key], "fast"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestECPlacementPlannerFallsBackWhenTagsInsufficient(t *testing.T) {
|
||||
activeTopology := buildActiveTopology(t, 3, []string{"hdd"}, 10, 0)
|
||||
topo := activeTopology.GetTopologyInfo()
|
||||
for _, dc := range topo.DataCenterInfos {
|
||||
for _, rack := range dc.RackInfos {
|
||||
for i, node := range rack.DataNodeInfos {
|
||||
for diskType := range node.DiskInfos {
|
||||
if i == 0 {
|
||||
node.DiskInfos[diskType].Tags = []string{"fast"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
require.NoError(t, activeTopology.UpdateTopology(topo))
|
||||
|
||||
planner := newECPlacementPlanner(activeTopology, []string{"fast"})
|
||||
require.NotNil(t, planner)
|
||||
|
||||
selected, err := planner.selectDestinations("", "", "", 3)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, selected, 3)
|
||||
|
||||
taggedCount := 0
|
||||
for _, candidate := range selected {
|
||||
key := ecDiskKey(candidate.NodeID, candidate.DiskID)
|
||||
if diskHasTag(planner.diskTags[key], "fast") {
|
||||
taggedCount++
|
||||
}
|
||||
}
|
||||
assert.Less(t, taggedCount, len(selected))
|
||||
requireAllShardsPlaced(t, plan, shardsPerPlan)
|
||||
}
|
||||
|
||||
// TestDetectionSkipsWhenECShardsAlreadyExist guards against issue #9448: a
|
||||
@@ -363,9 +266,6 @@ func TestPlanECDestinationsSpreadsAcrossPhysicalDisks(t *testing.T) {
|
||||
}},
|
||||
}))
|
||||
|
||||
planner := newECPlacementPlanner(activeTopology, nil)
|
||||
require.NotNil(t, planner)
|
||||
|
||||
metric := &types.VolumeHealthMetrics{
|
||||
VolumeID: 42,
|
||||
Server: "127.0.0.1:8081",
|
||||
@@ -373,23 +273,14 @@ func TestPlanECDestinationsSpreadsAcrossPhysicalDisks(t *testing.T) {
|
||||
Collection: "",
|
||||
}
|
||||
|
||||
plan, err := planECDestinations(planner, metric, NewDefaultConfig(), erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
|
||||
plan, shardsPerPlan, err := planECDestinations(activeTopology, metric, NewDefaultConfig(), nil, erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, plan)
|
||||
require.Equal(t, erasure_coding.TotalShardsCount, len(plan.Plans))
|
||||
|
||||
seen := make(map[string]bool, len(plan.Plans))
|
||||
for _, p := range plan.Plans {
|
||||
key := fmt.Sprintf("%s:%d", p.TargetNode, p.TargetDisk)
|
||||
assert.False(t, seen[key], "duplicate (server,disk_id) target %s", key)
|
||||
seen[key] = true
|
||||
}
|
||||
requireAllShardsPlaced(t, plan, shardsPerPlan)
|
||||
}
|
||||
|
||||
func TestPlanECDestinationsFailsWithInsufficientCapacity(t *testing.T) {
|
||||
activeTopology := buildActiveTopology(t, 1, []string{"hdd"}, 1, 1)
|
||||
planner := newECPlacementPlanner(activeTopology, nil)
|
||||
require.NotNil(t, planner)
|
||||
|
||||
metric := &types.VolumeHealthMetrics{
|
||||
VolumeID: 2,
|
||||
@@ -398,7 +289,7 @@ func TestPlanECDestinationsFailsWithInsufficientCapacity(t *testing.T) {
|
||||
Collection: "",
|
||||
}
|
||||
|
||||
_, err := planECDestinations(planner, metric, NewDefaultConfig(), erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
|
||||
_, _, err := planECDestinations(activeTopology, metric, NewDefaultConfig(), nil, erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
@@ -440,9 +331,6 @@ func TestPlanECDestinationsPacksWhenFewerDisksThanShards(t *testing.T) {
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{{Id: "dc1", RackInfos: rackInfos}},
|
||||
}))
|
||||
|
||||
planner := newECPlacementPlanner(activeTopology, nil)
|
||||
require.NotNil(t, planner)
|
||||
|
||||
metric := &types.VolumeHealthMetrics{
|
||||
VolumeID: 4569,
|
||||
Server: "192.168.1.145:8081",
|
||||
@@ -450,16 +338,18 @@ func TestPlanECDestinationsPacksWhenFewerDisksThanShards(t *testing.T) {
|
||||
Collection: "",
|
||||
}
|
||||
|
||||
plan, err := planECDestinations(planner, metric, NewDefaultConfig(), erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
|
||||
plan, shardsPerPlan, err := planECDestinations(activeTopology, metric, NewDefaultConfig(), nil, erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, plan)
|
||||
// One plan entry per available disk; fewer than the 14 shards.
|
||||
require.Equal(t, numServers, len(plan.Plans))
|
||||
// Packed onto the available disks: more than one shard per disk but never more
|
||||
// than the 8 disks, and at least the durability floor of distinct disks.
|
||||
require.LessOrEqual(t, len(plan.Plans), numServers)
|
||||
require.GreaterOrEqual(t, len(plan.Plans), (erasure_coding.TotalShardsCount+erasure_coding.ParityShardsCount-1)/erasure_coding.ParityShardsCount)
|
||||
|
||||
// createECTargets must cover all 14 shards exactly once, packing onto the
|
||||
// available disks without any disk exceeding parityShards shards.
|
||||
targets := createECTargets(plan, erasure_coding.DataShardsCount, erasure_coding.ParityShardsCount)
|
||||
require.Equal(t, numServers, len(targets))
|
||||
targets := createECTargets(plan, shardsPerPlan)
|
||||
require.Equal(t, len(plan.Plans), len(targets))
|
||||
|
||||
seenShards := make(map[uint32]bool)
|
||||
for _, target := range targets {
|
||||
@@ -473,6 +363,28 @@ func TestPlanECDestinationsPacksWhenFewerDisksThanShards(t *testing.T) {
|
||||
require.Len(t, seenShards, erasure_coding.TotalShardsCount, "every shard must be placed exactly once")
|
||||
}
|
||||
|
||||
// requireAllShardsPlaced asserts every EC shard landed exactly once, on a distinct
|
||||
// (node,disk) target, with no disk holding more than parityShards shards (so losing
|
||||
// any one disk cannot lose the volume). shardsPerPlan is parallel to plan.Plans.
|
||||
func requireAllShardsPlaced(t *testing.T, plan *topology.MultiDestinationPlan, shardsPerPlan [][]uint32) {
|
||||
t.Helper()
|
||||
require.Equal(t, len(plan.Plans), len(shardsPerPlan), "one shard list per plan entry")
|
||||
keys := make(map[string]bool, len(plan.Plans))
|
||||
seen := make(map[uint32]bool)
|
||||
for i, p := range plan.Plans {
|
||||
key := fmt.Sprintf("%s:%d", p.TargetNode, p.TargetDisk)
|
||||
require.False(t, keys[key], "duplicate (node,disk) target %s", key)
|
||||
keys[key] = true
|
||||
require.LessOrEqual(t, len(shardsPerPlan[i]), erasure_coding.ParityShardsCount,
|
||||
"disk %s holds %d shards, over parityShards", key, len(shardsPerPlan[i]))
|
||||
for _, s := range shardsPerPlan[i] {
|
||||
require.False(t, seen[s], "shard %d placed more than once", s)
|
||||
seen[s] = true
|
||||
}
|
||||
}
|
||||
require.Len(t, seen, erasure_coding.TotalShardsCount, "every shard must be placed exactly once")
|
||||
}
|
||||
|
||||
func buildVolumeMetricsForIDs(count int) []*types.VolumeHealthMetrics {
|
||||
metrics := make([]*types.VolumeHealthMetrics, 0, count)
|
||||
now := time.Now()
|
||||
|
||||
@@ -271,8 +271,17 @@ func (t *ErasureCodingTask) Validate(params *worker_pb.TaskParams) error {
|
||||
return fmt.Errorf("invalid parity shards: %d (must be >= 1)", ecParams.ParityShards)
|
||||
}
|
||||
|
||||
if len(params.Targets) < int(ecParams.DataShards+ecParams.ParityShards) {
|
||||
return fmt.Errorf("insufficient targets: got %d, need %d", len(params.Targets), ecParams.DataShards+ecParams.ParityShards)
|
||||
// Count distinct shard ids across targets, not target rows: Place packs several
|
||||
// shards onto one (node,disk) target when there are fewer disks than shards, so
|
||||
// a valid plan can have fewer target rows than total shards.
|
||||
distinctShards := make(map[uint32]struct{})
|
||||
for _, target := range params.Targets {
|
||||
for _, sid := range target.ShardIds {
|
||||
distinctShards[sid] = struct{}{}
|
||||
}
|
||||
}
|
||||
if total := int(ecParams.DataShards + ecParams.ParityShards); len(distinctShards) < total {
|
||||
return fmt.Errorf("insufficient shard targets: got %d distinct shards across %d targets, need %d", len(distinctShards), len(params.Targets), total)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -138,6 +138,14 @@ func (h *ErasureCodingHandler) Descriptor() *plugin_pb.JobTypeDescriptor {
|
||||
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_STRING,
|
||||
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_TEXT,
|
||||
},
|
||||
{
|
||||
Name: "replica_placement",
|
||||
Label: "Replica Placement",
|
||||
Description: "EC shard placement (e.g. 020): 2nd/3rd digits cap shards per rack/node (best-effort during encode, enforced by rebalancing); the data-center digit is ignored. Empty uses the master default.",
|
||||
Placeholder: "020",
|
||||
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_STRING,
|
||||
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_TEXT,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -154,6 +162,9 @@ func (h *ErasureCodingHandler) Descriptor() *plugin_pb.JobTypeDescriptor {
|
||||
"preferred_tags": {
|
||||
Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""},
|
||||
},
|
||||
"replica_placement": {
|
||||
Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""},
|
||||
},
|
||||
},
|
||||
},
|
||||
AdminRuntimeDefaults: &plugin_pb.AdminRuntimeDefaults{
|
||||
@@ -217,7 +228,11 @@ func (h *ErasureCodingHandler) Detect(
|
||||
return err
|
||||
}
|
||||
|
||||
clusterInfo := &workertypes.ClusterInfo{ActiveTopology: activeTopology, GrpcDialOption: h.grpcDialOption}
|
||||
clusterInfo := &workertypes.ClusterInfo{
|
||||
ActiveTopology: activeTopology,
|
||||
GrpcDialOption: h.grpcDialOption,
|
||||
DefaultReplicaPlacement: pluginworker.FetchDefaultReplicaPlacement(ctx, masters, h.grpcDialOption),
|
||||
}
|
||||
maxResults := int(request.MaxResults)
|
||||
if maxResults < 0 {
|
||||
maxResults = 0
|
||||
@@ -592,6 +607,8 @@ func deriveErasureCodingWorkerConfig(values map[string]*plugin_pb.ConfigValue) *
|
||||
|
||||
taskConfig.PreferredTags = util.NormalizeTagList(pluginworker.ReadStringListConfig(values, "preferred_tags"))
|
||||
|
||||
taskConfig.ReplicaPlacement = strings.TrimSpace(pluginworker.ReadStringConfig(values, "replica_placement", taskConfig.ReplicaPlacement))
|
||||
|
||||
return &erasureCodingWorkerConfig{
|
||||
TaskConfig: taskConfig,
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user