mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49d9d0c1cd | ||
|
|
6ec6cce3fe | ||
|
|
e057244b0a | ||
|
|
763e2a2090 | ||
|
|
917b6f4afd | ||
|
|
106fd31af1 | ||
|
|
137f23a229 | ||
|
|
e645449872 | ||
|
|
9b642d4636 |
No files matched your search
@@ -740,7 +740,11 @@ impl DiskLocation {
|
||||
if vol.is_read_only() {
|
||||
continue;
|
||||
}
|
||||
let dat_size = vol.dat_file_size().unwrap_or(0);
|
||||
// A preallocated volume already holds its space on disk.
|
||||
let dat_size = vol
|
||||
.dat_file_size()
|
||||
.unwrap_or(0)
|
||||
.max(vol.dat_allocated_size());
|
||||
let idx_size = vol.idx_file_size();
|
||||
let used = dat_size + idx_size;
|
||||
if volume_size_limit > used {
|
||||
|
||||
@@ -943,11 +943,7 @@ impl Store {
|
||||
let current = loc.max_volume_count.load(Ordering::Relaxed);
|
||||
let (_, free) = super::disk_location::get_disk_stats(&loc.directory);
|
||||
|
||||
let unused_space = if self.get_preallocate() {
|
||||
0
|
||||
} else {
|
||||
loc.unused_space(volume_size_limit)
|
||||
};
|
||||
let unused_space = loc.unused_space(volume_size_limit);
|
||||
let unclaimed = (free as i64) - (unused_space as i64);
|
||||
|
||||
let vol_count = loc.volumes_len() as i32;
|
||||
@@ -2479,7 +2475,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_maybe_adjust_volume_max_honors_preallocate_flag() {
|
||||
fn test_maybe_adjust_volume_max_reserves_plain_volumes_while_preallocating() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
|
||||
@@ -2494,13 +2490,6 @@ mod tests {
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
// Use a large volume_size_limit so the unused-space difference between
|
||||
// preallocate=true (0) and preallocate=false (~2 × limit) is big enough
|
||||
// that integer-division rounding and disk-free fluctuations between the
|
||||
// two get_disk_stats calls cannot make the quotients equal.
|
||||
store
|
||||
.volume_size_limit
|
||||
.store(100 * 1024 * 1024, Ordering::Relaxed);
|
||||
store
|
||||
.add_volume(
|
||||
VolumeId(61),
|
||||
@@ -2511,39 +2500,67 @@ mod tests {
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Room for 2.5 volumes: the plain volume claims one, leaving one more slot.
|
||||
let (_, free) = crate::storage::disk_location::get_disk_stats(dir);
|
||||
let volume_size_limit = (free as f64 / 2.5) as u64;
|
||||
if volume_size_limit == 0 {
|
||||
return; // cannot determine free disk space
|
||||
}
|
||||
store
|
||||
.add_volume(
|
||||
VolumeId(62),
|
||||
.volume_size_limit
|
||||
.store(volume_size_limit, Ordering::Relaxed);
|
||||
store.locations[0].original_max_volume_count = 0;
|
||||
store.set_preallocate(true);
|
||||
|
||||
store.maybe_adjust_volume_max();
|
||||
assert_eq!(
|
||||
store.locations[0].max_volume_count.load(Ordering::Relaxed),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_unused_space_counts_preallocated_volumes_as_full() {
|
||||
const LIMIT: u64 = 1 << 20;
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
2,
|
||||
DiskType::HardDrive,
|
||||
&VolumeSpec {
|
||||
collection: "preallocate_case",
|
||||
..Default::default()
|
||||
},
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
for vid in [VolumeId(61), VolumeId(62)] {
|
||||
let dat_path = store.find_volume(vid).unwrap().1.dat_path();
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(dat_path)
|
||||
.unwrap()
|
||||
.set_len((crate::storage::super_block::SUPER_BLOCK_SIZE + 1) as u64)
|
||||
for (vid, preallocate) in [(VolumeId(71), LIMIT), (VolumeId(72), 0)] {
|
||||
store
|
||||
.add_volume(
|
||||
vid,
|
||||
DiskType::HardDrive,
|
||||
&VolumeSpec {
|
||||
collection: "preallocate_case",
|
||||
preallocate,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
store.locations[0].original_max_volume_count = 0;
|
||||
store.locations[0]
|
||||
.max_volume_count
|
||||
.store(0, Ordering::Relaxed);
|
||||
let preallocated = store.find_volume(VolumeId(71)).unwrap().1;
|
||||
if preallocated.dat_allocated_size() < LIMIT {
|
||||
return; // the filesystem does not support fallocate
|
||||
}
|
||||
|
||||
store.set_preallocate(false);
|
||||
assert!(store.maybe_adjust_volume_max());
|
||||
let without_preallocate = store.locations[0].max_volume_count.load(Ordering::Relaxed);
|
||||
|
||||
store.set_preallocate(true);
|
||||
assert!(store.maybe_adjust_volume_max());
|
||||
let with_preallocate = store.locations[0].max_volume_count.load(Ordering::Relaxed);
|
||||
|
||||
assert!(with_preallocate > without_preallocate);
|
||||
let plain = store.find_volume(VolumeId(72)).unwrap().1;
|
||||
let plain_dat = plain.dat_file_size().unwrap();
|
||||
// The filesystem may round a small file up to a larger allocation unit.
|
||||
let plain_used = plain_dat.max(plain.dat_allocated_size()) + plain.idx_file_size();
|
||||
assert_eq!(store.locations[0].unused_space(LIMIT), LIMIT - plain_used);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -4985,6 +4985,25 @@ impl Volume {
|
||||
self.current_dat_file_size()
|
||||
}
|
||||
|
||||
/// Disk space held by the local .dat file, or 0 when it is unknown. It
|
||||
/// exceeds the file size when the file was preallocated with
|
||||
/// `FALLOC_FL_KEEP_SIZE`.
|
||||
pub fn dat_allocated_size(&self) -> u64 {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let io = self.io.read().unwrap();
|
||||
io.dat_file
|
||||
.as_ref()
|
||||
.and_then(|f| f.metadata().ok())
|
||||
.map_or(0, |m| m.blocks() * 512)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the modification time of the .dat file as Unix seconds.
|
||||
pub fn dat_file_mod_time(&self) -> u64 {
|
||||
let io = self.io.read().unwrap();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package filer_etc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -54,7 +56,7 @@ func (store *FilerEtcStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3Ap
|
||||
// This ensures that all identities (including legacy ones) are written to individual files
|
||||
// and the legacy file is renamed.
|
||||
if foundLegacy {
|
||||
if err := store.migrateToMultiFile(ctx, s3cfg); err != nil {
|
||||
if err := store.migrateToMultiFile(ctx, s3cfg, content); err != nil {
|
||||
glog.Errorf("Failed to migrate IAM configuration to multi-file layout: %v", err)
|
||||
return s3cfg, nil
|
||||
}
|
||||
@@ -137,7 +139,7 @@ func (store *FilerEtcStore) loadFromMultiFile(ctx context.Context, s3cfg *iam_pb
|
||||
return hasIdentities, nil
|
||||
}
|
||||
|
||||
func (store *FilerEtcStore) migrateToMultiFile(ctx context.Context, s3cfg *iam_pb.S3ApiConfiguration) error {
|
||||
func (store *FilerEtcStore) migrateToMultiFile(ctx context.Context, s3cfg *iam_pb.S3ApiConfiguration, migratedContent []byte) error {
|
||||
glog.Infof("Migrating IAM configuration to multi-file layout...")
|
||||
|
||||
// 1. Save all identities
|
||||
@@ -162,7 +164,7 @@ func (store *FilerEtcStore) migrateToMultiFile(ctx context.Context, s3cfg *iam_p
|
||||
}
|
||||
|
||||
// 4. Rename legacy file
|
||||
return store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
err := store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
_, err := client.AtomicRenameEntry(ctx, &filer_pb.AtomicRenameEntryRequest{
|
||||
OldDirectory: filer.IamConfigDirectory,
|
||||
OldName: IamLegacyIdentityFile,
|
||||
@@ -171,6 +173,85 @@ func (store *FilerEtcStore) migrateToMultiFile(ctx context.Context, s3cfg *iam_p
|
||||
})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// A legacy client can rewrite identity.json between the load-time read and
|
||||
// the rename; the rename then strands the newer content under
|
||||
// identity.json.old. Migrate whatever the rename actually captured.
|
||||
return store.migrateStrandedLegacyFile(ctx, migratedContent)
|
||||
}
|
||||
|
||||
func (store *FilerEtcStore) migrateStrandedLegacyFile(ctx context.Context, migratedContent []byte) error {
|
||||
content, found, err := store.readInsideFiler(ctx, filer.IamConfigDirectory, IamLegacyIdentityOldFile)
|
||||
if err != nil || !found || len(content) == 0 || bytes.Equal(content, migratedContent) {
|
||||
return err
|
||||
}
|
||||
|
||||
migrated := &iam_pb.S3ApiConfiguration{}
|
||||
if len(migratedContent) > 0 {
|
||||
if err := filer.ParseS3ConfigurationFromBytes(migratedContent, migrated); err != nil {
|
||||
return fmt.Errorf("failed to re-parse legacy IAM configuration: %w", err)
|
||||
}
|
||||
}
|
||||
stranded := &iam_pb.S3ApiConfiguration{}
|
||||
if err := filer.ParseS3ConfigurationFromBytes(content, stranded); err != nil {
|
||||
return fmt.Errorf("failed to parse renamed legacy IAM configuration: %w", err)
|
||||
}
|
||||
|
||||
for _, identity := range stranded.Identities {
|
||||
if existing := findIdentityByName(migrated.Identities, identity.Name); existing != nil && proto.Equal(existing, identity) {
|
||||
continue
|
||||
}
|
||||
if err := store.saveIdentity(ctx, identity); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, sa := range stranded.ServiceAccounts {
|
||||
if existing := findServiceAccountById(migrated.ServiceAccounts, sa.Id); existing != nil && proto.Equal(existing, sa) {
|
||||
continue
|
||||
}
|
||||
if err := store.saveServiceAccount(ctx, sa); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, g := range stranded.Groups {
|
||||
if existing := findGroupByName(migrated.Groups, g.Name); existing != nil && proto.Equal(existing, g) {
|
||||
continue
|
||||
}
|
||||
if err := store.saveGroup(ctx, g); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func findIdentityByName(identities []*iam_pb.Identity, name string) *iam_pb.Identity {
|
||||
for _, identity := range identities {
|
||||
if identity.Name == name {
|
||||
return identity
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func findServiceAccountById(accounts []*iam_pb.ServiceAccount, id string) *iam_pb.ServiceAccount {
|
||||
for _, sa := range accounts {
|
||||
if sa.Id == id {
|
||||
return sa
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func findGroupByName(groups []*iam_pb.Group, name string) *iam_pb.Group {
|
||||
for _, g := range groups {
|
||||
if g.Name == name {
|
||||
return g
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *FilerEtcStore) SaveConfiguration(ctx context.Context, config *iam_pb.S3ApiConfiguration) error {
|
||||
|
||||
@@ -2,6 +2,7 @@ package filer_etc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
@@ -142,3 +143,64 @@ func TestLoadConfigurationSucceedsOnValidFiles(t *testing.T) {
|
||||
}
|
||||
assert.ElementsMatch(t, []string{"alice", "bob"}, names)
|
||||
}
|
||||
|
||||
// A legacy client that rewrites identity.json between the migration's
|
||||
// load-time read and its rename strands the newer content in
|
||||
// identity.json.old. The migration must pick up those entries instead of
|
||||
// losing them.
|
||||
func TestLoadConfigurationMigratesLegacyWriteRacingWithRename(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, server := newPolicyTestStoreWithServer(t)
|
||||
|
||||
v1 := []byte(`{"identities":[{"name":"alice","credentials":[{"accessKey":"AK1","secretKey":"SK1"}]}]}`)
|
||||
v2 := []byte(`{"identities":[{"name":"alice","credentials":[{"accessKey":"AK1","secretKey":"SK1"}]},{"name":"bob","credentials":[{"accessKey":"AK2","secretKey":"SK2"}]}]}`)
|
||||
putEntry(t, server, filer.IamConfigDirectory, IamLegacyIdentityFile, v1)
|
||||
|
||||
var once sync.Once
|
||||
server.beforeAtomicRename = func(dir, name string) {
|
||||
once.Do(func() {
|
||||
server.mu.Lock()
|
||||
defer server.mu.Unlock()
|
||||
key := filerEntryKey(dir, name)
|
||||
entry := cloneEntry(server.entries[key])
|
||||
entry.Content = v2
|
||||
server.entries[key] = entry
|
||||
})
|
||||
}
|
||||
|
||||
_, err := store.LoadConfiguration(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
bob, err := store.GetUser(ctx, "bob")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "bob", bob.Name)
|
||||
|
||||
alice, err := store.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "alice", alice.Name)
|
||||
|
||||
_, found, err := store.readInsideFiler(ctx, filer.IamConfigDirectory, IamLegacyIdentityFile)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, found)
|
||||
}
|
||||
|
||||
// Without a concurrent write, the migration still renames the legacy file and
|
||||
// writes out every identity.
|
||||
func TestLoadConfigurationMigratesLegacyFile(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, server := newPolicyTestStoreWithServer(t)
|
||||
|
||||
legacy := []byte(`{"identities":[{"name":"alice","credentials":[{"accessKey":"AK1","secretKey":"SK1"}]}]}`)
|
||||
putEntry(t, server, filer.IamConfigDirectory, IamLegacyIdentityFile, legacy)
|
||||
|
||||
_, err := store.LoadConfiguration(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
alice, err := store.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "alice", alice.Name)
|
||||
|
||||
_, found, err := store.readInsideFiler(ctx, filer.IamConfigDirectory, IamLegacyIdentityFile)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, found)
|
||||
}
|
||||
@@ -32,6 +32,7 @@ type policyTestFilerServer struct {
|
||||
afterListEntry func(string, string)
|
||||
beforeDelete func(string, string) error
|
||||
beforeUpdate func(string, string) error
|
||||
beforeAtomicRename func(string, string)
|
||||
}
|
||||
|
||||
func newPolicyTestFilerServer() *policyTestFilerServer {
|
||||
@@ -139,6 +140,29 @@ func (s *policyTestFilerServer) DeleteEntry(_ context.Context, req *filer_pb.Del
|
||||
return &filer_pb.DeleteEntryResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *policyTestFilerServer) AtomicRenameEntry(_ context.Context, req *filer_pb.AtomicRenameEntryRequest) (*filer_pb.AtomicRenameEntryResponse, error) {
|
||||
s.mu.RLock()
|
||||
beforeAtomicRename := s.beforeAtomicRename
|
||||
s.mu.RUnlock()
|
||||
if beforeAtomicRename != nil {
|
||||
beforeAtomicRename(req.OldDirectory, req.OldName)
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
oldKey := filerEntryKey(req.OldDirectory, req.OldName)
|
||||
entry, found := s.entries[oldKey]
|
||||
if !found {
|
||||
return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error())
|
||||
}
|
||||
delete(s.entries, oldKey)
|
||||
renamed := cloneEntry(entry)
|
||||
renamed.Name = req.NewName
|
||||
s.entries[filerEntryKey(req.NewDirectory, req.NewName)] = renamed
|
||||
return &filer_pb.AtomicRenameEntryResponse{}, nil
|
||||
}
|
||||
|
||||
func newPolicyTestStore(t *testing.T) *FilerEtcStore {
|
||||
store, _ := newPolicyTestStoreWithServer(t)
|
||||
return store
|
||||
|
||||
+8
-5
@@ -98,11 +98,13 @@ var fineGrainedActionMap = map[string]string{
|
||||
// prefixed (s3:Action) and unprefixed (Action) variants in init().
|
||||
var baseS3ActionMap = map[string]string{
|
||||
// Object operations
|
||||
"DeleteObject": s3_constants.ACTION_WRITE,
|
||||
"PutObject": s3_constants.ACTION_WRITE,
|
||||
"GetObject": s3_constants.ACTION_READ,
|
||||
"DeleteObjectVersion": s3_constants.ACTION_WRITE,
|
||||
"GetObjectVersion": s3_constants.ACTION_READ,
|
||||
"DeleteObject": s3_constants.ACTION_WRITE,
|
||||
"PutObject": s3_constants.ACTION_WRITE,
|
||||
"GetObject": s3_constants.ACTION_READ,
|
||||
"DeleteObjectVersion": s3_constants.ACTION_WRITE,
|
||||
"GetObjectVersion": s3_constants.ACTION_READ,
|
||||
"GetObjectAttributes": s3_constants.ACTION_READ,
|
||||
"GetObjectVersionAttributes": s3_constants.ACTION_READ,
|
||||
// Tagging operations
|
||||
"GetObjectTagging": s3_constants.ACTION_TAGGING,
|
||||
"GetObjectVersionTagging": s3_constants.ACTION_TAGGING,
|
||||
@@ -115,6 +117,7 @@ var baseS3ActionMap = map[string]string{
|
||||
"DeleteBucketTagging": s3_constants.ACTION_TAGGING,
|
||||
// ACL operations
|
||||
"PutObjectAcl": s3_constants.ACTION_WRITE_ACP,
|
||||
"PutObjectVersionAcl": s3_constants.ACTION_WRITE_ACP,
|
||||
"GetObjectAcl": s3_constants.ACTION_READ_ACP,
|
||||
"GetObjectVersionAcl": s3_constants.ACTION_READ_ACP,
|
||||
"PutBucketAcl": s3_constants.ACTION_WRITE_ACP,
|
||||
|
||||
@@ -3,6 +3,7 @@ package s3api
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -251,9 +252,10 @@ func TestAuthorizeCopySource_PresignedURLSessionTokenPreserved(t *testing.T) {
|
||||
}
|
||||
|
||||
// Presigned URL: session token is in the query string, no
|
||||
// X-Amz-Security-Token header. The destination URL also carries unrelated
|
||||
// SigV4 query params (X-Amz-Algorithm, etc.) that must not leak into the
|
||||
// synthetic source action resolution.
|
||||
// X-Amz-Security-Token header. The destination URL also carries the rest of
|
||||
// the SigV4 presign params, which ride along so auth-derived policy
|
||||
// conditions (s3:authType) match the real request; none of them steer
|
||||
// ResolveS3Action.
|
||||
req, err := http.NewRequest(http.MethodPut,
|
||||
"http://s3.local/bucket-a/dst.bin?X-Amz-Algorithm=AWS4-HMAC-SHA256"+
|
||||
"&X-Amz-Credential=stsKey%2F20260518%2Fus-east-1%2Fs3%2Faws4_request"+
|
||||
@@ -267,8 +269,12 @@ func TestAuthorizeCopySource_PresignedURLSessionTokenPreserved(t *testing.T) {
|
||||
assert.Equal(t, s3err.ErrNone, errCode)
|
||||
assert.Equal(t, "presigned-session-token", capturedSessionToken,
|
||||
"session token from presigned-URL query must reach the IAM check")
|
||||
// versionId omitted, only the token should be present in the synthetic query.
|
||||
assert.Equal(t, "X-Amz-Security-Token=presigned-session-token", capturedRawQuery)
|
||||
capturedQuery, err := url.ParseQuery(capturedRawQuery)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "presigned-session-token", capturedQuery.Get("X-Amz-Security-Token"))
|
||||
assert.Equal(t, "AWS4-HMAC-SHA256", capturedQuery.Get("X-Amz-Algorithm"))
|
||||
assert.False(t, capturedQuery.Has("versionId"))
|
||||
assert.False(t, capturedQuery.Has("acl"))
|
||||
}
|
||||
|
||||
// TestAuthorizeCopySource_PreservesCopySourceHeader verifies that the synthetic
|
||||
|
||||
@@ -3061,11 +3061,21 @@ func (iam *IdentityAccessManagement) bucketsNamedByAttachedPolicies(r *http.Requ
|
||||
// its query describe. versionId, when set, and the STS session token ride along
|
||||
// for policy conditions. Returns ErrNone when auth is disabled (checked by the
|
||||
// callers) or the identity is an admin.
|
||||
// authQueryParams are the query keys carrying a request's authentication
|
||||
// material (SigV2 and SigV4 presign parameters). None steer ResolveS3Action,
|
||||
// so they can ride along on a synthesized request.
|
||||
var authQueryParams = []string{
|
||||
"AWSAccessKeyId", "Signature", "Expires",
|
||||
"X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date", "X-Amz-Expires",
|
||||
"X-Amz-Signature", "X-Amz-SignedHeaders", "X-Amz-Security-Token",
|
||||
}
|
||||
|
||||
// objectKeyPolicyRequest synthesizes a <method> /<bucket>/<objectKey> request
|
||||
// for policy evaluation against a key the real URL does not name. The query is
|
||||
// built from scratch so a param on the real request (delete, uploadId,
|
||||
// partNumber, ...) cannot steer ResolveS3Action off the intended action; the
|
||||
// STS token and versionId ride along for policy conditions.
|
||||
// versionId and the auth-material params ride along so auth-derived policy
|
||||
// conditions (s3:authType) evaluate as they did on the real request.
|
||||
func objectKeyPolicyRequest(r *http.Request, method, bucket, objectKey, versionId string) *http.Request {
|
||||
keyReq := new(http.Request)
|
||||
*keyReq = *r
|
||||
@@ -3078,9 +3088,9 @@ func objectKeyPolicyRequest(r *http.Request, method, bucket, objectKey, versionI
|
||||
if versionId != "" {
|
||||
keyQuery.Set("versionId", versionId)
|
||||
}
|
||||
if strings.Contains(r.URL.RawQuery, "X-Amz-Security-Token") {
|
||||
if token := r.URL.Query().Get("X-Amz-Security-Token"); token != "" {
|
||||
keyQuery.Set("X-Amz-Security-Token", token)
|
||||
for _, key := range authQueryParams {
|
||||
if vals, ok := r.URL.Query()[key]; ok {
|
||||
keyQuery[key] = vals
|
||||
}
|
||||
}
|
||||
if len(keyQuery) > 0 {
|
||||
|
||||
@@ -252,3 +252,59 @@ func (s *Server) finalizeCreateOnCommit(ctx context.Context, input createOnCommi
|
||||
Metadata: newMetadata,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// authorizeCommit asks the S3 Tables layer, before anything is written, whether
|
||||
// the caller may update the table. Both commit paths stage the new metadata
|
||||
// file in the table's directory before UpdateTable authorizes the pointer
|
||||
// flip, so without this gate a caller who may only read the table could still
|
||||
// make the server write and delete files under it. UpdateTable decides again
|
||||
// when the pointer flips.
|
||||
func (s *Server) authorizeCommit(ctx context.Context, bucketARN string, namespace []string, tableName, identityName string) *icebergRequestError {
|
||||
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return s.tablesManager.AuthorizeUpdateTable(ctx, s3tables.NewManagerClient(client), &s3tables.UpdateTableRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
Name: tableName,
|
||||
}, identityName)
|
||||
})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var tableErr *s3tables.S3TablesError
|
||||
if errors.As(err, &tableErr) {
|
||||
switch tableErr.Type {
|
||||
case s3tables.ErrCodeAccessDenied:
|
||||
return &icebergRequestError{http.StatusForbidden, "ForbiddenException", fmt.Sprintf("Not authorized to commit to table %s", tableName)}
|
||||
case s3tables.ErrCodeNoSuchTable, s3tables.ErrCodeNoSuchNamespace:
|
||||
return &icebergRequestError{http.StatusNotFound, "NoSuchTableException", fmt.Sprintf("Table does not exist: %s", tableName)}
|
||||
}
|
||||
}
|
||||
glog.V(1).Infof("Iceberg: commit authorization for %s failed: %v", tableName, err)
|
||||
return &icebergRequestError{http.StatusInternalServerError, "InternalServerError", "Failed to authorize commit: " + err.Error()}
|
||||
}
|
||||
|
||||
// authorizeViewCommit is authorizeCommit for a view, whose update path stages
|
||||
// its metadata file before UpdateView authorizes the pointer flip.
|
||||
func (s *Server) authorizeViewCommit(ctx context.Context, bucketARN string, namespace []string, viewName, identityName string) *icebergRequestError {
|
||||
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return s.tablesManager.AuthorizeUpdateView(ctx, s3tables.NewManagerClient(client), &s3tables.UpdateViewRequest{
|
||||
TableBucketARN: bucketARN,
|
||||
Namespace: namespace,
|
||||
Name: viewName,
|
||||
}, identityName)
|
||||
})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var tableErr *s3tables.S3TablesError
|
||||
if errors.As(err, &tableErr) {
|
||||
switch tableErr.Type {
|
||||
case s3tables.ErrCodeAccessDenied:
|
||||
return &icebergRequestError{http.StatusForbidden, "ForbiddenException", fmt.Sprintf("Not authorized to commit to view %s", viewName)}
|
||||
case s3tables.ErrCodeNoSuchView, s3tables.ErrCodeNoSuchNamespace:
|
||||
return &icebergRequestError{http.StatusNotFound, "NoSuchViewException", fmt.Sprintf("View does not exist: %s", viewName)}
|
||||
}
|
||||
}
|
||||
glog.V(1).Infof("Iceberg: view commit authorization for %s failed: %v", viewName, err)
|
||||
return &icebergRequestError{http.StatusInternalServerError, "InternalServerError", "Failed to authorize commit: " + err.Error()}
|
||||
}
|
||||
@@ -242,6 +242,10 @@ func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) {
|
||||
writeManagerError(w, err)
|
||||
return
|
||||
}
|
||||
if reqErr := s.authorizeCommit(r.Context(), bucketARN, namespace, tableName, identityName); reqErr != nil {
|
||||
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
|
||||
return
|
||||
}
|
||||
|
||||
location := tableLocationFromMetadataLocation(getResp.MetadataLocation)
|
||||
if location == "" {
|
||||
|
||||
@@ -140,6 +140,9 @@ func (s *Server) prepareTableCommit(ctx context.Context, bucketName, bucketARN,
|
||||
glog.V(1).Infof("Iceberg: CommitTransaction GetTable error: %v", err)
|
||||
return nil, &icebergRequestError{http.StatusInternalServerError, "InternalServerError", err.Error()}
|
||||
}
|
||||
if reqErr := s.authorizeCommit(ctx, bucketARN, namespace, tableName, identityName); reqErr != nil {
|
||||
return nil, reqErr
|
||||
}
|
||||
|
||||
location := tableLocationFromMetadataLocation(getResp.MetadataLocation)
|
||||
if location == "" {
|
||||
|
||||
@@ -48,6 +48,10 @@ func (s *Server) handleUpdateView(w http.ResponseWriter, r *http.Request) {
|
||||
writeManagerError(w, err)
|
||||
return
|
||||
}
|
||||
if reqErr := s.authorizeViewCommit(r.Context(), bucketARN, namespace, viewName, identityName); reqErr != nil {
|
||||
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
|
||||
return
|
||||
}
|
||||
if getResp.Metadata == nil || len(getResp.Metadata.FullMetadata) == 0 {
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", "view has no metadata")
|
||||
return
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/apache/iceberg-go"
|
||||
"github.com/apache/iceberg-go/table"
|
||||
"github.com/apache/iceberg-go/view"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// writeLogFiler records every file the handlers create, including files they
|
||||
// delete again before answering, which the final entry map cannot show.
|
||||
type writeLogFiler struct {
|
||||
*memFiler
|
||||
created []string
|
||||
}
|
||||
|
||||
func (f *writeLogFiler) WithFilerClient(_ bool, fn func(client filer_pb.SeaweedFilerClient) error) error {
|
||||
return fn(f)
|
||||
}
|
||||
|
||||
func (f *writeLogFiler) CreateEntry(ctx context.Context, in *filer_pb.CreateEntryRequest, opts ...grpc.CallOption) (*filer_pb.CreateEntryResponse, error) {
|
||||
if !in.Entry.IsDirectory {
|
||||
f.created = append(f.created, path.Join(in.Directory, in.Entry.Name))
|
||||
}
|
||||
return f.memFiler.CreateEntry(ctx, in, opts...)
|
||||
}
|
||||
|
||||
// seedOwnedTable registers an existing table owned by owner.
|
||||
func seedOwnedTable(fc *memFiler, bucket, namespace, tableName, owner string) {
|
||||
internal := map[string]any{
|
||||
"name": tableName,
|
||||
"namespace": namespace,
|
||||
"format": "ICEBERG",
|
||||
"ownerAccountId": owner,
|
||||
"versionToken": "v1",
|
||||
"metadataVersion": 1,
|
||||
"metadataLocation": "s3://" + bucket + "/" + namespace + "/" + tableName + "/metadata/v1.metadata.json",
|
||||
"metadata": s3tables.TableMetadata{
|
||||
Iceberg: &s3tables.IcebergMetadata{TableUUID: "00000000-0000-0000-0000-000000000001"},
|
||||
},
|
||||
}
|
||||
metaBytes, _ := json.Marshal(internal)
|
||||
fc.seed(s3tables.GetTablePath(bucket, namespace, tableName), &filer_pb.Entry{
|
||||
Name: tableName,
|
||||
IsDirectory: true,
|
||||
Extended: map[string][]byte{s3tables.ExtendedKeyMetadata: metaBytes},
|
||||
})
|
||||
}
|
||||
|
||||
// seedOwnedView registers an existing view owned by owner.
|
||||
func seedOwnedView(fc *memFiler, bucket, namespace, viewName, owner string, fullMetadata []byte) {
|
||||
internal := map[string]any{
|
||||
"name": viewName,
|
||||
"namespace": namespace,
|
||||
"format": "ICEBERG",
|
||||
"ownerAccountId": owner,
|
||||
"versionToken": "v1",
|
||||
"metadataVersion": 1,
|
||||
"metadataLocation": "s3://" + bucket + "/" + namespace + "/" + viewName + "/metadata/v1.metadata.json",
|
||||
}
|
||||
if len(fullMetadata) > 0 {
|
||||
internal["metadata"] = s3tables.TableMetadata{FullMetadata: fullMetadata}
|
||||
}
|
||||
metaBytes, _ := json.Marshal(internal)
|
||||
fc.seed(s3tables.GetTablePath(bucket, namespace, viewName), &filer_pb.Entry{
|
||||
Name: viewName,
|
||||
IsDirectory: true,
|
||||
Extended: map[string][]byte{
|
||||
s3tables.ExtendedKeyMetadata: metaBytes,
|
||||
s3tables.ExtendedKeyEntryType: []byte(s3tables.EntryTypeView),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// withActions gives the request an identity allowed only the listed actions.
|
||||
func withActions(r *http.Request, name string, actions ...string) *http.Request {
|
||||
ctx := s3_constants.SetIdentityNameInContext(r.Context(), name)
|
||||
return r.WithContext(s3_constants.SetIdentityInContext(ctx, &struct {
|
||||
Name string
|
||||
Actions []string
|
||||
}{Name: name, Actions: actions}))
|
||||
}
|
||||
|
||||
func viewMetadataJSON(t *testing.T, location string) []byte {
|
||||
t.Helper()
|
||||
schema := iceberg.NewSchemaWithIdentifiers(0, nil,
|
||||
iceberg.NestedField{ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int32, Required: true})
|
||||
ver, err := view.NewVersionFromSQL(1, schema.ID, "SELECT 1", table.Identifier{"finance"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
md, err := view.NewMetadata(ver, schema, location, iceberg.Properties{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fullMetadata, err := json.Marshal(md)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return fullMetadata
|
||||
}
|
||||
|
||||
// A caller that may load a table but not commit to it must be refused before
|
||||
// the commit stages its metadata file in the table's directory. The commit
|
||||
// paths used to write that file, reach the UpdateTable authorization, and
|
||||
// delete the file again on the way out.
|
||||
func TestCommitDeniedBeforeStagingMetadata(t *testing.T) {
|
||||
const bucket = "warehouse"
|
||||
cases := map[string]func(s *Server) *httptest.ResponseRecorder{
|
||||
"commit-table": func(s *Server) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/namespaces/finance/tables/quarterly_reports",
|
||||
strings.NewReader(`{"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}`))
|
||||
r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "table": "quarterly_reports"})
|
||||
w := httptest.NewRecorder()
|
||||
s.handleUpdateTable(w, withActions(r, "reader", "s3tables:GetTable"))
|
||||
return w
|
||||
},
|
||||
"commit-transaction": func(s *Server) *httptest.ResponseRecorder {
|
||||
body := `{"table-changes":[{"identifier":{"namespace":["finance"],"name":"quarterly_reports"},"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}]}`
|
||||
r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/transactions/commit", strings.NewReader(body))
|
||||
r = mux.SetURLVars(r, map[string]string{"prefix": bucket})
|
||||
w := httptest.NewRecorder()
|
||||
s.handleCommitTransaction(w, withActions(r, "reader", "s3tables:GetTable"))
|
||||
return w
|
||||
},
|
||||
"commit-view": func(s *Server) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/namespaces/finance/views/quarterly_view",
|
||||
strings.NewReader(`{"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}`))
|
||||
r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "view": "quarterly_view"})
|
||||
w := httptest.NewRecorder()
|
||||
s.handleUpdateView(w, withActions(r, "reader", "s3tables:GetView"))
|
||||
return w
|
||||
},
|
||||
}
|
||||
for name, run := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
fc := &writeLogFiler{memFiler: newMemFiler()}
|
||||
seedNamespace(fc.memFiler, bucket, "finance", "alice")
|
||||
seedOwnedTable(fc.memFiler, bucket, "finance", "quarterly_reports", "alice")
|
||||
seedOwnedView(fc.memFiler, bucket, "finance", "quarterly_view", "alice", viewMetadataJSON(t, "s3://"+bucket+"/finance/quarterly_view"))
|
||||
s := NewServer(fc, nil)
|
||||
|
||||
w := run(s)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Errorf("status = %d, want %d (body: %s)", w.Code, http.StatusForbidden, w.Body.String())
|
||||
}
|
||||
if len(fc.created) != 0 {
|
||||
t.Errorf("refused commit wrote %v", fc.created)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The owner, and a caller whose own identity carries UpdateTable, still
|
||||
// stage their metadata file and land the commit.
|
||||
func TestCommitAllowedStagesMetadata(t *testing.T) {
|
||||
const bucket = "warehouse"
|
||||
callers := map[string]func(r *http.Request) *http.Request{
|
||||
"owner": func(r *http.Request) *http.Request {
|
||||
return r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice"))
|
||||
},
|
||||
"identity-actions": func(r *http.Request) *http.Request {
|
||||
return withActions(r, "writer", "s3tables:GetTable", "s3tables:UpdateTable")
|
||||
},
|
||||
}
|
||||
for name, as := range callers {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
fc := &writeLogFiler{memFiler: newMemFiler()}
|
||||
seedNamespace(fc.memFiler, bucket, "finance", "alice")
|
||||
seedOwnedTable(fc.memFiler, bucket, "finance", "quarterly_reports", "alice")
|
||||
s := NewServer(fc, nil)
|
||||
|
||||
r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/namespaces/finance/tables/quarterly_reports",
|
||||
strings.NewReader(`{"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}`))
|
||||
r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "table": "quarterly_reports"})
|
||||
w := httptest.NewRecorder()
|
||||
s.handleUpdateTable(w, as(r))
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d (body: %s)", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
if len(fc.created) != 1 || !strings.HasSuffix(fc.created[0], ".metadata.json") {
|
||||
t.Fatalf("created = %v, want one metadata file", fc.created)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Same staging gate on the view commit path: the owner, and a caller whose own
|
||||
// identity carries UpdateView, stage a metadata file and land the commit.
|
||||
func TestViewCommitAllowedStagesMetadata(t *testing.T) {
|
||||
const bucket = "warehouse"
|
||||
fullMetadata := viewMetadataJSON(t, "s3://"+bucket+"/finance/quarterly_view")
|
||||
|
||||
callers := map[string]func(r *http.Request) *http.Request{
|
||||
"owner": func(r *http.Request) *http.Request {
|
||||
return r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice"))
|
||||
},
|
||||
"identity-actions": func(r *http.Request) *http.Request {
|
||||
return withActions(r, "writer", "s3tables:GetView", "s3tables:UpdateView")
|
||||
},
|
||||
}
|
||||
for name, as := range callers {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
fc := &writeLogFiler{memFiler: newMemFiler()}
|
||||
seedNamespace(fc.memFiler, bucket, "finance", "alice")
|
||||
seedOwnedView(fc.memFiler, bucket, "finance", "quarterly_view", "alice", fullMetadata)
|
||||
s := NewServer(fc, nil)
|
||||
|
||||
r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/namespaces/finance/views/quarterly_view",
|
||||
strings.NewReader(`{"requirements":[],"updates":[{"action":"set-properties","updates":{"k":"v"}}]}`))
|
||||
r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "view": "quarterly_view"})
|
||||
w := httptest.NewRecorder()
|
||||
s.handleUpdateView(w, as(r))
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d (body: %s)", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
if len(fc.created) != 1 || !strings.HasSuffix(fc.created[0], ".metadata.json") {
|
||||
t.Fatalf("created = %v, want one metadata file", fc.created)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -166,15 +166,25 @@ func resolveFromQueryParameters(query url.Values, method string, hasObject bool)
|
||||
}
|
||||
}
|
||||
|
||||
// ACL operations
|
||||
// ACL operations. A versionId retargets the request at a specific
|
||||
// version, so the version ACL action applies, not the current-object one.
|
||||
if query.Has("acl") {
|
||||
versioned := hasObject && query.Get("versionId") != ""
|
||||
switch method {
|
||||
case http.MethodGet, http.MethodHead:
|
||||
// HEAD has no acl route; it lands on HeadObjectHandler and should
|
||||
// resolve like a read — s3:GetObject, or s3:GetObjectVersion below.
|
||||
case http.MethodGet:
|
||||
if versioned {
|
||||
return s3_constants.S3_ACTION_GET_OBJECT_VERSION_ACL
|
||||
}
|
||||
if hasObject {
|
||||
return s3_constants.S3_ACTION_GET_OBJECT_ACL
|
||||
}
|
||||
return s3_constants.S3_ACTION_GET_BUCKET_ACL
|
||||
case http.MethodPut:
|
||||
if versioned {
|
||||
return s3_constants.S3_ACTION_PUT_OBJECT_VERSION_ACL
|
||||
}
|
||||
if hasObject {
|
||||
return s3_constants.S3_ACTION_PUT_OBJECT_ACL
|
||||
}
|
||||
@@ -220,6 +230,9 @@ func resolveFromQueryParameters(query url.Values, method string, hasObject bool)
|
||||
// Must be checked before versionId, because GET /bucket/key?attributes&versionId=xyz
|
||||
// is a GetObjectAttributes request, not a GetObjectVersion request
|
||||
if hasObject && query.Has("attributes") && method == http.MethodGet {
|
||||
if query.Get("versionId") != "" {
|
||||
return s3_constants.S3_ACTION_GET_OBJECT_VERSION_ATTRIBUTES
|
||||
}
|
||||
return s3_constants.S3_ACTION_GET_OBJECT_ATTRIBUTES
|
||||
}
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ func TestResolveS3Action_AttributesBeforeVersionId(t *testing.T) {
|
||||
method: http.MethodGet,
|
||||
baseAction: s3_constants.ACTION_READ,
|
||||
object: "key",
|
||||
want: s3_constants.S3_ACTION_GET_OBJECT_ATTRIBUTES,
|
||||
want: s3_constants.S3_ACTION_GET_OBJECT_VERSION_ATTRIBUTES,
|
||||
},
|
||||
{
|
||||
name: "versionId only GET",
|
||||
@@ -146,6 +146,59 @@ func TestResolveS3Action_VersionTagging(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// An ACL request carrying versionId targets a specific version and must
|
||||
// resolve to the version ACL action so a grant limited to the current-object
|
||||
// action cannot reach historical versions.
|
||||
func TestResolveS3Action_VersionAcl(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
object string
|
||||
query string
|
||||
want string
|
||||
}{
|
||||
{"get current acl", http.MethodGet, "key", "acl", s3_constants.S3_ACTION_GET_OBJECT_ACL},
|
||||
{"put current acl", http.MethodPut, "key", "acl", s3_constants.S3_ACTION_PUT_OBJECT_ACL},
|
||||
{"get version acl", http.MethodGet, "key", "acl&versionId=v1", s3_constants.S3_ACTION_GET_OBJECT_VERSION_ACL},
|
||||
{"head acl resolves as head object", http.MethodHead, "key", "acl", s3_constants.S3_ACTION_GET_OBJECT},
|
||||
{"head version acl resolves as head version", http.MethodHead, "key", "acl&versionId=v1", s3_constants.S3_ACTION_GET_OBJECT_VERSION},
|
||||
{"put version acl", http.MethodPut, "key", "acl&versionId=v1", s3_constants.S3_ACTION_PUT_OBJECT_VERSION_ACL},
|
||||
{"empty versionId stays current", http.MethodGet, "key", "acl&versionId=", s3_constants.S3_ACTION_GET_OBJECT_ACL},
|
||||
{"bucket acl ignores versionId", http.MethodGet, "", "acl&versionId=v1", s3_constants.S3_ACTION_GET_BUCKET_ACL},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r, _ := http.NewRequest(tt.method, "http://localhost/bucket/"+tt.object+"?"+tt.query, nil)
|
||||
if got := ResolveS3Action(r, s3_constants.ACTION_READ, "bucket", tt.object); got != tt.want {
|
||||
t.Errorf("ResolveS3Action() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An attributes request carrying versionId targets a specific version and
|
||||
// must resolve to the version attributes action.
|
||||
func TestResolveS3Action_VersionAttributes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
object string
|
||||
query string
|
||||
want string
|
||||
}{
|
||||
{"get current attributes", http.MethodGet, "key", "attributes", s3_constants.S3_ACTION_GET_OBJECT_ATTRIBUTES},
|
||||
{"get version attributes", http.MethodGet, "key", "attributes&versionId=v1", s3_constants.S3_ACTION_GET_OBJECT_VERSION_ATTRIBUTES},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r, _ := http.NewRequest(tt.method, "http://localhost/bucket/"+tt.object+"?"+tt.query, nil)
|
||||
if got := ResolveS3Action(r, s3_constants.ACTION_READ, "bucket", tt.object); got != tt.want {
|
||||
t.Errorf("ResolveS3Action() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Bucket subresources registered with ACTION_ADMIN must resolve to their own
|
||||
// S3 actions so a policy granting one of them does not need s3:*, and so no
|
||||
// broader grant sweeps them in.
|
||||
|
||||
@@ -4,17 +4,22 @@ package s3_constants
|
||||
// These match the official AWS S3 action format used in IAM and bucket policies
|
||||
const (
|
||||
// Object operations
|
||||
S3_ACTION_GET_OBJECT = "s3:GetObject"
|
||||
S3_ACTION_PUT_OBJECT = "s3:PutObject"
|
||||
S3_ACTION_DELETE_OBJECT = "s3:DeleteObject"
|
||||
S3_ACTION_DELETE_OBJECT_VERSION = "s3:DeleteObjectVersion"
|
||||
S3_ACTION_GET_OBJECT_VERSION = "s3:GetObjectVersion"
|
||||
S3_ACTION_GET_OBJECT_ATTRIBUTES = "s3:GetObjectAttributes"
|
||||
S3_ACTION_GET_OBJECT = "s3:GetObject"
|
||||
S3_ACTION_PUT_OBJECT = "s3:PutObject"
|
||||
S3_ACTION_DELETE_OBJECT = "s3:DeleteObject"
|
||||
S3_ACTION_DELETE_OBJECT_VERSION = "s3:DeleteObjectVersion"
|
||||
S3_ACTION_GET_OBJECT_VERSION = "s3:GetObjectVersion"
|
||||
S3_ACTION_GET_OBJECT_ATTRIBUTES = "s3:GetObjectAttributes"
|
||||
S3_ACTION_GET_OBJECT_VERSION_ATTRIBUTES = "s3:GetObjectVersionAttributes"
|
||||
|
||||
// Object ACL operations
|
||||
S3_ACTION_GET_OBJECT_ACL = "s3:GetObjectAcl"
|
||||
S3_ACTION_PUT_OBJECT_ACL = "s3:PutObjectAcl"
|
||||
|
||||
// Version-specific ACL operations (?acl&versionId)
|
||||
S3_ACTION_GET_OBJECT_VERSION_ACL = "s3:GetObjectVersionAcl"
|
||||
S3_ACTION_PUT_OBJECT_VERSION_ACL = "s3:PutObjectVersionAcl"
|
||||
|
||||
// Object tagging operations
|
||||
S3_ACTION_GET_OBJECT_TAGGING = "s3:GetObjectTagging"
|
||||
S3_ACTION_PUT_OBJECT_TAGGING = "s3:PutObjectTagging"
|
||||
|
||||
@@ -576,3 +576,97 @@ func TestRecheckObjectAclTagConditionedPolicy(t *testing.T) {
|
||||
assert.Equal(t, s3err.ErrNone,
|
||||
s3a.recheckPolicyWithObjectEntry(putReq, "b", "secret.txt", s3_constants.S3_ACTION_PUT_OBJECT_ACL, publicEntry, "test"))
|
||||
}
|
||||
|
||||
// A versioned GetObjectAttributes request is authorized against the version
|
||||
// read grant, not the attributes action the original request resolves to: an
|
||||
// explicit bucket-policy Deny on s3:GetObjectVersion blocks it, while a legacy
|
||||
// identity holding only the coarse Read grant is still accepted.
|
||||
func TestCheckVersionReadGrant(t *testing.T) {
|
||||
s3a := &S3ApiServer{
|
||||
policyEngine: NewBucketPolicyEngine(),
|
||||
iam: &IdentityAccessManagement{},
|
||||
}
|
||||
|
||||
denyPolicyJSON := `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "s3:*",
|
||||
"Resource": ["arn:aws:s3:::deny-bucket", "arn:aws:s3:::deny-bucket/*"]
|
||||
},
|
||||
{
|
||||
"Effect": "Deny",
|
||||
"Principal": "*",
|
||||
"Action": "s3:GetObjectVersion",
|
||||
"Resource": "arn:aws:s3:::deny-bucket/key"
|
||||
}
|
||||
]
|
||||
}`
|
||||
require.NoError(t, s3a.policyEngine.engine.SetBucketPolicy("deny-bucket", denyPolicyJSON))
|
||||
|
||||
allowPolicyJSON := `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "s3:*",
|
||||
"Resource": ["arn:aws:s3:::allow-bucket", "arn:aws:s3:::allow-bucket/*"]
|
||||
}
|
||||
]
|
||||
}`
|
||||
require.NoError(t, s3a.policyEngine.engine.SetBucketPolicy("allow-bucket", allowPolicyJSON))
|
||||
|
||||
identity := &Identity{
|
||||
Name: "reader",
|
||||
Actions: []Action{s3_constants.ACTION_READ},
|
||||
PrincipalArn: "arn:aws:iam::000000000000:user/reader",
|
||||
}
|
||||
|
||||
attrsReq := func(bucket string) *http.Request {
|
||||
req := httptest.NewRequest(http.MethodGet, "/"+bucket+"/key?attributes&versionId=v1", nil)
|
||||
return req.WithContext(s3_constants.SetIdentityInContext(req.Context(), identity))
|
||||
}
|
||||
|
||||
assert.Equal(t, s3err.ErrAccessDenied,
|
||||
s3a.checkVersionReadGrant(attrsReq("deny-bucket"), "deny-bucket", "key", "v1", nil))
|
||||
assert.Equal(t, s3err.ErrNone,
|
||||
s3a.checkVersionReadGrant(attrsReq("allow-bucket"), "allow-bucket", "key", "v1", nil))
|
||||
assert.Equal(t, s3err.ErrNone,
|
||||
s3a.checkVersionReadGrant(attrsReq("no-policy-bucket"), "no-policy-bucket", "key", "v1", nil))
|
||||
}
|
||||
|
||||
// Presigned-URL credentials ride along on the synthesized version-read
|
||||
// request, so an s3:authType=REST-QUERY-STRING policy condition decides the
|
||||
// recheck the same way it decided the real request.
|
||||
func TestCheckVersionReadGrantPreservesQueryAuth(t *testing.T) {
|
||||
s3a := &S3ApiServer{
|
||||
policyEngine: NewBucketPolicyEngine(),
|
||||
iam: &IdentityAccessManagement{},
|
||||
}
|
||||
|
||||
policyJSON := `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "s3:*",
|
||||
"Resource": ["arn:aws:s3:::qs-bucket", "arn:aws:s3:::qs-bucket/*"],
|
||||
"Condition": {"StringEquals": {"s3:authType": "REST-QUERY-STRING"}}
|
||||
}]
|
||||
}`
|
||||
require.NoError(t, s3a.policyEngine.engine.SetBucketPolicy("qs-bucket", policyJSON))
|
||||
|
||||
presigned := httptest.NewRequest(http.MethodGet,
|
||||
"/qs-bucket/key?attributes&versionId=v1&AWSAccessKeyId=AK&Signature=sig&Expires=9999999999", nil)
|
||||
assert.Equal(t, s3err.ErrNone,
|
||||
s3a.checkVersionReadGrant(presigned, "qs-bucket", "key", "v1", nil))
|
||||
|
||||
keyReq := objectKeyPolicyRequest(presigned, http.MethodGet, "qs-bucket", "key", "v1")
|
||||
q := keyReq.URL.Query()
|
||||
assert.Equal(t, "AK", q.Get("AWSAccessKeyId"))
|
||||
assert.Equal(t, "v1", q.Get("versionId"))
|
||||
assert.False(t, q.Has("attributes"))
|
||||
}
|
||||
@@ -30,6 +30,10 @@ func (s3a *S3ApiServer) GetObjectAclHandler(w http.ResponseWriter, r *http.Reque
|
||||
|
||||
// Check for specific version ID in query parameters
|
||||
versionId := r.URL.Query().Get("versionId")
|
||||
if errCode := s3a.checkVersionIdConfigured(bucket, versionId); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if versioning is configured for the bucket (Enabled or Suspended)
|
||||
versioningConfigured, err := s3a.isVersioningConfigured(bucket)
|
||||
@@ -89,7 +93,11 @@ func (s3a *S3ApiServer) GetObjectAclHandler(w http.ResponseWriter, r *http.Reque
|
||||
return
|
||||
}
|
||||
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, s3_constants.S3_ACTION_GET_OBJECT_ACL, entry.Extended, "GetObjectAclHandler"); errCode != s3err.ErrNone {
|
||||
action := s3_constants.S3_ACTION_GET_OBJECT_ACL
|
||||
if versionId != "" {
|
||||
action = s3_constants.S3_ACTION_GET_OBJECT_VERSION_ACL
|
||||
}
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, action, entry.Extended, "GetObjectAclHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
@@ -142,6 +150,10 @@ func (s3a *S3ApiServer) PutObjectAclHandler(w http.ResponseWriter, r *http.Reque
|
||||
|
||||
// Check for specific version ID in query parameters
|
||||
versionId := r.URL.Query().Get("versionId")
|
||||
if errCode := s3a.checkVersionIdConfigured(bucket, versionId); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if versioning is configured for the bucket (Enabled or Suspended)
|
||||
versioningConfigured, err := s3a.isVersioningConfigured(bucket)
|
||||
@@ -201,7 +213,11 @@ func (s3a *S3ApiServer) PutObjectAclHandler(w http.ResponseWriter, r *http.Reque
|
||||
return
|
||||
}
|
||||
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, s3_constants.S3_ACTION_PUT_OBJECT_ACL, entry.Extended, "PutObjectAclHandler"); errCode != s3err.ErrNone {
|
||||
putAction := s3_constants.S3_ACTION_PUT_OBJECT_ACL
|
||||
if versionId != "" {
|
||||
putAction = s3_constants.S3_ACTION_PUT_OBJECT_VERSION_ACL
|
||||
}
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, putAction, entry.Extended, "PutObjectAclHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -129,6 +129,10 @@ func (s3a *S3ApiServer) GetObjectAttributesHandler(w http.ResponseWriter, r *htt
|
||||
|
||||
// Check for specific version ID
|
||||
versionId := r.URL.Query().Get("versionId")
|
||||
if errCode := s3a.checkVersionIdConfigured(bucket, versionId); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
entry *filer_pb.Entry
|
||||
@@ -219,11 +223,24 @@ func (s3a *S3ApiServer) GetObjectAttributesHandler(w http.ResponseWriter, r *htt
|
||||
}
|
||||
}
|
||||
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, s3_constants.S3_ACTION_GET_OBJECT_ATTRIBUTES, entry.Extended, "GetObjectAttributesHandler"); errCode != s3err.ErrNone {
|
||||
action := s3_constants.S3_ACTION_GET_OBJECT_ATTRIBUTES
|
||||
if versionId != "" {
|
||||
action = s3_constants.S3_ACTION_GET_OBJECT_VERSION_ATTRIBUTES
|
||||
}
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, action, entry.Extended, "GetObjectAttributesHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// AWS also asks for the version read grant on a versioned attributes
|
||||
// request: s3:GetObjectVersionAttributes alone is not sufficient.
|
||||
if versionId != "" {
|
||||
if errCode := s3a.checkVersionReadGrant(r, bucket, object, versionId, entry.Extended); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Evaluate conditional headers against the resolved entry (after version resolution)
|
||||
// This ensures conditions are checked against the correct version, not always the latest
|
||||
if s3a.hasConditionalHeaders(r) {
|
||||
|
||||
@@ -29,6 +29,10 @@ func (s3a *S3ApiServer) GetObjectTaggingHandler(w http.ResponseWriter, r *http.R
|
||||
|
||||
// Check for specific version ID in query parameters
|
||||
versionId := r.URL.Query().Get("versionId")
|
||||
if errCode := s3a.checkVersionIdConfigured(bucket, versionId); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if versioning is configured for the bucket (Enabled or Suspended)
|
||||
versioningConfigured, err := s3a.isVersioningConfigured(bucket)
|
||||
@@ -87,7 +91,11 @@ func (s3a *S3ApiServer) GetObjectTaggingHandler(w http.ResponseWriter, r *http.R
|
||||
}
|
||||
}
|
||||
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, s3_constants.S3_ACTION_GET_OBJECT_TAGGING, entry.Extended, "GetObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
action := s3_constants.S3_ACTION_GET_OBJECT_TAGGING
|
||||
if versionId != "" {
|
||||
action = s3_constants.S3_ACTION_GET_OBJECT_VERSION_TAGGING
|
||||
}
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, action, entry.Extended, "GetObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
@@ -140,6 +148,10 @@ func (s3a *S3ApiServer) PutObjectTaggingHandler(w http.ResponseWriter, r *http.R
|
||||
|
||||
// Check for specific version ID in query parameters
|
||||
versionId := r.URL.Query().Get("versionId")
|
||||
if errCode := s3a.checkVersionIdConfigured(bucket, versionId); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if versioning is configured for the bucket (Enabled or Suspended)
|
||||
versioningConfigured, err := s3a.isVersioningConfigured(bucket)
|
||||
@@ -185,7 +197,11 @@ func (s3a *S3ApiServer) PutObjectTaggingHandler(w http.ResponseWriter, r *http.R
|
||||
target := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), object))
|
||||
dir, name := target.DirAndName()
|
||||
|
||||
if errCode := s3a.recheckTagConditionedPolicyWithLookup(r, bucket, object, versionId, s3_constants.S3_ACTION_PUT_OBJECT_TAGGING, "PutObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
putAction := s3_constants.S3_ACTION_PUT_OBJECT_TAGGING
|
||||
if versionId != "" {
|
||||
putAction = s3_constants.S3_ACTION_PUT_OBJECT_VERSION_TAGGING
|
||||
}
|
||||
if errCode := s3a.recheckTagConditionedPolicyWithLookup(r, bucket, object, versionId, putAction, "PutObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
@@ -206,7 +222,11 @@ func (s3a *S3ApiServer) PutObjectTaggingHandler(w http.ResponseWriter, r *http.R
|
||||
return
|
||||
}
|
||||
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, s3_constants.S3_ACTION_PUT_OBJECT_TAGGING, entry.Extended, "PutObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
putAction := s3_constants.S3_ACTION_PUT_OBJECT_TAGGING
|
||||
if versionId != "" {
|
||||
putAction = s3_constants.S3_ACTION_PUT_OBJECT_VERSION_TAGGING
|
||||
}
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, putAction, entry.Extended, "PutObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
@@ -268,6 +288,10 @@ func (s3a *S3ApiServer) DeleteObjectTaggingHandler(w http.ResponseWriter, r *htt
|
||||
|
||||
// Check for specific version ID in query parameters
|
||||
versionId := r.URL.Query().Get("versionId")
|
||||
if errCode := s3a.checkVersionIdConfigured(bucket, versionId); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if versioning is configured for the bucket (Enabled or Suspended)
|
||||
versioningConfigured, err := s3a.isVersioningConfigured(bucket)
|
||||
@@ -313,7 +337,11 @@ func (s3a *S3ApiServer) DeleteObjectTaggingHandler(w http.ResponseWriter, r *htt
|
||||
target := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), object))
|
||||
dir, name := target.DirAndName()
|
||||
|
||||
if errCode := s3a.recheckTagConditionedPolicyWithLookup(r, bucket, object, versionId, s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING, "DeleteObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
deleteAction := s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING
|
||||
if versionId != "" {
|
||||
deleteAction = s3_constants.S3_ACTION_DELETE_OBJECT_VERSION_TAGGING
|
||||
}
|
||||
if errCode := s3a.recheckTagConditionedPolicyWithLookup(r, bucket, object, versionId, deleteAction, "DeleteObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
@@ -335,7 +363,11 @@ func (s3a *S3ApiServer) DeleteObjectTaggingHandler(w http.ResponseWriter, r *htt
|
||||
return
|
||||
}
|
||||
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING, entry.Extended, "DeleteObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
deleteAction := s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING
|
||||
if versionId != "" {
|
||||
deleteAction = s3_constants.S3_ACTION_DELETE_OBJECT_VERSION_TAGGING
|
||||
}
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, deleteAction, entry.Extended, "DeleteObjectTaggingHandler"); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -681,6 +681,21 @@ func (s3a *S3ApiServer) recheckPolicyWithObjectEntry(r *http.Request, bucket, ob
|
||||
return errCode
|
||||
}
|
||||
|
||||
// checkVersionReadGrant enforces the version read grant AWS requires alongside
|
||||
// a version-scoped action such as s3:GetObjectVersionAttributes. The check runs
|
||||
// on a request shaped like a plain versioned GET so the s3:GetObjectVersion
|
||||
// action resolves from the request instead of the caller's subresource, and a
|
||||
// legacy Read grant still applies.
|
||||
func (s3a *S3ApiServer) checkVersionReadGrant(r *http.Request, bucket, object, versionId string, objectEntry map[string][]byte) s3err.ErrorCode {
|
||||
versionReadReq := objectKeyPolicyRequest(r, http.MethodGet, bucket, object, versionId)
|
||||
if identity, ok := GetIdentityFromContext(r).(*Identity); ok && identity != nil {
|
||||
if errCode := s3a.iam.VerifyActionPermission(versionReadReq, identity, ACTION_READ, bucket, object); errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
}
|
||||
return s3a.recheckPolicyWithObjectEntry(versionReadReq, bucket, object, ACTION_READ, objectEntry, "checkVersionReadGrant")
|
||||
}
|
||||
|
||||
// recheckCopySourcePolicy repeats the source object's policy check once its
|
||||
// entry is fetched, so conditions on the object's existing tags apply to a
|
||||
// CopyObject / UploadPartCopy / RenameObject source the same way they do to a
|
||||
|
||||
@@ -4,7 +4,8 @@ package backend
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
)
|
||||
@@ -15,8 +16,11 @@ func CreateVolumeFile(fileName string, preallocate int64, memoryMapSizeMB uint32
|
||||
return nil, e
|
||||
}
|
||||
if preallocate != 0 {
|
||||
syscall.Fallocate(int(file.Fd()), 1, 0, preallocate)
|
||||
glog.V(1).Infof("Preallocated %d bytes disk space for %s", preallocate, fileName)
|
||||
if err := unix.Fallocate(int(file.Fd()), unix.FALLOC_FL_KEEP_SIZE, 0, preallocate); err != nil {
|
||||
glog.Warningf("Preallocate %d bytes disk space for %s: %v", preallocate, fileName, err)
|
||||
} else {
|
||||
glog.V(1).Infof("Preallocated %d bytes disk space for %s", preallocate, fileName)
|
||||
}
|
||||
}
|
||||
return NewDiskFile(file), nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//go:build linux
|
||||
|
||||
package backend
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func TestCreateVolumeFilePreallocateKeepsSize(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
const preallocate = 1 << 20
|
||||
|
||||
probe, err := os.Create(filepath.Join(dir, "probe"))
|
||||
if err != nil {
|
||||
t.Fatalf("create probe: %v", err)
|
||||
}
|
||||
err = unix.Fallocate(int(probe.Fd()), unix.FALLOC_FL_KEEP_SIZE, 0, preallocate)
|
||||
probe.Close()
|
||||
if err != nil {
|
||||
t.Skipf("fallocate not supported in %s: %v", dir, err)
|
||||
}
|
||||
|
||||
fileName := filepath.Join(dir, "1.dat")
|
||||
f, err := CreateVolumeFile(fileName, preallocate, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateVolumeFile: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
size, _, err := f.GetStat()
|
||||
if err != nil {
|
||||
t.Fatalf("GetStat: %v", err)
|
||||
}
|
||||
if size != 0 {
|
||||
t.Errorf("file size = %d, want 0", size)
|
||||
}
|
||||
|
||||
var st syscall.Stat_t
|
||||
if err := syscall.Stat(fileName, &st); err != nil {
|
||||
t.Fatalf("stat: %v", err)
|
||||
}
|
||||
if st.Blocks*512 < preallocate {
|
||||
t.Errorf("allocated %d bytes, want at least %d", st.Blocks*512, preallocate)
|
||||
}
|
||||
}
|
||||
@@ -704,6 +704,8 @@ func (l *DiskLocation) UnUsedSpace(volumeSizeLimit uint64) (unUsedSpace uint64)
|
||||
continue
|
||||
}
|
||||
datSize, idxSize, _ := vol.FileStat()
|
||||
// A preallocated volume already holds its space on disk.
|
||||
datSize = max(datSize, vol.datAllocatedSize())
|
||||
unUsedSpaceVolume := int64(volumeSizeLimit) - int64(datSize+idxSize)
|
||||
glog.V(4).Infof("Volume stats for %d: volumeSizeLimit=%d, datSize=%d idxSize=%d unused=%d", vol.Id, volumeSizeLimit, datSize, idxSize, unUsedSpaceVolume)
|
||||
if unUsedSpaceVolume >= 0 {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
)
|
||||
|
||||
func TestUnUsedSpaceCountsPreallocatedVolumesAsFull(t *testing.T) {
|
||||
const volumeSizeLimit = 1 << 20
|
||||
dir := t.TempDir()
|
||||
|
||||
preallocated, err := backend.CreateVolumeFile(filepath.Join(dir, "1.dat"), volumeSizeLimit, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer preallocated.Close()
|
||||
fi, err := preallocated.(*backend.DiskFile).File.Stat()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if allocatedSize(fi) < volumeSizeLimit {
|
||||
t.Skipf("filesystem at %s does not support fallocate", dir)
|
||||
}
|
||||
|
||||
plainFile, err := os.Create(filepath.Join(dir, "2.dat"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := plainFile.Write(make([]byte, 4096)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plain := backend.NewDiskFile(plainFile)
|
||||
defer plain.Close()
|
||||
fi, err = plainFile.Stat()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The filesystem may round a small file up to a larger allocation unit.
|
||||
plainSize := max(uint64(fi.Size()), allocatedSize(fi))
|
||||
|
||||
diskLocation := DiskLocation{Directory: dir, IdxDirectory: dir}
|
||||
diskLocation.volumes = make(map[needle.VolumeId]*Volume)
|
||||
diskLocation.SetVolume(1, &Volume{Id: 1, dir: dir, dirIdx: dir, DataBackend: preallocated, nm: &mockNeedleMapper{}})
|
||||
diskLocation.SetVolume(2, &Volume{Id: 2, dir: dir, dirIdx: dir, DataBackend: plain, nm: &mockNeedleMapper{}})
|
||||
|
||||
if got, want := diskLocation.UnUsedSpace(volumeSizeLimit), volumeSizeLimit-plainSize; got != want {
|
||||
t.Errorf("unUsedSpace = %d, want %d", got, want)
|
||||
}
|
||||
}
|
||||
@@ -30,8 +30,8 @@ fmt.Println(dist.Summary())
|
||||
// Replication: replication=110 (DCs:2, Racks/DC:2, Nodes/Rack:1)
|
||||
// Distribution Plan:
|
||||
// Data Centers: 2 (target 7 shards each, max 9)
|
||||
// Racks per DC: 2 (target 4 shards each, max 6)
|
||||
// Nodes per Rack: 1 (target 4 shards each, max 6)
|
||||
// Racks per DC: 2 (target 4 shards each, max 4)
|
||||
// Nodes per Rack: 1 (target 4 shards each, max 4)
|
||||
```
|
||||
|
||||
### Custom EC Ratios (seaweed-enterprise)
|
||||
|
||||
@@ -1,5 +1,103 @@
|
||||
package distribution
|
||||
|
||||
// NewTopologyAnalysis creates an empty topology analysis.
|
||||
func NewTopologyAnalysis() *TopologyAnalysis {
|
||||
return &TopologyAnalysis{
|
||||
ShardsByDC: make(map[string]int),
|
||||
ShardsByRack: make(map[string]int),
|
||||
ShardsByNode: make(map[string]int),
|
||||
DCToShards: make(map[string][]int),
|
||||
RackToShards: make(map[string][]int),
|
||||
NodeToShards: make(map[string][]int),
|
||||
DCToRacks: make(map[string][]string),
|
||||
RackToNodes: make(map[string][]*TopologyNode),
|
||||
AllNodes: make(map[string]*TopologyNode),
|
||||
}
|
||||
}
|
||||
|
||||
// AddNode registers a node in the topology, including any shards it already
|
||||
// holds for the volume being analyzed. A node id may only register once;
|
||||
// registering it again updates its capacity and adds any new shards. The
|
||||
// first registration wins for the node's place in the topology.
|
||||
func (a *TopologyAnalysis) AddNode(node *TopologyNode) {
|
||||
registered, ok := a.AllNodes[node.NodeID]
|
||||
if !ok {
|
||||
registered = node
|
||||
a.AllNodes[node.NodeID] = node
|
||||
a.RackToNodes[rackKey(node.DataCenter, node.Rack)] = append(a.RackToNodes[rackKey(node.DataCenter, node.Rack)], node)
|
||||
if !contains(a.DCToRacks[node.DataCenter], node.Rack) {
|
||||
a.DCToRacks[node.DataCenter] = append(a.DCToRacks[node.DataCenter], node.Rack)
|
||||
}
|
||||
} else {
|
||||
registered.FreeSlots = node.FreeSlots
|
||||
registered.TotalShards = node.TotalShards
|
||||
}
|
||||
seen := node.ShardIDs[:0]
|
||||
for _, shardID := range node.ShardIDs {
|
||||
if !contains(seen, shardID) {
|
||||
seen = append(seen, shardID)
|
||||
}
|
||||
}
|
||||
node.ShardIDs = seen
|
||||
for _, shardID := range node.ShardIDs {
|
||||
a.AddShardLocation(ShardLocation{
|
||||
ShardID: shardID,
|
||||
NodeID: registered.NodeID,
|
||||
DataCenter: registered.DataCenter,
|
||||
Rack: registered.Rack,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// AddShardLocation records one shard's placement in the topology. Repeated
|
||||
// calls for a shard already known to its node are ignored, so callers may
|
||||
// either set ShardIDs on the TopologyNode or register each shard here. A
|
||||
// location naming an unregistered node registers that node so the rebalancer
|
||||
// can see the shard; for a registered node the node's own dc/rack win.
|
||||
func (a *TopologyAnalysis) AddShardLocation(loc ShardLocation) {
|
||||
node, ok := a.AllNodes[loc.NodeID]
|
||||
if !ok {
|
||||
node = &TopologyNode{NodeID: loc.NodeID, DataCenter: loc.DataCenter, Rack: loc.Rack}
|
||||
a.AddNode(node)
|
||||
}
|
||||
if contains(a.NodeToShards[loc.NodeID], loc.ShardID) {
|
||||
return
|
||||
}
|
||||
a.ShardsByDC[node.DataCenter]++
|
||||
a.ShardsByRack[rackKey(node.DataCenter, node.Rack)]++
|
||||
a.ShardsByNode[loc.NodeID]++
|
||||
a.DCToShards[node.DataCenter] = append(a.DCToShards[node.DataCenter], loc.ShardID)
|
||||
a.RackToShards[rackKey(node.DataCenter, node.Rack)] = append(a.RackToShards[rackKey(node.DataCenter, node.Rack)], loc.ShardID)
|
||||
a.NodeToShards[loc.NodeID] = append(a.NodeToShards[loc.NodeID], loc.ShardID)
|
||||
a.TotalShards++
|
||||
if !contains(node.ShardIDs, loc.ShardID) {
|
||||
node.ShardIDs = append(node.ShardIDs, loc.ShardID)
|
||||
}
|
||||
}
|
||||
|
||||
// rackKey qualifies a rack name with its data center: rack names are only
|
||||
// unique within a DC, so two DCs can both hold a "rack1". NUL separates the
|
||||
// parts so a "/" inside either name cannot merge distinct racks.
|
||||
func rackKey(dc, rack string) string {
|
||||
return dc + "\x00" + rack
|
||||
}
|
||||
|
||||
// Finalize computes topology statistics after all nodes and shards are added.
|
||||
func (a *TopologyAnalysis) Finalize() {
|
||||
a.TotalNodes = len(a.AllNodes)
|
||||
a.TotalRacks = len(a.RackToNodes)
|
||||
a.TotalDCs = len(a.DCToRacks)
|
||||
}
|
||||
|
||||
func contains[T comparable](list []T, s T) bool {
|
||||
for _, item := range list {
|
||||
if item == s {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ShardLocation represents where a shard is located in the topology
|
||||
type ShardLocation struct {
|
||||
ShardID int
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
// Package distribution provides EC shard distribution algorithms with configurable EC ratios.
|
||||
package distribution
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
)
|
||||
|
||||
// ECConfig holds erasure coding configuration parameters.
|
||||
// This replaces hard-coded constants like DataShardsCount=10, ParityShardsCount=4.
|
||||
type ECConfig struct {
|
||||
@@ -17,3 +25,76 @@ type ReplicationConfig struct {
|
||||
// Original replication string (for logging/debugging)
|
||||
Original string
|
||||
}
|
||||
|
||||
// NewECConfig creates an erasure coding configuration with the given shard counts.
|
||||
func NewECConfig(dataShards, parityShards int) (ECConfig, error) {
|
||||
if dataShards < 1 || parityShards < 1 {
|
||||
return ECConfig{}, fmt.Errorf("data and parity shard counts must be positive, got %d+%d", dataShards, parityShards)
|
||||
}
|
||||
return ECConfig{DataShards: dataShards, ParityShards: parityShards}, nil
|
||||
}
|
||||
|
||||
// DefaultECConfig returns the standard 10+4 erasure coding configuration.
|
||||
func DefaultECConfig() ECConfig {
|
||||
return ECConfig{DataShards: erasure_coding.DataShardsCount, ParityShards: erasure_coding.ParityShardsCount}
|
||||
}
|
||||
|
||||
// NewReplicationConfig parses a replication policy string like "110".
|
||||
func NewReplicationConfigFromString(s string) (ReplicationConfig, error) {
|
||||
rp, err := super_block.NewReplicaPlacementFromString(s)
|
||||
if err != nil {
|
||||
return ReplicationConfig{}, err
|
||||
}
|
||||
return NewReplicationConfig(rp), nil
|
||||
}
|
||||
|
||||
// NewReplicationConfig converts a replica placement into a replication config.
|
||||
func NewReplicationConfig(rp *super_block.ReplicaPlacement) ReplicationConfig {
|
||||
if rp == nil {
|
||||
rp = &super_block.ReplicaPlacement{}
|
||||
}
|
||||
return ReplicationConfig{
|
||||
MinDataCenters: rp.DiffDataCenterCount + 1,
|
||||
MinRacksPerDC: rp.DiffRackCount + 1,
|
||||
MinNodesPerRack: rp.SameRackCount + 1,
|
||||
Original: rp.String(),
|
||||
}
|
||||
}
|
||||
|
||||
// TotalShards returns the number of shards each volume splits into.
|
||||
func (ec ECConfig) TotalShards() int {
|
||||
return ec.DataShards + ec.ParityShards
|
||||
}
|
||||
|
||||
// CanLoseShards returns how many shards of a volume can be missing before the
|
||||
// volume is no longer readable.
|
||||
func (ec ECConfig) CanLoseShards() int {
|
||||
return ec.ParityShards
|
||||
}
|
||||
|
||||
// IsDataShard reports whether the shard id is a data shard, which serves reads.
|
||||
func (ec ECConfig) IsDataShard(shardID int) bool {
|
||||
return shardID >= 0 && shardID < ec.DataShards
|
||||
}
|
||||
|
||||
// IsParityShard reports whether the shard id is a parity shard, which is only
|
||||
// used for reconstruction.
|
||||
func (ec ECConfig) IsParityShard(shardID int) bool {
|
||||
return shardID >= ec.DataShards && shardID < ec.TotalShards()
|
||||
}
|
||||
|
||||
// SortShardsDataFirst orders shard ids so data shards come before parity
|
||||
// shards, for initial placement.
|
||||
func (ec ECConfig) SortShardsDataFirst(shards []int) []int {
|
||||
sorted := append([]int(nil), shards...)
|
||||
sort.Ints(sorted)
|
||||
return sorted
|
||||
}
|
||||
|
||||
// SortShardsParityFirst orders shard ids so parity shards come before data
|
||||
// shards, for picking which shards to move away first when rebalancing.
|
||||
func (ec ECConfig) SortShardsParityFirst(shards []int) []int {
|
||||
sorted := append([]int(nil), shards...)
|
||||
sort.Sort(sort.Reverse(sort.IntSlice(sorted)))
|
||||
return sorted
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
package distribution
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ECDistribution represents the target distribution of EC shards
|
||||
// based on EC configuration and replication policy.
|
||||
type ECDistribution struct {
|
||||
@@ -20,3 +25,97 @@ type ECDistribution struct {
|
||||
MaxShardsPerRack int
|
||||
MaxShardsPerNode int
|
||||
}
|
||||
|
||||
// CalculateDistribution computes the balanced shard counts each topology level
|
||||
// should hold for the given EC ratio spread over the minimum topology the
|
||||
// replication policy describes.
|
||||
func CalculateDistribution(ec ECConfig, rep ReplicationConfig) *ECDistribution {
|
||||
total := ec.TotalShards()
|
||||
rep.MinDataCenters = max(rep.MinDataCenters, 1)
|
||||
rep.MinRacksPerDC = max(rep.MinRacksPerDC, 1)
|
||||
rep.MinNodesPerRack = max(rep.MinNodesPerRack, 1)
|
||||
dcUnits := rep.MinDataCenters
|
||||
rackUnits := dcUnits * rep.MinRacksPerDC
|
||||
nodeUnits := rackUnits * rep.MinNodesPerRack
|
||||
return &ECDistribution{
|
||||
ECConfig: ec,
|
||||
ReplicationConfig: rep,
|
||||
TargetShardsPerDC: evenShare(total, dcUnits),
|
||||
TargetShardsPerRack: evenShare(total, rackUnits),
|
||||
TargetShardsPerNode: evenShare(total, nodeUnits),
|
||||
MaxShardsPerDC: maxShare(total, dcUnits, ec.CanLoseShards()),
|
||||
MaxShardsPerRack: maxShare(total, rackUnits, ec.CanLoseShards()),
|
||||
MaxShardsPerNode: maxShare(total, nodeUnits, ec.CanLoseShards()),
|
||||
}
|
||||
}
|
||||
|
||||
// evenShare is the balanced shard count per unit at one topology level.
|
||||
func evenShare(total, units int) int {
|
||||
return ceilDivide(total, units)
|
||||
}
|
||||
|
||||
// maxShare bounds how many shards a single failure domain may hold: the even
|
||||
// share plus the slack that would pad the total to the next multiple of the
|
||||
// unit count. When the even share is survivable on its own, the loss budget
|
||||
// caps the bound so the fault tolerance report stays true even at the max.
|
||||
func maxShare(total, units, lossBudget int) int {
|
||||
if units < 1 {
|
||||
units = 1
|
||||
}
|
||||
m := ceilDivide(total, units) + units - total%units
|
||||
if m > total {
|
||||
m = total
|
||||
}
|
||||
if evenShare(total, units) <= lossBudget && m > lossBudget {
|
||||
m = lossBudget
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func ceilDivide(a, b int) int {
|
||||
if b < 1 {
|
||||
return a
|
||||
}
|
||||
return (a + b - 1) / b
|
||||
}
|
||||
|
||||
// Summary describes the distribution plan in human-readable form.
|
||||
func (d *ECDistribution) Summary() string {
|
||||
var sb strings.Builder
|
||||
ec := d.ECConfig
|
||||
rep := d.ReplicationConfig
|
||||
fmt.Fprintf(&sb, "EC Configuration: %d+%d (total: %d, can lose: %d)\n",
|
||||
ec.DataShards, ec.ParityShards, ec.TotalShards(), ec.CanLoseShards())
|
||||
fmt.Fprintf(&sb, "Replication: replication=%s (DCs:%d, Racks/DC:%d, Nodes/Rack:%d)\n",
|
||||
rep.Original, rep.MinDataCenters, rep.MinRacksPerDC, rep.MinNodesPerRack)
|
||||
sb.WriteString("Distribution Plan:\n")
|
||||
fmt.Fprintf(&sb, " Data Centers: %d (target %d shards each, max %d)\n",
|
||||
rep.MinDataCenters, d.TargetShardsPerDC, d.MaxShardsPerDC)
|
||||
fmt.Fprintf(&sb, " Racks per DC: %d (target %d shards each, max %d)\n",
|
||||
rep.MinRacksPerDC, d.TargetShardsPerRack, d.MaxShardsPerRack)
|
||||
fmt.Fprintf(&sb, " Nodes per Rack: %d (target %d shards each, max %d)\n",
|
||||
rep.MinNodesPerRack, d.TargetShardsPerNode, d.MaxShardsPerNode)
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// FaultToleranceAnalysis reports whether losing one unit at each topology
|
||||
// level still leaves enough shards to reconstruct the volume.
|
||||
func (d *ECDistribution) FaultToleranceAnalysis() string {
|
||||
var sb strings.Builder
|
||||
ec := d.ECConfig
|
||||
fmt.Fprintf(&sb, "Fault Tolerance Analysis for %d+%d:\n", ec.DataShards, ec.ParityShards)
|
||||
writeLevel := func(name string, target int) {
|
||||
remaining := ec.TotalShards() - target
|
||||
status := "SURVIVABLE ✓"
|
||||
if remaining < ec.DataShards {
|
||||
status = "NOT SURVIVABLE ✗"
|
||||
}
|
||||
fmt.Fprintf(&sb, " %s Failure: %s\n", name, status)
|
||||
fmt.Fprintf(&sb, " - Losing one %s loses ~%d shards\n", name, target)
|
||||
fmt.Fprintf(&sb, " - Remaining: %d shards (need %d)\n", remaining, ec.DataShards)
|
||||
}
|
||||
writeLevel("DC", d.TargetShardsPerDC)
|
||||
writeLevel("Rack", d.TargetShardsPerRack)
|
||||
writeLevel("Node", d.TargetShardsPerNode)
|
||||
return sb.String()
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
package distribution
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDefaultECConfig(t *testing.T) {
|
||||
ec := DefaultECConfig()
|
||||
assert.Equal(t, 10, ec.DataShards)
|
||||
assert.Equal(t, 4, ec.ParityShards)
|
||||
assert.Equal(t, 14, ec.TotalShards())
|
||||
assert.Equal(t, 4, ec.CanLoseShards())
|
||||
assert.True(t, ec.IsDataShard(0))
|
||||
assert.True(t, ec.IsDataShard(9))
|
||||
assert.False(t, ec.IsDataShard(10))
|
||||
assert.True(t, ec.IsParityShard(13))
|
||||
assert.False(t, ec.IsParityShard(14))
|
||||
assert.Equal(t, []int{0, 1, 10, 11}, ec.SortShardsDataFirst([]int{11, 1, 10, 0}))
|
||||
assert.Equal(t, []int{13, 12, 2, 1}, ec.SortShardsParityFirst([]int{2, 13, 1, 12}))
|
||||
}
|
||||
|
||||
func TestNewECConfig(t *testing.T) {
|
||||
ec, err := NewECConfig(8, 4)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 12, ec.TotalShards())
|
||||
|
||||
for _, bad := range [][2]int{{0, 4}, {8, 0}, {-1, 4}} {
|
||||
_, err := NewECConfig(bad[0], bad[1])
|
||||
assert.Error(t, err, "config %v must be rejected", bad)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewReplicationConfigFromString(t *testing.T) {
|
||||
rep, err := NewReplicationConfigFromString("110")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 2, rep.MinDataCenters)
|
||||
assert.Equal(t, 2, rep.MinRacksPerDC)
|
||||
assert.Equal(t, 1, rep.MinNodesPerRack)
|
||||
assert.Equal(t, "110", rep.Original)
|
||||
|
||||
rep, err = NewReplicationConfigFromString("000")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, rep.MinDataCenters)
|
||||
assert.Equal(t, 1, rep.MinRacksPerDC)
|
||||
assert.Equal(t, 1, rep.MinNodesPerRack)
|
||||
|
||||
_, err = NewReplicationConfigFromString("abc")
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestCalculateDistribution(t *testing.T) {
|
||||
rep, err := NewReplicationConfigFromString("110")
|
||||
require.NoError(t, err)
|
||||
dist := CalculateDistribution(DefaultECConfig(), rep)
|
||||
|
||||
assert.Equal(t, 7, dist.TargetShardsPerDC)
|
||||
assert.Equal(t, 4, dist.TargetShardsPerRack)
|
||||
assert.Equal(t, 4, dist.TargetShardsPerNode)
|
||||
assert.Equal(t, 9, dist.MaxShardsPerDC)
|
||||
assert.Equal(t, 4, dist.MaxShardsPerRack)
|
||||
assert.Equal(t, 4, dist.MaxShardsPerNode)
|
||||
|
||||
expected := "EC Configuration: 10+4 (total: 14, can lose: 4)\n" +
|
||||
"Replication: replication=110 (DCs:2, Racks/DC:2, Nodes/Rack:1)\n" +
|
||||
"Distribution Plan:\n" +
|
||||
" Data Centers: 2 (target 7 shards each, max 9)\n" +
|
||||
" Racks per DC: 2 (target 4 shards each, max 4)\n" +
|
||||
" Nodes per Rack: 1 (target 4 shards each, max 4)\n"
|
||||
assert.Equal(t, expected, dist.Summary())
|
||||
}
|
||||
|
||||
// The reported max may not exceed the loss budget at a survivable level:
|
||||
// 8+4 over "200" lets a domain drift to 7 of 12 shards, but losing that domain
|
||||
// would leave 5 < 8 — capping the max at the budget keeps SURVIVABLE true.
|
||||
func TestCalculateDistributionMaxWithinLossBudget(t *testing.T) {
|
||||
ec, err := NewECConfig(8, 4)
|
||||
require.NoError(t, err)
|
||||
rep, err := NewReplicationConfigFromString("200")
|
||||
require.NoError(t, err)
|
||||
dist := CalculateDistribution(ec, rep)
|
||||
|
||||
assert.Equal(t, 4, dist.TargetShardsPerDC)
|
||||
assert.Equal(t, 4, dist.MaxShardsPerDC)
|
||||
assert.Equal(t, 4, dist.MaxShardsPerRack)
|
||||
assert.Equal(t, 4, dist.MaxShardsPerNode)
|
||||
|
||||
// a level whose even share already exceeds the budget keeps the slack bound
|
||||
dist = CalculateDistribution(DefaultECConfig(), rep)
|
||||
assert.Equal(t, 6, dist.MaxShardsPerDC) // even 5 > 4: DC loss is not survivable anyway
|
||||
}
|
||||
|
||||
func TestCalculateDistributionSingleDomain(t *testing.T) {
|
||||
rep, err := NewReplicationConfigFromString("000")
|
||||
require.NoError(t, err)
|
||||
dist := CalculateDistribution(DefaultECConfig(), rep)
|
||||
assert.Equal(t, 14, dist.TargetShardsPerDC)
|
||||
assert.Equal(t, 14, dist.MaxShardsPerDC)
|
||||
}
|
||||
|
||||
func TestFaultToleranceAnalysis(t *testing.T) {
|
||||
ec, err := NewECConfig(8, 4)
|
||||
require.NoError(t, err)
|
||||
rep, err := NewReplicationConfigFromString("200")
|
||||
require.NoError(t, err)
|
||||
dist := CalculateDistribution(ec, rep)
|
||||
|
||||
analysis := dist.FaultToleranceAnalysis()
|
||||
assert.Contains(t, analysis, "Fault Tolerance Analysis for 8+4:")
|
||||
assert.Contains(t, analysis, "DC Failure: SURVIVABLE")
|
||||
assert.Contains(t, analysis, "- Losing one DC loses ~4 shards")
|
||||
assert.Contains(t, analysis, "- Remaining: 8 shards (need 8)")
|
||||
}
|
||||
|
||||
func TestFaultToleranceAnalysisNotSurvivable(t *testing.T) {
|
||||
rep, err := NewReplicationConfigFromString("000")
|
||||
require.NoError(t, err)
|
||||
dist := CalculateDistribution(DefaultECConfig(), rep)
|
||||
analysis := dist.FaultToleranceAnalysis()
|
||||
assert.Contains(t, analysis, "DC Failure: NOT SURVIVABLE")
|
||||
assert.Contains(t, analysis, "Rack Failure: NOT SURVIVABLE")
|
||||
assert.Contains(t, analysis, "Node Failure: NOT SURVIVABLE")
|
||||
}
|
||||
|
||||
func makeNode(id, dc, rack string, freeSlots int, shards ...int) *TopologyNode {
|
||||
return &TopologyNode{NodeID: id, DataCenter: dc, Rack: rack, FreeSlots: freeSlots, ShardIDs: shards}
|
||||
}
|
||||
|
||||
func TestTopologyAnalysis(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("n1", "dc1", "r1", 5, 0, 1))
|
||||
a.AddNode(makeNode("n2", "dc1", "r1", 5, 2))
|
||||
a.AddNode(makeNode("n3", "dc2", "r2", 5))
|
||||
a.Finalize()
|
||||
|
||||
assert.Equal(t, 3, a.TotalShards)
|
||||
assert.Equal(t, 3, a.TotalNodes)
|
||||
assert.Equal(t, 2, a.TotalRacks)
|
||||
assert.Equal(t, 2, a.TotalDCs)
|
||||
assert.Equal(t, 3, a.ShardsByDC["dc1"])
|
||||
assert.Equal(t, 0, a.ShardsByDC["dc2"])
|
||||
assert.Equal(t, []string{"r1"}, a.DCToRacks["dc1"])
|
||||
assert.Equal(t, []int{0, 1, 2}, a.RackToShards[rackKey("dc1", "r1")])
|
||||
}
|
||||
|
||||
// A node registered twice must still count once in rack and shard totals.
|
||||
func TestTopologyAnalysisDuplicateNode(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("n1", "dc1", "r1", 5, 0, 1))
|
||||
a.AddNode(makeNode("n1", "dc1", "r1", 5, 0, 1))
|
||||
a.Finalize()
|
||||
|
||||
assert.Equal(t, 1, a.TotalNodes)
|
||||
assert.Len(t, a.RackToNodes[rackKey("dc1", "r1")], 1)
|
||||
assert.Equal(t, 2, a.ShardsByNode["n1"])
|
||||
}
|
||||
|
||||
// A node auto-registered by a shard location gets its real capacity when the
|
||||
// node itself registers later, plus any shards the location did not mention.
|
||||
func TestTopologyAnalysisNodeCapacityLateRegistration(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddShardLocation(ShardLocation{ShardID: 0, NodeID: "n1", DataCenter: "dc1", Rack: "r1"})
|
||||
a.AddNode(makeNode("n1", "dc1", "r1", 10, 1))
|
||||
a.Finalize()
|
||||
|
||||
assert.Equal(t, 10, a.AllNodes["n1"].FreeSlots)
|
||||
assert.Equal(t, []int{0, 1}, a.AllNodes["n1"].ShardIDs)
|
||||
assert.Equal(t, 2, a.ShardsByNode["n1"])
|
||||
assert.Len(t, a.RackToNodes[rackKey("dc1", "r1")], 1)
|
||||
}
|
||||
|
||||
// Shards may be registered either through TopologyNode.ShardIDs or through
|
||||
// AddShardLocation — both must leave the node holding the shards.
|
||||
func TestTopologyAnalysisAddShardLocation(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("n1", "dc1", "r1", 5))
|
||||
a.AddShardLocation(ShardLocation{ShardID: 0, NodeID: "n1", DataCenter: "dc1", Rack: "r1"})
|
||||
a.AddShardLocation(ShardLocation{ShardID: 1, NodeID: "n1", DataCenter: "dc1", Rack: "r1"})
|
||||
a.AddShardLocation(ShardLocation{ShardID: 1, NodeID: "n1", DataCenter: "dc1", Rack: "r1"})
|
||||
a.Finalize()
|
||||
|
||||
assert.Equal(t, 2, a.TotalShards)
|
||||
assert.Equal(t, 2, a.ShardsByNode["n1"])
|
||||
assert.Equal(t, []int{0, 1}, a.AllNodes["n1"].ShardIDs)
|
||||
}
|
||||
|
||||
// Rack names are only unique within a DC, so dc1/rack1 and dc2/rack1 are
|
||||
// distinct domains.
|
||||
func TestTopologyAnalysisSameRackNameAcrossDCs(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("n1", "dc1", "rack1", 5, 0, 1))
|
||||
a.AddNode(makeNode("n2", "dc2", "rack1", 5, 2))
|
||||
a.Finalize()
|
||||
|
||||
assert.Equal(t, 2, a.TotalDCs)
|
||||
assert.Equal(t, 2, a.TotalRacks)
|
||||
assert.Equal(t, 2, a.ShardsByRack[rackKey("dc1", "rack1")])
|
||||
assert.Equal(t, 1, a.ShardsByRack[rackKey("dc2", "rack1")])
|
||||
}
|
||||
|
||||
// A "/" inside a data-center or rack name must not merge distinct racks.
|
||||
func TestTopologyAnalysisSlashInNames(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("n1", "a", "b/c", 5, 0))
|
||||
a.AddNode(makeNode("n2", "a/b", "c", 5, 1))
|
||||
a.Finalize()
|
||||
|
||||
assert.Equal(t, 2, a.TotalRacks)
|
||||
assert.Equal(t, 1, a.ShardsByRack[rackKey("a", "b/c")])
|
||||
assert.Equal(t, 1, a.ShardsByRack[rackKey("a/b", "c")])
|
||||
}
|
||||
|
||||
func TestPlanRebalanceAcrossDCs(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("a1", "dcA", "rA1", 10, 0, 1, 2, 3))
|
||||
a.AddNode(makeNode("a2", "dcA", "rA2", 10, 4, 5, 6, 7))
|
||||
a.AddNode(makeNode("a3", "dcA", "rA3", 10, 8, 9, 10, 11))
|
||||
a.AddNode(makeNode("a4", "dcA", "rA4", 10, 12, 13))
|
||||
a.AddNode(makeNode("b1", "dcB", "rB1", 10))
|
||||
a.AddNode(makeNode("b2", "dcB", "rB2", 10))
|
||||
a.Finalize()
|
||||
|
||||
rep, err := NewReplicationConfigFromString("110")
|
||||
require.NoError(t, err)
|
||||
plan, err := NewRebalancer(DefaultECConfig(), rep).PlanRebalance(a)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, 7, plan.MovesAcrossDC)
|
||||
assert.Equal(t, 7, plan.Analysis.ShardsByDC["dcA"])
|
||||
assert.Equal(t, 7, plan.Analysis.ShardsByDC["dcB"])
|
||||
|
||||
// the given analysis still describes the un-moved layout
|
||||
assert.Equal(t, 14, a.ShardsByDC["dcA"])
|
||||
assert.Equal(t, 0, a.ShardsByDC["dcB"])
|
||||
assert.Equal(t, []int{0, 1, 2, 3}, a.AllNodes["a1"].ShardIDs)
|
||||
|
||||
// parity shards (10-13) move before data shards
|
||||
assert.True(t, plan.Moves[0].ShardID >= 10)
|
||||
assert.Equal(t, "b1", plan.Moves[0].DestNode.NodeID)
|
||||
}
|
||||
|
||||
func TestPlanRebalanceAcrossRacks(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("n1", "dc1", "r1", 10, 0, 1, 2, 3))
|
||||
a.AddNode(makeNode("n2", "dc1", "r2", 10))
|
||||
a.Finalize()
|
||||
|
||||
rep, err := NewReplicationConfigFromString("110")
|
||||
require.NoError(t, err)
|
||||
plan, err := NewRebalancer(DefaultECConfig(), rep).PlanRebalance(a)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, 2, plan.TotalMoves)
|
||||
assert.Equal(t, 2, plan.MovesAcrossRack)
|
||||
assert.Equal(t, 2, plan.Analysis.ShardsByRack[rackKey("dc1", "r1")])
|
||||
assert.Equal(t, 2, plan.Analysis.ShardsByRack[rackKey("dc1", "r2")])
|
||||
// parity-first ordering: shards 3 then 2 move out of r1
|
||||
assert.Equal(t, 3, plan.Moves[0].ShardID)
|
||||
assert.Equal(t, 2, plan.Moves[1].ShardID)
|
||||
}
|
||||
|
||||
func TestPlanRebalanceWithinRack(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("n1", "dc1", "r1", 10, 0, 1, 2, 3))
|
||||
a.AddNode(makeNode("n2", "dc1", "r1", 10))
|
||||
a.Finalize()
|
||||
|
||||
rep, err := NewReplicationConfigFromString("001")
|
||||
require.NoError(t, err)
|
||||
plan, err := NewRebalancer(DefaultECConfig(), rep).PlanRebalance(a)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, 2, plan.TotalMoves)
|
||||
assert.Equal(t, 2, plan.MovesWithinRack)
|
||||
assert.Equal(t, 2, plan.Analysis.ShardsByNode["n1"])
|
||||
assert.Equal(t, 2, plan.Analysis.ShardsByNode["n2"])
|
||||
assert.Equal(t, []int{3, 2}, plan.Analysis.AllNodes["n2"].ShardIDs)
|
||||
assert.Equal(t, []int{0, 1, 2, 3}, a.AllNodes["n1"].ShardIDs)
|
||||
}
|
||||
|
||||
func TestPlanRebalanceRespectsFreeSlots(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("n1", "dc1", "r1", 10, 0, 1, 2, 3))
|
||||
a.AddNode(makeNode("n2", "dc1", "r1", 1))
|
||||
a.Finalize()
|
||||
|
||||
plan, err := NewRebalancer(DefaultECConfig(), ReplicationConfig{MinDataCenters: 1, MinRacksPerDC: 1, MinNodesPerRack: 2}).PlanRebalance(a)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, 1, plan.TotalMoves, "only one slot is free on the destination")
|
||||
assert.Equal(t, 3, plan.Analysis.ShardsByNode["n1"])
|
||||
assert.Equal(t, 1, plan.Analysis.ShardsByNode["n2"])
|
||||
assert.Equal(t, 0, plan.Analysis.AllNodes["n2"].FreeSlots)
|
||||
assert.Equal(t, 1, a.AllNodes["n2"].FreeSlots)
|
||||
}
|
||||
|
||||
func TestPlanRebalanceNoopWhenBalanced(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("n1", "dc1", "r1", 10, 0, 1))
|
||||
a.AddNode(makeNode("n2", "dc1", "r1", 10, 2, 3))
|
||||
a.Finalize()
|
||||
|
||||
plan, err := NewRebalancer(DefaultECConfig(), ReplicationConfig{MinDataCenters: 1, MinRacksPerDC: 1, MinNodesPerRack: 2}).PlanRebalance(a)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, plan.TotalMoves)
|
||||
}
|
||||
|
||||
func TestPlanRebalanceNilAnalysis(t *testing.T) {
|
||||
_, err := NewRebalancer(DefaultECConfig(), ReplicationConfig{}).PlanRebalance(nil)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
// Node balancing inside a rack must aim for the rack's count after
|
||||
// DC- and rack-level moves, not the count the rack started with.
|
||||
func TestPlanRebalanceNodeTargetAfterMoves(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("n1", "dc1", "r1", 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))
|
||||
a.AddNode(makeNode("n2", "dc1", "r1", 10))
|
||||
a.AddNode(makeNode("n3", "dc1", "r2", 10))
|
||||
a.Finalize()
|
||||
|
||||
rep, err := NewReplicationConfigFromString("010")
|
||||
require.NoError(t, err)
|
||||
plan, err := NewRebalancer(DefaultECConfig(), rep).PlanRebalance(a)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, 7, plan.Analysis.ShardsByRack[rackKey("dc1", "r1")])
|
||||
assert.Equal(t, 7, plan.Analysis.ShardsByRack[rackKey("dc1", "r2")])
|
||||
assert.Equal(t, 4, plan.Analysis.ShardsByNode["n1"])
|
||||
assert.Equal(t, 3, plan.Analysis.ShardsByNode["n2"])
|
||||
assert.Equal(t, []int{0, 1, 2, 3}, plan.Analysis.AllNodes["n1"].ShardIDs)
|
||||
assert.Equal(t, []int{6, 5, 4}, plan.Analysis.AllNodes["n2"].ShardIDs)
|
||||
}
|
||||
|
||||
// A shard that already has a copy anywhere in the destination domain must not
|
||||
// be moved there again — the second copy adds no redundancy.
|
||||
func TestPlanRebalanceNoDuplicateShardInDomain(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("a1", "dcA", "rA1", 10, 0, 1, 2, 3))
|
||||
a.AddNode(makeNode("b1", "dcB", "rB1", 10, 3))
|
||||
a.AddNode(makeNode("b2", "dcB", "rB2", 10))
|
||||
a.Finalize()
|
||||
|
||||
rep, err := NewReplicationConfigFromString("100")
|
||||
require.NoError(t, err)
|
||||
plan, err := NewRebalancer(DefaultECConfig(), rep).PlanRebalance(a)
|
||||
require.NoError(t, err)
|
||||
|
||||
// dcA holds 4, dcB holds 1, target 3 each: one move, and it cannot be shard 3
|
||||
require.Len(t, plan.Moves, 1)
|
||||
assert.Equal(t, 2, plan.Moves[0].ShardID)
|
||||
assert.Equal(t, []int{2}, plan.Analysis.AllNodes["b2"].ShardIDs)
|
||||
assert.Equal(t, []int{3}, plan.Analysis.AllNodes["b1"].ShardIDs)
|
||||
}
|
||||
|
||||
// Shard locations may be registered without registering the node first; the
|
||||
// rebalancer must still see the shard, counted under the node's own dc/rack.
|
||||
func TestPlanRebalanceShardForUnregisteredNode(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddShardLocation(ShardLocation{ShardID: 0, NodeID: "n1", DataCenter: "dc1", Rack: "r1"})
|
||||
a.AddShardLocation(ShardLocation{ShardID: 1, NodeID: "n1", DataCenter: "dc1", Rack: "r1"})
|
||||
a.AddNode(makeNode("n2", "dc1", "r1", 10))
|
||||
a.Finalize()
|
||||
|
||||
assert.Equal(t, 1, a.TotalDCs)
|
||||
assert.Equal(t, 2, a.ShardsByNode["n1"])
|
||||
assert.Equal(t, []int{0, 1}, a.AllNodes["n1"].ShardIDs)
|
||||
|
||||
plan, err := NewRebalancer(DefaultECConfig(), ReplicationConfig{MinDataCenters: 1, MinRacksPerDC: 1, MinNodesPerRack: 2}).PlanRebalance(a)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, plan.TotalMoves)
|
||||
assert.Equal(t, 1, plan.Analysis.ShardsByNode["n1"])
|
||||
assert.Equal(t, 1, plan.Analysis.ShardsByNode["n2"])
|
||||
}
|
||||
|
||||
// When the most overloaded domain can only offer duplicates, balancing must
|
||||
// fall through to the next overloaded source rather than stop.
|
||||
func TestPlanRebalanceSkipsBlockedSource(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("a1", "dcA", "rA", 10, 0, 1, 2, 3))
|
||||
a.AddNode(makeNode("a2", "dcA", "rA", 10, 0, 1, 2, 3))
|
||||
a.AddNode(makeNode("a3", "dcA", "rA", 10, 0, 1, 2, 3))
|
||||
a.AddNode(makeNode("b1", "dcB", "rB", 10, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))
|
||||
a.AddNode(makeNode("c1", "dcC", "rC", 10, 0, 1, 2, 3))
|
||||
a.AddNode(makeNode("c2", "dcC", "rC", 10))
|
||||
a.AddNode(makeNode("d1", "dcD", "rD", 10, 0, 1, 2, 3))
|
||||
a.AddNode(makeNode("d2", "dcD", "rD", 10))
|
||||
a.Finalize()
|
||||
|
||||
plan, err := NewRebalancer(DefaultECConfig(), ReplicationConfig{MinDataCenters: 4, MinRacksPerDC: 1, MinNodesPerRack: 1}).PlanRebalance(a)
|
||||
require.NoError(t, err)
|
||||
|
||||
// dcA is stuck on duplicates (target 8), but dcB still sheds two shards
|
||||
assert.Equal(t, 12, plan.Analysis.ShardsByDC["dcA"])
|
||||
assert.Equal(t, 8, plan.Analysis.ShardsByDC["dcB"])
|
||||
assert.Equal(t, 5, plan.Analysis.ShardsByDC["dcC"])
|
||||
assert.Equal(t, 5, plan.Analysis.ShardsByDC["dcD"])
|
||||
}
|
||||
|
||||
// A shard that dc-level balancing lands on a node can be shed again at rack or
|
||||
// node level; its moves must collapse to one transfer to the final holder.
|
||||
func TestPlanRebalanceCollapsesChainedMoves(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("a1", "dcA", "rA", 20, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))
|
||||
a.AddNode(makeNode("b1", "dcB", "rB1", 20))
|
||||
a.AddNode(makeNode("c1", "dcB", "rB2", 20))
|
||||
a.AddNode(makeNode("c2", "dcB", "rB2", 20))
|
||||
a.AddNode(makeNode("c3", "dcB", "rB2", 20))
|
||||
a.Finalize()
|
||||
|
||||
rep, err := NewReplicationConfigFromString("100")
|
||||
require.NoError(t, err)
|
||||
plan, err := NewRebalancer(DefaultECConfig(), rep).PlanRebalance(a)
|
||||
require.NoError(t, err)
|
||||
|
||||
moved := make(map[int]string)
|
||||
for _, m := range plan.Moves {
|
||||
_, twice := moved[m.ShardID]
|
||||
assert.False(t, twice, "shard %d moves more than once", m.ShardID)
|
||||
moved[m.ShardID] = m.DestNode.NodeID
|
||||
assert.Contains(t, m.DestNode.ShardIDs, m.ShardID)
|
||||
}
|
||||
assert.Equal(t, 7, plan.TotalMoves)
|
||||
assert.Equal(t, 7, plan.MovesAcrossDC)
|
||||
// shard 12 reached b1 through c1 in simulation; the plan moves it directly
|
||||
assert.Equal(t, "b1", moved[12])
|
||||
assert.Equal(t, []int{13, 9, 12}, plan.Analysis.AllNodes["b1"].ShardIDs)
|
||||
}
|
||||
|
||||
// A collapsed move must not be scheduled before the departures that free its
|
||||
// destination: applying the plan in order may never target a full node.
|
||||
func TestPlanRebalanceMovesRespectSlots(t *testing.T) {
|
||||
ec, err := NewECConfig(20, 4)
|
||||
require.NoError(t, err)
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("a1", "dcA", "rA", 20, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))
|
||||
a.AddNode(makeNode("b1", "dcB", "rB1", 10))
|
||||
a.AddNode(makeNode("b2", "dcB", "rB1", 0, 20, 21, 22, 23))
|
||||
a.AddNode(makeNode("c1", "dcB", "rB2", 10, 17, 18, 19))
|
||||
a.Finalize()
|
||||
|
||||
rep, err := NewReplicationConfigFromString("100")
|
||||
require.NoError(t, err)
|
||||
plan, err := NewRebalancer(ec, rep).PlanRebalance(a)
|
||||
require.NoError(t, err)
|
||||
|
||||
free := make(map[string]int)
|
||||
for _, n := range a.AllNodes {
|
||||
free[n.NodeID] = n.FreeSlots
|
||||
}
|
||||
firstDeparture, firstArrival := -1, -1
|
||||
for i, m := range plan.Moves {
|
||||
assert.Greater(t, free[m.DestNode.NodeID], 0, "move %d targets a full node", i)
|
||||
free[m.DestNode.NodeID]--
|
||||
free[m.SourceNode.NodeID]++
|
||||
if m.DestNode.NodeID == "b2" && firstArrival < 0 {
|
||||
firstArrival = i
|
||||
}
|
||||
if m.SourceNode.NodeID == "b2" && firstDeparture < 0 {
|
||||
firstDeparture = i
|
||||
}
|
||||
}
|
||||
moved := make(map[int]string)
|
||||
for _, m := range plan.Moves {
|
||||
moved[m.ShardID] = m.DestNode.NodeID
|
||||
}
|
||||
// shard 16 reaches full-at-start b2 through b1; the plan moves it directly,
|
||||
// but only after the departures that free b2's slots
|
||||
assert.Equal(t, "b2", moved[16])
|
||||
assert.Equal(t, "c1", moved[23])
|
||||
assert.Greater(t, firstArrival, firstDeparture)
|
||||
}
|
||||
|
||||
func TestPlanRebalanceNoDuplicateShardOnNode(t *testing.T) {
|
||||
a := NewTopologyAnalysis()
|
||||
a.AddNode(makeNode("n1", "dc1", "r1", 10, 0, 1, 2, 3))
|
||||
a.AddNode(makeNode("n2", "dc1", "r1", 10, 3))
|
||||
a.Finalize()
|
||||
|
||||
plan, err := NewRebalancer(DefaultECConfig(), ReplicationConfig{MinDataCenters: 1, MinRacksPerDC: 1, MinNodesPerRack: 2}).PlanRebalance(a)
|
||||
require.NoError(t, err)
|
||||
|
||||
// n2 already holds 3, so the balancing move brings a different shard
|
||||
assert.Equal(t, 3, plan.Analysis.ShardsByNode["n1"])
|
||||
assert.Equal(t, 2, plan.Analysis.ShardsByNode["n2"])
|
||||
assert.Equal(t, []int{3, 2}, plan.Analysis.AllNodes["n2"].ShardIDs)
|
||||
for _, move := range plan.Moves {
|
||||
assert.NotContains(t, move.DestNode.ShardIDs[:len(move.DestNode.ShardIDs)-1], move.ShardID,
|
||||
"shard %d must not be moved onto a node already holding it", move.ShardID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalculateDistributionZeroReplication(t *testing.T) {
|
||||
dist := CalculateDistribution(DefaultECConfig(), ReplicationConfig{})
|
||||
assert.Equal(t, 14, dist.TargetShardsPerDC)
|
||||
assert.Contains(t, dist.Summary(), "Data Centers: 1")
|
||||
assert.NotPanics(t, func() { dist.FaultToleranceAnalysis() })
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
package distribution
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// ShardMove represents a planned shard move
|
||||
type ShardMove struct {
|
||||
ShardID int
|
||||
@@ -12,7 +17,7 @@ type ShardMove struct {
|
||||
type RebalancePlan struct {
|
||||
Moves []ShardMove
|
||||
Distribution *ECDistribution
|
||||
Analysis *TopologyAnalysis
|
||||
Analysis *TopologyAnalysis // simulated layout once every move applies; move endpoints reference its nodes
|
||||
|
||||
// Statistics
|
||||
TotalMoves int
|
||||
@@ -26,3 +31,305 @@ type Rebalancer struct {
|
||||
ecConfig ECConfig
|
||||
repConfig ReplicationConfig
|
||||
}
|
||||
|
||||
// NewRebalancer creates a rebalancer for the given EC ratio and replication policy.
|
||||
func NewRebalancer(ec ECConfig, rep ReplicationConfig) *Rebalancer {
|
||||
return &Rebalancer{ecConfig: ec, repConfig: rep}
|
||||
}
|
||||
|
||||
// PlanRebalance generates shard moves that bring the volume's shard layout to
|
||||
// the balanced distribution: first across data centers, then racks within each
|
||||
// data center, then nodes within each rack. Moves stop when source and
|
||||
// destination both reach their even share, or when destination nodes have no
|
||||
// free slots. The moves are planned on a copy of the topology, so the given
|
||||
// analysis still describes the cluster as it is; plan.Analysis shows the
|
||||
// layout the moves would produce.
|
||||
func (r *Rebalancer) PlanRebalance(analysis *TopologyAnalysis) (*RebalancePlan, error) {
|
||||
if analysis == nil {
|
||||
return nil, fmt.Errorf("cannot plan rebalancing without a topology analysis")
|
||||
}
|
||||
sim := NewTopologyAnalysis()
|
||||
for _, id := range sortedKeys(analysis.AllNodes) {
|
||||
node := *analysis.AllNodes[id]
|
||||
node.ShardIDs = append([]int(nil), node.ShardIDs...)
|
||||
sim.AddNode(&node)
|
||||
}
|
||||
sim.Finalize()
|
||||
plan := &RebalancePlan{
|
||||
Distribution: CalculateDistribution(r.ecConfig, r.repConfig),
|
||||
Analysis: sim,
|
||||
}
|
||||
|
||||
recordMove := func(shardID int, src, dst *TopologyNode, level, domain string) {
|
||||
src.ShardIDs = removeShard(src.ShardIDs, shardID)
|
||||
dst.ShardIDs = append(dst.ShardIDs, shardID)
|
||||
src.FreeSlots++
|
||||
dst.FreeSlots--
|
||||
sim.ShardsByDC[src.DataCenter]--
|
||||
sim.ShardsByDC[dst.DataCenter]++
|
||||
sim.ShardsByRack[rackKey(src.DataCenter, src.Rack)]--
|
||||
sim.ShardsByRack[rackKey(dst.DataCenter, dst.Rack)]++
|
||||
sim.ShardsByNode[src.NodeID]--
|
||||
sim.ShardsByNode[dst.NodeID]++
|
||||
sim.DCToShards[src.DataCenter] = removeShard(sim.DCToShards[src.DataCenter], shardID)
|
||||
sim.DCToShards[dst.DataCenter] = append(sim.DCToShards[dst.DataCenter], shardID)
|
||||
sim.RackToShards[rackKey(src.DataCenter, src.Rack)] = removeShard(sim.RackToShards[rackKey(src.DataCenter, src.Rack)], shardID)
|
||||
sim.RackToShards[rackKey(dst.DataCenter, dst.Rack)] = append(sim.RackToShards[rackKey(dst.DataCenter, dst.Rack)], shardID)
|
||||
sim.NodeToShards[src.NodeID] = removeShard(sim.NodeToShards[src.NodeID], shardID)
|
||||
sim.NodeToShards[dst.NodeID] = append(sim.NodeToShards[dst.NodeID], shardID)
|
||||
plan.Moves = append(plan.Moves, ShardMove{
|
||||
ShardID: shardID,
|
||||
SourceNode: src,
|
||||
DestNode: dst,
|
||||
Reason: fmt.Sprintf("%s balance: %s above target", level, domain),
|
||||
})
|
||||
}
|
||||
|
||||
moveOut := func(level, srcDomain string, srcNodes, dstNodes []*TopologyNode) bool {
|
||||
var shardIDs []int
|
||||
for _, n := range srcNodes {
|
||||
shardIDs = append(shardIDs, n.ShardIDs...)
|
||||
}
|
||||
for _, shardID := range r.ecConfig.SortShardsParityFirst(shardIDs) {
|
||||
var src *TopologyNode
|
||||
for _, n := range srcNodes {
|
||||
if contains(n.ShardIDs, shardID) {
|
||||
src = n
|
||||
break
|
||||
}
|
||||
}
|
||||
if src == nil {
|
||||
continue
|
||||
}
|
||||
// a shard already inside the destination domain gains nothing there
|
||||
duplicate := false
|
||||
for _, n := range dstNodes {
|
||||
if contains(n.ShardIDs, shardID) {
|
||||
duplicate = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if duplicate {
|
||||
continue
|
||||
}
|
||||
var dst *TopologyNode
|
||||
for _, n := range dstNodes {
|
||||
if n.FreeSlots > 0 && (dst == nil || nodeLess(n, dst)) {
|
||||
dst = n
|
||||
}
|
||||
}
|
||||
if dst == nil {
|
||||
continue
|
||||
}
|
||||
recordMove(shardID, src, dst, level, srcDomain)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// balance moves shards between domains of one level until every domain
|
||||
// holds at most its even share or no destination can take a shard. A
|
||||
// source that cannot shed any shard is set aside rather than stopping
|
||||
// the level, so other overloaded sources still get to move.
|
||||
balance := func(level string, domains []string, countOf func(string) int, target int, nodesOf func(string) []*TopologyNode, dstDomains func(string) []string) {
|
||||
blocked := make(map[string]bool)
|
||||
for {
|
||||
src := ""
|
||||
srcFound := false
|
||||
for _, d := range domains {
|
||||
if blocked[d] {
|
||||
continue
|
||||
}
|
||||
if countOf(d) > target && (!srcFound || countOf(d) > countOf(src)) {
|
||||
src, srcFound = d, true
|
||||
}
|
||||
}
|
||||
if !srcFound {
|
||||
return
|
||||
}
|
||||
dsts := append([]string(nil), dstDomains(src)...)
|
||||
sort.Slice(dsts, func(i, j int) bool {
|
||||
if countOf(dsts[i]) != countOf(dsts[j]) {
|
||||
return countOf(dsts[i]) < countOf(dsts[j])
|
||||
}
|
||||
return dsts[i] < dsts[j]
|
||||
})
|
||||
moved := false
|
||||
for _, dst := range dsts {
|
||||
if countOf(dst) < target && moveOut(level, src, nodesOf(src), nodesOf(dst)) {
|
||||
moved = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !moved {
|
||||
blocked[src] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dcList := sortedKeys(sim.DCToRacks)
|
||||
dcRackKeys := func(dc string) []string {
|
||||
racks := sim.DCToRacks[dc]
|
||||
keys := make([]string, 0, len(racks))
|
||||
for _, rack := range racks {
|
||||
keys = append(keys, rackKey(dc, rack))
|
||||
}
|
||||
return keys
|
||||
}
|
||||
totalShards := 0
|
||||
for _, dc := range dcList {
|
||||
totalShards += shardCount(dcRackKeys(dc), sim.RackToNodes)
|
||||
}
|
||||
dcCount := func(dc string) int { return shardCount(dcRackKeys(dc), sim.RackToNodes) }
|
||||
balance("dc", dcList, dcCount, ceilDivide(totalShards, len(dcList)),
|
||||
func(dc string) []*TopologyNode { return nodesOfRacks(dcRackKeys(dc), sim.RackToNodes) },
|
||||
func(string) []string { return dcList })
|
||||
|
||||
for _, dc := range dcList {
|
||||
racks := sim.DCToRacks[dc]
|
||||
rackCount := func(rack string) int { return shardCount([]string{rackKey(dc, rack)}, sim.RackToNodes) }
|
||||
balance("rack", racks, rackCount, ceilDivide(dcCount(dc), len(racks)),
|
||||
func(rack string) []*TopologyNode { return sim.RackToNodes[rackKey(dc, rack)] },
|
||||
func(string) []string { return racks })
|
||||
}
|
||||
|
||||
for _, rack := range sortedKeys(sim.RackToNodes) {
|
||||
nodes := sim.RackToNodes[rack]
|
||||
nodeCount := func(nodeID string) int {
|
||||
for _, n := range nodes {
|
||||
if n.NodeID == nodeID {
|
||||
return len(n.ShardIDs)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
nodeIDs := make([]string, 0, len(nodes))
|
||||
for _, n := range nodes {
|
||||
nodeIDs = append(nodeIDs, n.NodeID)
|
||||
}
|
||||
sort.Strings(nodeIDs)
|
||||
balance("node", nodeIDs, nodeCount, ceilDivide(shardCount([]string{rack}, sim.RackToNodes), len(nodes)),
|
||||
func(nodeID string) []*TopologyNode {
|
||||
for _, n := range nodes {
|
||||
if n.NodeID == nodeID {
|
||||
return []*TopologyNode{n}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
func(string) []string { return nodeIDs })
|
||||
}
|
||||
|
||||
// A copy of a shard moves at most once per level, and each finer level only
|
||||
// moves it deeper inside the domain the previous level sent it to, so its
|
||||
// moves form a chain from the first source to the final destination.
|
||||
// Collapse each chain into one transfer — intermediate hops would copy the
|
||||
// shard over the network only to move it again. Chains are keyed by where
|
||||
// the copy sits, so duplicate copies of a shard still move independently.
|
||||
pending := make(map[ShardLocation]int)
|
||||
moves := plan.Moves[:0]
|
||||
for _, m := range plan.Moves {
|
||||
key := ShardLocation{ShardID: m.ShardID, NodeID: m.SourceNode.NodeID}
|
||||
if i, ok := pending[key]; ok {
|
||||
delete(pending, key)
|
||||
moves[i].DestNode = m.DestNode
|
||||
pending[ShardLocation{ShardID: m.ShardID, NodeID: m.DestNode.NodeID}] = i
|
||||
continue
|
||||
}
|
||||
pending[ShardLocation{ShardID: m.ShardID, NodeID: m.DestNode.NodeID}] = len(moves)
|
||||
moves = append(moves, m)
|
||||
}
|
||||
// Order the collapsed moves so each destination has a free slot when its
|
||||
// move is applied: a chain's final destination may only gain a slot from a
|
||||
// later move's departure, so the early position the collapse kept can be
|
||||
// wrong. Emit every move whose destination has room first; a source gains
|
||||
// its slot back as soon as its move is emitted.
|
||||
free := make(map[string]int)
|
||||
for _, n := range sim.AllNodes {
|
||||
free[n.NodeID] = n.FreeSlots
|
||||
}
|
||||
for _, m := range moves {
|
||||
free[m.DestNode.NodeID]++
|
||||
free[m.SourceNode.NodeID]--
|
||||
}
|
||||
ordered := make([]ShardMove, 0, len(moves))
|
||||
for len(moves) > 0 {
|
||||
kept := moves[:0]
|
||||
for _, m := range moves {
|
||||
if free[m.DestNode.NodeID] > 0 {
|
||||
free[m.DestNode.NodeID]--
|
||||
free[m.SourceNode.NodeID]++
|
||||
ordered = append(ordered, m)
|
||||
} else {
|
||||
kept = append(kept, m)
|
||||
}
|
||||
}
|
||||
if len(kept) == len(moves) {
|
||||
ordered = append(ordered, kept...)
|
||||
break
|
||||
}
|
||||
moves = kept
|
||||
}
|
||||
plan.Moves = ordered
|
||||
for _, m := range ordered {
|
||||
switch {
|
||||
case m.SourceNode.DataCenter != m.DestNode.DataCenter:
|
||||
plan.MovesAcrossDC++
|
||||
case m.SourceNode.Rack != m.DestNode.Rack:
|
||||
plan.MovesAcrossRack++
|
||||
default:
|
||||
plan.MovesWithinRack++
|
||||
}
|
||||
}
|
||||
plan.TotalMoves = len(ordered)
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// nodeLess prefers the node holding fewer of the volume's shards, then the one
|
||||
// with more free slots, for a stable destination choice.
|
||||
func nodeLess(a, b *TopologyNode) bool {
|
||||
if len(a.ShardIDs) != len(b.ShardIDs) {
|
||||
return len(a.ShardIDs) < len(b.ShardIDs)
|
||||
}
|
||||
if a.FreeSlots != b.FreeSlots {
|
||||
return a.FreeSlots > b.FreeSlots
|
||||
}
|
||||
return a.NodeID < b.NodeID
|
||||
}
|
||||
|
||||
// shardCount sums the shards the given racks currently hold for the volume.
|
||||
func shardCount(racks []string, rackToNodes map[string][]*TopologyNode) int {
|
||||
total := 0
|
||||
for _, rack := range racks {
|
||||
for _, n := range rackToNodes[rack] {
|
||||
total += len(n.ShardIDs)
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
func nodesOfRacks(racks []string, rackToNodes map[string][]*TopologyNode) []*TopologyNode {
|
||||
var nodes []*TopologyNode
|
||||
for _, rack := range racks {
|
||||
nodes = append(nodes, rackToNodes[rack]...)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
func removeShard(shards []int, shardID int) []int {
|
||||
for i, s := range shards {
|
||||
if s == shardID {
|
||||
return append(shards[:i], shards[i+1:]...)
|
||||
}
|
||||
}
|
||||
return shards
|
||||
}
|
||||
|
||||
func sortedKeys[V any](m map[string]V) []string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
@@ -1341,12 +1341,8 @@ func (s *Store) MaybeAdjustVolumeMax() (hasChanges bool) {
|
||||
if diskLocation.OriginalMaxVolumeCount == 0 {
|
||||
currentMaxVolumeCount := atomic.LoadInt32(&diskLocation.MaxVolumeCount)
|
||||
diskStatus := stats.NewDiskStatus(diskLocation.Directory)
|
||||
var unusedSpace uint64 = 0
|
||||
unclaimedSpaces := int64(diskStatus.Free)
|
||||
if !s.GetPreallocate() {
|
||||
unusedSpace = diskLocation.UnUsedSpace(volumeSizeLimit)
|
||||
unclaimedSpaces -= int64(unusedSpace)
|
||||
}
|
||||
unusedSpace := diskLocation.UnUsedSpace(volumeSizeLimit)
|
||||
unclaimedSpaces := int64(diskStatus.Free) - int64(unusedSpace)
|
||||
volCount := diskLocation.VolumesLen()
|
||||
ecShardCount := diskLocation.EcShardCount()
|
||||
maxVolumeCount := int32(volCount) + int32((ecShardCount+erasure_coding.DataShardsCount-1)/erasure_coding.DataShardsCount)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
)
|
||||
|
||||
// A volume that was not preallocated keeps its remaining room reserved when
|
||||
// the master turns preallocation on, so it still takes a slot of the free space.
|
||||
func TestMaybeAdjustVolumeMaxReservesPlainVolumesWhilePreallocating(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
// Room for 2.5 volumes: the plain volume claims one, leaving one more slot.
|
||||
volumeSizeLimit := uint64(float64(stats.NewDiskStatus(dir).Free) / 2.5)
|
||||
if volumeSizeLimit == 0 {
|
||||
t.Skip("cannot determine free disk space")
|
||||
}
|
||||
|
||||
loc := &DiskLocation{Directory: dir, IdxDirectory: dir}
|
||||
loc.volumes = make(map[needle.VolumeId]*Volume)
|
||||
loc.SetVolume(1, &Volume{Id: 1, dir: dir, dirIdx: dir, DataBackend: &mockBackendStorageFile{}, nm: &mockNeedleMapper{}})
|
||||
s := &Store{Locations: []*DiskLocation{loc}}
|
||||
s.SetVolumeSizeLimit(volumeSizeLimit)
|
||||
s.SetPreallocate(true)
|
||||
|
||||
s.MaybeAdjustVolumeMax()
|
||||
|
||||
if loc.MaxVolumeCount != 2 {
|
||||
t.Errorf("MaxVolumeCount=%d; want 2", loc.MaxVolumeCount)
|
||||
}
|
||||
}
|
||||
@@ -34,10 +34,16 @@ func ReadSuperBlock(datBackend backend.BackendStorageFile) (superBlock SuperBloc
|
||||
if superBlock.ExtraSize > 0 {
|
||||
// read more
|
||||
extraData := make([]byte, int(superBlock.ExtraSize))
|
||||
if n, e := datBackend.ReadAt(extraData, SuperBlockSize); e != nil {
|
||||
if n != len(extraData) {
|
||||
err = fmt.Errorf("cannot read volume %s super block extra: %v", datBackend.Name(), e)
|
||||
return
|
||||
}
|
||||
}
|
||||
superBlock.Extra = &master_pb.SuperBlockExtra{}
|
||||
err = proto.Unmarshal(extraData, superBlock.Extra)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("cannot read volume %s super block extra: %v", datBackend.Name(), err)
|
||||
err = fmt.Errorf("cannot unmarshal volume %s super block extra: %v", datBackend.Name(), err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
package super_block
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
)
|
||||
|
||||
@@ -23,3 +31,114 @@ func TestSuperBlockReadWrite(t *testing.T) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestReadSuperBlockWithExtra(t *testing.T) {
|
||||
rp, _ := NewReplicaPlacementFromByte(byte(001))
|
||||
ttl, _ := needle.ReadTTL("15d")
|
||||
s := &SuperBlock{
|
||||
Version: needle.GetCurrentVersion(),
|
||||
ReplicaPlacement: rp,
|
||||
Ttl: ttl,
|
||||
Extra: &master_pb.SuperBlockExtra{
|
||||
ErasureCoding: &master_pb.SuperBlockExtra_ErasureCoding{
|
||||
Data: 10,
|
||||
Parity: 4,
|
||||
VolumeIds: []uint32{1, 2, 3},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
datPath := filepath.Join(t.TempDir(), "1.dat")
|
||||
if err := os.WriteFile(datPath, s.Bytes(), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := os.Open(datPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
datBackend := backend.NewDiskFile(f)
|
||||
defer datBackend.Close()
|
||||
|
||||
got, err := ReadSuperBlock(datBackend)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadSuperBlock: %v", err)
|
||||
}
|
||||
if got.ExtraSize != s.ExtraSize {
|
||||
t.Errorf("ExtraSize = %d, want %d", got.ExtraSize, s.ExtraSize)
|
||||
}
|
||||
if !proto.Equal(got.Extra, s.Extra) {
|
||||
t.Errorf("Extra = %v, want %v", got.Extra, s.Extra)
|
||||
}
|
||||
}
|
||||
|
||||
// io.ReaderAt may return io.EOF on a full read; a remote backend can pass that through.
|
||||
type eofBackendStorageFile struct {
|
||||
backend.DiskFile
|
||||
data []byte
|
||||
}
|
||||
|
||||
func (f *eofBackendStorageFile) ReadAt(p []byte, off int64) (n int, err error) {
|
||||
if off >= int64(len(f.data)) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
return copy(p, f.data[off:]), io.EOF
|
||||
}
|
||||
|
||||
func TestReadSuperBlockExtraFullReadWithEOF(t *testing.T) {
|
||||
rp, _ := NewReplicaPlacementFromByte(byte(001))
|
||||
ttl, _ := needle.ReadTTL("15d")
|
||||
s := &SuperBlock{
|
||||
Version: needle.GetCurrentVersion(),
|
||||
ReplicaPlacement: rp,
|
||||
Ttl: ttl,
|
||||
Extra: &master_pb.SuperBlockExtra{
|
||||
ErasureCoding: &master_pb.SuperBlockExtra_ErasureCoding{
|
||||
Data: 10,
|
||||
Parity: 4,
|
||||
VolumeIds: []uint32{1, 2, 3},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
got, err := ReadSuperBlock(&eofBackendStorageFile{data: s.Bytes()})
|
||||
if err != nil {
|
||||
t.Fatalf("ReadSuperBlock: %v", err)
|
||||
}
|
||||
if !proto.Equal(got.Extra, s.Extra) {
|
||||
t.Errorf("Extra = %v, want %v", got.Extra, s.Extra)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadSuperBlockTruncatedExtra(t *testing.T) {
|
||||
rp, _ := NewReplicaPlacementFromByte(byte(001))
|
||||
ttl, _ := needle.ReadTTL("15d")
|
||||
s := &SuperBlock{
|
||||
Version: needle.GetCurrentVersion(),
|
||||
ReplicaPlacement: rp,
|
||||
Ttl: ttl,
|
||||
Extra: &master_pb.SuperBlockExtra{
|
||||
ErasureCoding: &master_pb.SuperBlockExtra_ErasureCoding{
|
||||
Data: 10,
|
||||
Parity: 4,
|
||||
VolumeIds: []uint32{1, 2, 3},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
data := s.Bytes()
|
||||
datPath := filepath.Join(t.TempDir(), "1.dat")
|
||||
if err := os.WriteFile(datPath, data[:len(data)-1], 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := os.Open(datPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
datBackend := backend.NewDiskFile(f)
|
||||
defer datBackend.Close()
|
||||
|
||||
_, err = ReadSuperBlock(datBackend)
|
||||
if err == nil || !strings.Contains(err.Error(), "cannot read") {
|
||||
t.Fatalf("expected read error for truncated extra, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -204,6 +204,22 @@ func (v *Volume) FileStat() (datSize uint64, idxSize uint64, modTime time.Time)
|
||||
return // -1 causes integer overflow and the volume to become unwritable.
|
||||
}
|
||||
|
||||
// datAllocatedSize returns the disk space held by the .dat file, or 0 when it is unknown.
|
||||
func (v *Volume) datAllocatedSize() uint64 {
|
||||
v.dataFileAccessLock.RLock()
|
||||
defer v.dataFileAccessLock.RUnlock()
|
||||
|
||||
df, ok := v.DataBackend.(*backend.DiskFile)
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
fi, err := df.File.Stat()
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return allocatedSize(fi)
|
||||
}
|
||||
|
||||
func (v *Volume) ContentSize() uint64 {
|
||||
v.dataFileAccessLock.RLock()
|
||||
defer v.dataFileAccessLock.RUnlock()
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
//go:build !windows
|
||||
|
||||
package storage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// allocatedSize reports the bytes the filesystem holds for a file, which
|
||||
// exceeds its size when the file was preallocated with FALLOC_FL_KEEP_SIZE.
|
||||
func allocatedSize(fi os.FileInfo) uint64 {
|
||||
st, ok := fi.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
return uint64(st.Blocks) * 512
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//go:build windows
|
||||
|
||||
package storage
|
||||
|
||||
import "os"
|
||||
|
||||
// allocatedSize is unknown on Windows, where volume files are never preallocated.
|
||||
func allocatedSize(fi os.FileInfo) uint64 {
|
||||
return 0
|
||||
}
|
||||
@@ -37,7 +37,7 @@ func resolveCompactionOrder(meta table.Metadata, entries []iceberg.ManifestEntry
|
||||
continue
|
||||
}
|
||||
typ, ok := field.Type.(iceberg.PrimitiveType)
|
||||
if !ok {
|
||||
if !ok || !orderableType(typ) {
|
||||
continue
|
||||
}
|
||||
candidate := &compactionOrder{fieldID: field.ID, typ: typ, descending: sortField.Direction == table.SortDESC}
|
||||
@@ -57,7 +57,7 @@ func resolveCompactionOrder(meta table.Metadata, entries []iceberg.ManifestEntry
|
||||
// different format, or another partition) cannot disable ordering here.
|
||||
for _, field := range schema.Fields() {
|
||||
typ, ok := field.Type.(iceberg.PrimitiveType)
|
||||
if !ok {
|
||||
if !ok || !orderableType(typ) {
|
||||
continue
|
||||
}
|
||||
candidate := &compactionOrder{fieldID: field.ID, typ: typ, bestEffort: true}
|
||||
@@ -68,6 +68,18 @@ func resolveCompactionOrder(meta table.Metadata, entries []iceberg.ManifestEntry
|
||||
return nil
|
||||
}
|
||||
|
||||
// orderableType reports whether bounds of the type order files. Geometry and
|
||||
// geography bounds are corners of a box: they decode into literals that do
|
||||
// not compare, so ordering by them would sort nothing while still splitting
|
||||
// oversized bins as if the files were in order.
|
||||
func orderableType(t iceberg.PrimitiveType) bool {
|
||||
switch t.(type) {
|
||||
case iceberg.GeometryType, iceberg.GeographyType:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (o *compactionOrder) coversEntries(entries []iceberg.ManifestEntry) bool {
|
||||
for _, entry := range entries {
|
||||
if _, ok := o.key(entry); !ok {
|
||||
|
||||
@@ -386,3 +386,36 @@ func TestCompactDataFilesKeepsRunsWhenRepackFails(t *testing.T) {
|
||||
t.Fatalf("expected the ordered run to survive the failed repack, got %q", result)
|
||||
}
|
||||
}
|
||||
|
||||
// Geometry bounds have no order, so they never order a bin's files: a table
|
||||
// whose first column is a geometry is ordered by the next column with bounds.
|
||||
func TestResolveCompactionOrderSkipsGeometry(t *testing.T) {
|
||||
schema := iceberg.NewSchema(0,
|
||||
iceberg.NestedField{ID: 1, Type: iceberg.GeometryType{}, Name: "geom"},
|
||||
iceberg.NestedField{ID: 2, Type: iceberg.PrimitiveTypes.Int64, Name: "id", Required: true})
|
||||
meta, err := table.NewMetadata(schema, iceberg.UnpartitionedSpec, table.UnsortedSortOrder, "s3://tb/ns/geo", iceberg.Properties{"format-version": "3"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
geomField, _ := meta.CurrentSchema().FindFieldByName("geom")
|
||||
idField, _ := meta.CurrentSchema().FindFieldByName("id")
|
||||
snap := int64(1)
|
||||
var entries []iceberg.ManifestEntry
|
||||
for i, name := range []string{"a.parquet", "b.parquet", "c.parquet"} {
|
||||
b, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentData, "s3://tb/ns/geo/data/"+name, iceberg.ParquetFile, map[int]any{}, nil, nil, 1, 100)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b.LowerBoundValues(map[int][]byte{geomField.ID: xyBound(float64(i), 0), idField.ID: geoLE64(int64(10 - i))})
|
||||
b.UpperBoundValues(map[int][]byte{geomField.ID: xyBound(float64(i)+1, 1), idField.ID: geoLE64(int64(10 - i))})
|
||||
entries = append(entries, iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snap, nil, nil, b.Build()))
|
||||
}
|
||||
order := resolveCompactionOrder(meta, entries)
|
||||
if order == nil || order.fieldID != idField.ID {
|
||||
t.Fatalf("order %+v, want the id column (field %d), not the geometry (field %d)", order, idField.ID, geomField.ID)
|
||||
}
|
||||
order.sortEntries(entries)
|
||||
if first := entries[0].DataFile().FilePath(); !strings.HasSuffix(first, "c.parquet") {
|
||||
t.Errorf("first file %s, want c.parquet (the lowest id)", first)
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,7 @@ func collectColumnStats(data []byte, schema *iceberg.Schema) (*columnStats, erro
|
||||
stats := &columnStats{sizes: map[int]int64{}, values: map[int]int64{}, nulls: map[int]int64{},
|
||||
lower: map[int][]byte{}, upper: map[int][]byte{}}
|
||||
agg := map[int]*bounds{}
|
||||
geoAgg := map[int]*geometryBounds{}
|
||||
meta := file.Metadata()
|
||||
for rgIdx, rg := range file.RowGroups() {
|
||||
stats.splitOffsets = append(stats.splitOffsets, rowGroupOffset(&meta.RowGroups[rgIdx]))
|
||||
@@ -82,9 +83,24 @@ func collectColumnStats(data []byte, schema *iceberg.Schema) (*columnStats, erro
|
||||
chunk, ok := cc.(*parquet.FileColumnChunk)
|
||||
if !ok {
|
||||
b.invalid = true
|
||||
geoAgg[field.ID] = &geometryBounds{invalid: true}
|
||||
continue
|
||||
}
|
||||
stats.nulls[field.ID] += chunk.NullCount()
|
||||
switch field.Type.(type) {
|
||||
case iceberg.GeometryType:
|
||||
// the bound comes from the row group's geospatial statistics
|
||||
g := geoAgg[field.ID]
|
||||
if g == nil {
|
||||
g = &geometryBounds{}
|
||||
geoAgg[field.ID] = g
|
||||
}
|
||||
g.add(meta.RowGroups[rgIdx].Columns[col].MetaData.GeospatialStatistics, chunk.NumValues(), chunk.NullCount())
|
||||
continue
|
||||
case iceberg.GeographyType:
|
||||
// no bound: edges are geodesic and a box may cross the antimeridian
|
||||
continue
|
||||
}
|
||||
if chunk.NullCount() == chunk.NumValues() {
|
||||
continue // an all-null chunk constrains nothing
|
||||
}
|
||||
@@ -122,6 +138,11 @@ func collectColumnStats(data []byte, schema *iceberg.Schema) (*columnStats, erro
|
||||
stats.upper[id] = raw
|
||||
}
|
||||
}
|
||||
for id, g := range geoAgg {
|
||||
if lower, upper, ok := g.encoded(); ok {
|
||||
stats.lower[id], stats.upper[id] = lower, upper
|
||||
}
|
||||
}
|
||||
sort.Slice(stats.splitOffsets, func(i, j int) bool { return stats.splitOffsets[i] < stats.splitOffsets[j] })
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"math"
|
||||
|
||||
"github.com/parquet-go/parquet-go/format"
|
||||
)
|
||||
|
||||
// geometryBounds aggregates the bound of a geometry column over the row groups
|
||||
// of a written file. The spec serializes a geometry bound as a point: the
|
||||
// lower bound is (xmin, ymin), the upper bound (xmax, ymax), each coordinate
|
||||
// an 8-byte little-endian double; z and m are optional and not written here.
|
||||
//
|
||||
// Readers skip a file whose bound does not intersect a spatial filter, so a
|
||||
// box smaller than the file's geometries returns wrong results. Any doubt
|
||||
// gives no bound:
|
||||
// - the box is the union of the row groups' geospatial statistics, which
|
||||
// the Parquet writer computes from every non-null value;
|
||||
// - a row group with non-null values but no statistics (the writer omits
|
||||
// them when a value does not parse as WKB) gives the column no bound, as
|
||||
// does a box that is not finite or is inverted;
|
||||
// - a row group of nulls only constrains nothing.
|
||||
type geometryBounds struct {
|
||||
xmin, ymin, xmax, ymax float64
|
||||
seen bool
|
||||
invalid bool
|
||||
}
|
||||
|
||||
func (g *geometryBounds) add(gs format.GeospatialStatistics, numValues, nullCount int64) {
|
||||
if g.invalid || numValues <= 0 || nullCount >= numValues {
|
||||
return
|
||||
}
|
||||
if len(gs.GeoSpatialTypes) == 0 {
|
||||
g.invalid = true
|
||||
return
|
||||
}
|
||||
bb := gs.BBox
|
||||
for _, v := range []float64{bb.XMin, bb.XMax, bb.YMin, bb.YMax} {
|
||||
if math.IsNaN(v) || math.IsInf(v, 0) {
|
||||
g.invalid = true
|
||||
return
|
||||
}
|
||||
}
|
||||
if bb.XMin > bb.XMax || bb.YMin > bb.YMax {
|
||||
g.invalid = true
|
||||
return
|
||||
}
|
||||
if !g.seen {
|
||||
g.xmin, g.ymin, g.xmax, g.ymax, g.seen = bb.XMin, bb.YMin, bb.XMax, bb.YMax, true
|
||||
return
|
||||
}
|
||||
g.xmin, g.ymin = math.Min(g.xmin, bb.XMin), math.Min(g.ymin, bb.YMin)
|
||||
g.xmax, g.ymax = math.Max(g.xmax, bb.XMax), math.Max(g.ymax, bb.YMax)
|
||||
}
|
||||
|
||||
// encoded returns the lower and upper bound, or false when the column gets
|
||||
// none.
|
||||
func (g *geometryBounds) encoded() (lower, upper []byte, ok bool) {
|
||||
if g == nil || g.invalid || !g.seen {
|
||||
return nil, nil, false
|
||||
}
|
||||
return encodeGeometryPoint(g.xmin, g.ymin), encodeGeometryPoint(g.xmax, g.ymax), true
|
||||
}
|
||||
|
||||
func encodeGeometryPoint(x, y float64) []byte {
|
||||
b := make([]byte, 16)
|
||||
binary.LittleEndian.PutUint64(b, math.Float64bits(x))
|
||||
binary.LittleEndian.PutUint64(b[8:], math.Float64bits(y))
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/apache/iceberg-go"
|
||||
"github.com/apache/iceberg-go/table"
|
||||
"github.com/parquet-go/parquet-go/format"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
type geoBox struct{ xmin, ymin, xmax, ymax float64 }
|
||||
|
||||
func (b geoBox) String() string {
|
||||
return fmt.Sprintf("(%g %g, %g %g)", b.xmin, b.ymin, b.xmax, b.ymax)
|
||||
}
|
||||
|
||||
func (b geoBox) covers(o geoBox) bool {
|
||||
return b.xmin <= o.xmin && b.ymin <= o.ymin && b.xmax >= o.xmax && b.ymax >= o.ymax
|
||||
}
|
||||
|
||||
// compactedGeoBounds is the geometry bound of each compacted file in the
|
||||
// current manifests (nil: none), and whether its id column has a bound, the
|
||||
// control that statistics were collected at all.
|
||||
func compactedGeoBounds(t *testing.T, client filer_pb.SeaweedFilerClient, setup tableSetup) (map[string]*geoBox, map[string]bool) {
|
||||
t.Helper()
|
||||
geo, idBounded := map[string]*geoBox{}, map[string]bool{}
|
||||
for _, e := range currentDataEntries(t, client, setup) {
|
||||
df := e.DataFile()
|
||||
if !strings.Contains(df.FilePath(), "/compact-") {
|
||||
continue
|
||||
}
|
||||
idBounded[df.FilePath()] = df.LowerBoundValues()[geoTestIDField] != nil
|
||||
lo, hi := df.LowerBoundValues()[geoTestGeomField], df.UpperBoundValues()[geoTestGeomField]
|
||||
if lo == nil && hi == nil {
|
||||
geo[df.FilePath()] = nil
|
||||
continue
|
||||
}
|
||||
x0, y0 := decodeXYBound(t, lo)
|
||||
x1, y1 := decodeXYBound(t, hi)
|
||||
geo[df.FilePath()] = &geoBox{x0, y0, x1, y1}
|
||||
}
|
||||
if len(geo) == 0 {
|
||||
t.Fatal("no compacted file in the manifests")
|
||||
}
|
||||
return geo, idBounded
|
||||
}
|
||||
|
||||
// mixedGeoFiles holds points and polygons far apart, so a bound that misses
|
||||
// any of them shows.
|
||||
func mixedGeoFiles() ([]geoFile, geoBox) {
|
||||
files := []geoFile{
|
||||
{Name: "pts.parquet", Rows: []geoRow{{1, wkbPoint(-3.70, 40.41)}, {2, wkbPoint(2.17, 41.38)}, {3, wkbPoint(-5.98, 37.38)}}},
|
||||
{Name: "boxes.parquet", Rows: []geoRow{{4, wkbBox(-9.3, 42.1, -8.5, 43.4)}, {5, wkbBox(1.0, 36.0, 4.3, 39.9)}}},
|
||||
{Name: "nulls.parquet", Rows: []geoRow{{6, nil}, {7, nil}}},
|
||||
{Name: "mixed.parquet", Rows: []geoRow{{8, nil}, {9, wkbPoint(-1.10, 40.34)}, {10, wkbBox(-0.5, 38.9, -0.3, 39.5)}}},
|
||||
}
|
||||
return files, geoBox{-9.3, 36.0, 4.3, 43.4}
|
||||
}
|
||||
|
||||
func TestCompactRecordsGeometryBounds(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"}
|
||||
files, want := mixedGeoFiles()
|
||||
populateGeoTable(t, fs, setup, files, geoTableOptions{})
|
||||
if result := compactGeo(t, client, setup, Config{}); !strings.Contains(result, "compacted 4 files") {
|
||||
t.Fatalf("result %q", result)
|
||||
}
|
||||
geo, idBounded := compactedGeoBounds(t, client, setup)
|
||||
for p, got := range geo {
|
||||
if !idBounded[p] {
|
||||
t.Errorf("%s: no id bound: statistics were not collected", p)
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatalf("%s: no geometry bound", p)
|
||||
}
|
||||
if *got != want {
|
||||
t.Errorf("%s: geometry bound %s, want the union of every geometry %s", p, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A sorted rewrite may write its output without row-group geospatial
|
||||
// statistics; the file then gets no geometry bound, never one that misses
|
||||
// a row.
|
||||
func TestCompactSortedGeometryBoundCoversEveryRow(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"}
|
||||
so, err := table.NewSortOrder(1, []table.SortField{{SourceIDs: []int{geoTestIDField}, Transform: iceberg.IdentityTransform{}, Direction: table.SortDESC, NullOrder: table.NullsFirst}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files, want := mixedGeoFiles()
|
||||
populateGeoTable(t, fs, setup, files, geoTableOptions{sortOrder: &so})
|
||||
compactGeo(t, client, setup, Config{RewriteStrategy: "sort", SortBufferRows: minSortBufferRows})
|
||||
geo, _ := compactedGeoBounds(t, client, setup)
|
||||
for p, got := range geo {
|
||||
if got != nil && !got.covers(want) {
|
||||
t.Errorf("%s: geometry bound %s does not cover every geometry %s", p, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompactAllNullGeometryGetsNoBound(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"}
|
||||
populateGeoTable(t, fs, setup, []geoFile{
|
||||
{Name: "a.parquet", Rows: []geoRow{{1, nil}, {2, nil}}},
|
||||
{Name: "b.parquet", Rows: []geoRow{{3, nil}}},
|
||||
}, geoTableOptions{})
|
||||
compactGeo(t, client, setup, Config{})
|
||||
geo, idBounded := compactedGeoBounds(t, client, setup)
|
||||
for p, got := range geo {
|
||||
if got != nil {
|
||||
t.Errorf("%s: geometry bound %s on a column of nulls", p, got)
|
||||
}
|
||||
if !idBounded[p] {
|
||||
t.Errorf("%s: no id bound: statistics were not collected", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A value that does not parse as WKB leaves its row group without
|
||||
// geospatial statistics; the file then gets no geometry bound rather than
|
||||
// one from the other row groups that does not cover that row group.
|
||||
func TestCompactUnparseableGeometryGivesNoBound(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"}
|
||||
populateGeoTable(t, fs, setup, []geoFile{
|
||||
{Name: "ok.parquet", Rows: []geoRow{{1, wkbPoint(10, 10)}, {2, wkbPoint(11, 11)}}},
|
||||
{Name: "bad.parquet", Rows: []geoRow{{3, []byte("not wkb at all")}, {4, wkbPoint(-50, -50)}}},
|
||||
}, geoTableOptions{})
|
||||
// two rows a row group: the valid file's rows, then the other file's
|
||||
compactGeo(t, client, setup, Config{RowGroupRowLimit: 2})
|
||||
geo, idBounded := compactedGeoBounds(t, client, setup)
|
||||
for p, got := range geo {
|
||||
if got != nil {
|
||||
t.Errorf("%s: geometry bound %s although a value did not parse", p, got)
|
||||
}
|
||||
if !idBounded[p] {
|
||||
t.Errorf("%s: no id bound: statistics were not collected", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollectColumnStatsGivesGeographyNoBound(t *testing.T) {
|
||||
data := writeGeoParquet(t, []geoRow{{1, wkbPoint(170, 10)}, {2, wkbPoint(-170, 12)}}, "")
|
||||
geog, err := iceberg.GeographyTypeOf(iceberg.DefaultGeoCRS, "spherical")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
typ iceberg.Type
|
||||
wantBound bool
|
||||
}{{iceberg.GeometryType{}, true}, {geog, false}} {
|
||||
stats, err := collectColumnStats(data, geoTestSchema(tc.typ))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, has := stats.lower[geoTestGeomField]; has != tc.wantBound {
|
||||
t.Errorf("%s: lower bound present %v, want %v", tc.typ, has, tc.wantBound)
|
||||
}
|
||||
if stats.values[geoTestGeomField] != 2 {
|
||||
t.Errorf("%s: value count %d, want 2", tc.typ, stats.values[geoTestGeomField])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeometryBoundsAggregation(t *testing.T) {
|
||||
stats := func(xmin, ymin, xmax, ymax float64) format.GeospatialStatistics {
|
||||
return format.GeospatialStatistics{BBox: format.BoundingBox{XMin: xmin, XMax: xmax, YMin: ymin, YMax: ymax}, GeoSpatialTypes: []int32{1}}
|
||||
}
|
||||
type chunk struct {
|
||||
gs format.GeospatialStatistics
|
||||
values, nulls int64
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
chunks []chunk
|
||||
want *geoBox
|
||||
}{
|
||||
{"one", []chunk{{stats(1, 2, 3, 4), 5, 0}}, &geoBox{1, 2, 3, 4}},
|
||||
{"union", []chunk{{stats(1, 2, 3, 4), 5, 0}, {stats(-1, 3, 2, 9), 5, 1}}, &geoBox{-1, 2, 3, 9}},
|
||||
{"nulls only constrain nothing", []chunk{{stats(1, 2, 3, 4), 5, 0}, {format.GeospatialStatistics{}, 4, 4}}, &geoBox{1, 2, 3, 4}},
|
||||
{"values without statistics", []chunk{{stats(1, 2, 3, 4), 5, 0}, {format.GeospatialStatistics{}, 4, 1}}, nil},
|
||||
{"NaN", []chunk{{stats(1, math.NaN(), 3, 4), 5, 0}}, nil},
|
||||
{"infinity", []chunk{{stats(1, 2, math.Inf(1), 4), 5, 0}}, nil},
|
||||
{"inverted", []chunk{{stats(3, 2, 1, 4), 5, 0}}, nil},
|
||||
{"nothing", nil, nil},
|
||||
} {
|
||||
var g geometryBounds
|
||||
for _, c := range tc.chunks {
|
||||
g.add(c.gs, c.values, c.nulls)
|
||||
}
|
||||
lo, hi, ok := g.encoded()
|
||||
if tc.want == nil {
|
||||
if ok {
|
||||
t.Errorf("%s: bound given, want none", tc.name)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !ok {
|
||||
t.Errorf("%s: no bound, want %s", tc.name, tc.want)
|
||||
continue
|
||||
}
|
||||
x0, y0 := decodeXYBound(t, lo)
|
||||
x1, y1 := decodeXYBound(t, hi)
|
||||
if got := (geoBox{x0, y0, x1, y1}); got != *tc.want {
|
||||
t.Errorf("%s: bound %s, want %s", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user