mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49d9d0c1cd | ||
|
|
6ec6cce3fe | ||
|
|
e057244b0a | ||
|
|
763e2a2090 | ||
|
|
917b6f4afd | ||
|
|
106fd31af1 | ||
|
|
137f23a229 | ||
|
|
e645449872 | ||
|
|
9b642d4636 | ||
|
|
a882565cd7 | ||
|
|
de2fc03c7d | ||
|
|
21add33b6e | ||
|
|
9a03c09396 | ||
|
|
f40267db44 | ||
|
|
6ee7c4c5c7 | ||
|
|
9c427b265f | ||
|
|
97f8ca13ff |
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]
|
||||
|
||||
@@ -4185,8 +4185,10 @@ impl Volume {
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let (was_no_write_or_delete, was_no_write_can_delete) = self.no_write_flags();
|
||||
// Remote-tiered volumes must stay no_write_can_delete regardless of marks.
|
||||
let no_write_can_delete = was_no_write_can_delete && self.has_remote_file();
|
||||
// A remote-tiered volume keeps the delete-only mode a load derives: its
|
||||
// .dat cannot take appends, so "writable" resolves to can-delete rather
|
||||
// than advertising writable with no local data file.
|
||||
let no_write_can_delete = self.has_remote_file();
|
||||
self.no_write.store(
|
||||
if no_write_can_delete {
|
||||
NO_WRITE_CAN_DELETE
|
||||
@@ -4300,21 +4302,70 @@ impl Volume {
|
||||
}
|
||||
f(&mut self.volume_info.write().unwrap().files);
|
||||
let mut io = self.io.write().unwrap();
|
||||
self.refresh_remote_write_mode(&mut io)
|
||||
self.refresh_remote_write_mode(&mut io, true)
|
||||
}
|
||||
|
||||
/// Go's MarkTieredDeletable: a live tier-up lifts the upload-time
|
||||
/// read-only mark, except on a replicated volume — the shell copies the
|
||||
/// uploaded replica's .idx and .vif to the other replicas after the
|
||||
/// upload, and a tombstone written before that copy would reach one
|
||||
/// replica only — or under an I/O quarantine, which is not the tier
|
||||
/// upload's to lift. A refused volume keeps its flags until the next
|
||||
/// load, as the Go volume does.
|
||||
fn mark_tiered_deletable(&self) -> bool {
|
||||
if self
|
||||
.super_block
|
||||
.read()
|
||||
.unwrap()
|
||||
.replica_placement
|
||||
.has_replication()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if !self.has_remote_file() {
|
||||
return false;
|
||||
}
|
||||
// Go takes noWriteLock around the quarantine check and the flag
|
||||
// change; here a compare-exchange gives the same ordering — a
|
||||
// heartbeat refusal landing between the check and the swap fails the
|
||||
// swap, and the retry sees the quarantine mark the heartbeat set
|
||||
// first.
|
||||
loop {
|
||||
if self.should_quarantine() {
|
||||
return false;
|
||||
}
|
||||
let flags = self.no_write.load(Ordering::Acquire);
|
||||
let promoted = (flags & !NO_WRITE_OR_DELETE) | NO_WRITE_CAN_DELETE;
|
||||
if self
|
||||
.no_write
|
||||
.compare_exchange(flags, promoted, Ordering::AcqRel, Ordering::Acquire)
|
||||
.is_ok()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Recompute the Go-style write/delete mode from the current remote tier
|
||||
/// state, and bring the needle map in line with it — a volume that stops
|
||||
/// being remote also stops using the read-only sorted index.
|
||||
///
|
||||
/// `live` is a tier transition on a running volume: the promotion then
|
||||
/// goes through mark_tiered_deletable, Go's MarkTieredDeletable, while a
|
||||
/// load promotes every tiered volume unconditionally as Go's load() does.
|
||||
///
|
||||
/// If the map cannot be rebuilt the volume is pinned read-only rather than
|
||||
/// published as writable with an index that rejects every put; a restart
|
||||
/// recovers it.
|
||||
fn refresh_remote_write_mode(&self, io: &mut VolumeIo) -> Result<(), VolumeError> {
|
||||
fn refresh_remote_write_mode(&self, io: &mut VolumeIo, live: bool) -> Result<(), VolumeError> {
|
||||
let has_remote = self.has_remote_file();
|
||||
if has_remote {
|
||||
// remote-tiered: no writes, deletes allowed
|
||||
self.no_write.store(NO_WRITE_CAN_DELETE, Ordering::Release);
|
||||
if !live {
|
||||
self.no_write.store(NO_WRITE_CAN_DELETE, Ordering::Release);
|
||||
} else {
|
||||
self.mark_tiered_deletable();
|
||||
}
|
||||
} else if !self.volume_info.read().unwrap().read_only_can_delete {
|
||||
// only clear the remoteness-derived flag, not an operator mark
|
||||
self.set_no_write_flag(NO_WRITE_CAN_DELETE, false);
|
||||
@@ -4363,7 +4414,7 @@ impl Volume {
|
||||
}
|
||||
}
|
||||
*self.volume_info.write().unwrap() = pb_info;
|
||||
self.refresh_remote_write_mode(io)?;
|
||||
self.refresh_remote_write_mode(io, false)?;
|
||||
{
|
||||
let mut vi = self.volume_info.write().unwrap();
|
||||
if vi.version == 0 {
|
||||
@@ -4394,7 +4445,7 @@ impl Volume {
|
||||
self.set_no_write_flag(NO_WRITE_OR_DELETE, true);
|
||||
}
|
||||
*self.volume_info.write().unwrap() = pb_info;
|
||||
self.refresh_remote_write_mode(io)?;
|
||||
self.refresh_remote_write_mode(io, false)?;
|
||||
{
|
||||
let mut vi = self.volume_info.write().unwrap();
|
||||
if vi.version == 0 {
|
||||
@@ -4934,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();
|
||||
@@ -9701,6 +9771,72 @@ mod tests {
|
||||
assert!(!v.is_no_write_or_delete());
|
||||
}
|
||||
|
||||
/// Go's MarkTieredDeletable leaves a replicated volume's upload-time
|
||||
/// read-only mark alone: the shell still has to copy the uploaded
|
||||
/// replica's .idx to the others, and a tombstone written before that copy
|
||||
/// would reach one replica only.
|
||||
#[test]
|
||||
fn test_update_remote_files_keeps_a_replicated_volume_refusing_deletes() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let v = make_test_volume(dir);
|
||||
v.super_block.write().unwrap().replica_placement =
|
||||
crate::storage::super_block::ReplicaPlacement::from_string("001").unwrap();
|
||||
v.set_no_write_or_delete(true); // the shell's pre-upload mark
|
||||
|
||||
v.update_remote_files(|files| files.push(Default::default()))
|
||||
.unwrap();
|
||||
|
||||
assert!(v.has_remote_file());
|
||||
assert!(
|
||||
v.is_no_write_or_delete(),
|
||||
"a replicated volume keeps refusing deletes until its next load"
|
||||
);
|
||||
assert!(!v.is_no_write_can_delete());
|
||||
}
|
||||
|
||||
/// An I/O quarantine is not the tier upload's to lift: a live tier-up
|
||||
/// leaves a quarantined volume's read-only mark alone, as Go's
|
||||
/// MarkTieredDeletable does.
|
||||
#[test]
|
||||
fn test_update_remote_files_keeps_an_io_quarantine() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let v = make_test_volume(dir);
|
||||
v.set_no_write_or_delete(true);
|
||||
v.mark_io_quarantined();
|
||||
|
||||
v.update_remote_files(|files| files.push(Default::default()))
|
||||
.unwrap();
|
||||
|
||||
assert!(v.has_remote_file());
|
||||
assert!(v.is_no_write_or_delete());
|
||||
assert!(!v.is_no_write_can_delete());
|
||||
}
|
||||
|
||||
/// A refused tiered volume keeps OR_DELETE without CAN_DELETE; marking it
|
||||
/// writable must resolve to the delete-only mode a load derives — the
|
||||
/// remote .dat cannot take appends — not drop every protection.
|
||||
#[test]
|
||||
fn test_set_writable_on_a_refused_tiered_volume_stays_delete_only() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let v = make_test_volume(dir);
|
||||
v.super_block.write().unwrap().replica_placement =
|
||||
crate::storage::super_block::ReplicaPlacement::from_string("001").unwrap();
|
||||
v.set_no_write_or_delete(true);
|
||||
|
||||
v.update_remote_files(|files| files.push(Default::default()))
|
||||
.unwrap();
|
||||
assert!(v.is_no_write_or_delete());
|
||||
|
||||
v.set_writable().unwrap();
|
||||
|
||||
assert!(v.is_read_only());
|
||||
assert!(!v.no_write_flags().0);
|
||||
assert!(v.no_write_flags().1);
|
||||
}
|
||||
|
||||
// Tier-down clears the remote mode and publishes the volume as writable. The
|
||||
// map it booted with is the read-only sorted one, whose put always fails, so
|
||||
// without a rebuild the first write appends to .dat and then cannot be
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package s3tables
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/config"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/smithy-go"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newObjectClient(t *testing.T) *s3.Client {
|
||||
t.Helper()
|
||||
cfg, err := config.LoadDefaultConfig(context.Background(),
|
||||
config.WithRegion(testRegion),
|
||||
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(testAccessKey, testSecretKey, "")),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return s3.NewFromConfig(cfg, func(o *s3.Options) {
|
||||
o.BaseEndpoint = aws.String(sharedCluster.s3Endpoint)
|
||||
o.UsePathStyle = true
|
||||
})
|
||||
}
|
||||
|
||||
func apiErrorCode(err error) string {
|
||||
var apiErr smithy.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
return apiErr.ErrorCode()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// The external-volume verification object round-trips at a table bucket's
|
||||
// root the way the check uses it: PUT, HEAD, GET, list, DELETE. Any other key
|
||||
// at the root is still refused.
|
||||
func TestTableBucketExternalVolumeVerificationRoundTrip(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
ctx := context.Background()
|
||||
tables := NewS3TablesClient(sharedCluster.s3Endpoint, testRegion, testAccessKey, testSecretKey)
|
||||
bucket := "verify-" + randomString(8)
|
||||
created, err := tables.CreateTableBucket(bucket, nil)
|
||||
require.NoError(t, err)
|
||||
defer tables.DeleteTableBucket(created.ARN)
|
||||
client := newObjectClient(t)
|
||||
|
||||
body := []byte("verification payload!") // 21 bytes
|
||||
key := fmt.Sprintf("verify_%d_%d", time.Now().UnixMilli(), 1081846483)
|
||||
|
||||
// the control: an ordinary key at the root is refused
|
||||
_, err = client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String("notes.parquet"), Body: bytes.NewReader(body)})
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, "AccessDenied", apiErrorCode(err))
|
||||
|
||||
_, err = client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String(key), Body: bytes.NewReader(body), ContentLength: aws.Int64(int64(len(body)))})
|
||||
require.NoError(t, err)
|
||||
|
||||
head, err := client.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(len(body)), aws.ToInt64(head.ContentLength))
|
||||
|
||||
got, err := client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
data, err := io.ReadAll(got.Body)
|
||||
got.Body.Close()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, body, data)
|
||||
|
||||
list, err := client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{Bucket: aws.String(bucket), Prefix: aws.String("verify_")})
|
||||
require.NoError(t, err)
|
||||
var keys []string
|
||||
for _, o := range list.Contents {
|
||||
keys = append(keys, aws.ToString(o.Key))
|
||||
}
|
||||
assert.Equal(t, []string{key}, keys)
|
||||
|
||||
_, err = client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
_, err = client.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.Error(t, err, "the verification object must be gone after DELETE")
|
||||
}
|
||||
|
||||
// A namespace can carry a name of the verification key's shape. The key
|
||||
// then names the namespace's directory: a PUT or DELETE through it must not
|
||||
// replace or remove the namespace.
|
||||
func TestTableBucketVerificationKeyLeavesNamespaceAlone(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
ctx := context.Background()
|
||||
tables := NewS3TablesClient(sharedCluster.s3Endpoint, testRegion, testAccessKey, testSecretKey)
|
||||
bucket := "verify-ns-" + randomString(8)
|
||||
created, err := tables.CreateTableBucket(bucket, nil)
|
||||
require.NoError(t, err)
|
||||
defer tables.DeleteTableBucket(created.ARN)
|
||||
client := newObjectClient(t)
|
||||
body := []byte("verification payload!")
|
||||
|
||||
listed := func(name string) bool {
|
||||
resp, err := tables.ListNamespaces(created.ARN, "", "", 0)
|
||||
require.NoError(t, err)
|
||||
for _, ns := range resp.Namespaces {
|
||||
if len(ns.Namespace) == 1 && ns.Namespace[0] == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
for i, op := range []string{"PUT", "DELETE"} {
|
||||
t.Run(op, func(t *testing.T) {
|
||||
name := fmt.Sprintf("verify_%d_%d", time.Now().UnixMilli(), 7+i)
|
||||
_, err := tables.CreateNamespace(created.ARN, []string{name})
|
||||
require.NoError(t, err)
|
||||
defer tables.DeleteNamespace(created.ARN, []string{name})
|
||||
require.True(t, listed(name), "setup: the namespace is listed")
|
||||
|
||||
if op == "PUT" {
|
||||
_, err = client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String(name), Body: bytes.NewReader(body), ContentLength: aws.Int64(int64(len(body)))})
|
||||
assert.Error(t, err, "a PUT over a namespace must be refused")
|
||||
} else {
|
||||
_, err = client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(name)})
|
||||
assert.Error(t, err, "a DELETE of a namespace must be refused")
|
||||
}
|
||||
_, err = tables.GetNamespace(created.ARN, []string{name})
|
||||
assert.NoError(t, err, "the namespace survives the %s", op)
|
||||
assert.True(t, listed(name), "the namespace is still listed after the %s", op)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -34,14 +34,6 @@ connection_max_lifetime_seconds = 3600
|
||||
[credential.memory]
|
||||
enabled = false
|
||||
|
||||
# Store secret keys KMS-encrypted instead of plaintext.
|
||||
# Requires a KMS provider configured in the [kms] section (filer.toml or
|
||||
# security.toml): local, aws, azure, gcp, or openbao for Vault/OpenBao.
|
||||
# Existing plaintext secrets keep working and are encrypted on their next write.
|
||||
[credential.encryption]
|
||||
enabled = false
|
||||
#key_id = "seaweedfs-credentials"
|
||||
|
||||
# Environment variable overrides:
|
||||
# Any configuration value can be overridden by environment variables
|
||||
# Rules:
|
||||
|
||||
@@ -28,6 +28,10 @@ region = "us-east-2"
|
||||
bucket = "your_bucket_name" # an existing bucket
|
||||
endpoint = ""
|
||||
storage_class = "STANDARD_IA"
|
||||
# optional HTTP client tuning for S3-compatible services:
|
||||
# disable_http2 = false # true keeps the client on HTTP/1.1, one connection per concurrent request
|
||||
# max_connections = 0 # cap on connections to the endpoint, 0 = no cap
|
||||
# idle_connection_timeout_seconds = 0 # close idle connections sooner, 0 = Go default (90s)
|
||||
|
||||
# create this number of logical volumes if no more writable volumes
|
||||
# count_x means how many copies of data.
|
||||
|
||||
@@ -101,25 +101,6 @@ connection_max_lifetime_seconds = 3600
|
||||
enabled = true
|
||||
```
|
||||
|
||||
### Encrypted Secret Keys
|
||||
|
||||
Any store can persist secret keys encrypted instead of plaintext:
|
||||
|
||||
```toml
|
||||
[credential.filer_etc]
|
||||
enabled = true
|
||||
|
||||
[credential.encryption]
|
||||
enabled = true
|
||||
#key_id = "seaweedfs-credentials" # optional KMS key id
|
||||
```
|
||||
|
||||
Secrets are wrapped with a data key from the configured KMS provider
|
||||
(`[kms]` section — local, aws, azure, gcp, or openbao for Vault/OpenBao),
|
||||
so the master key material can live in an external KMS or Vault. Secrets
|
||||
already stored in plaintext keep working and are encrypted on their next
|
||||
write.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
All credential configuration can be overridden with environment variables:
|
||||
|
||||
@@ -58,11 +58,6 @@ func NewCredentialManager(storeName CredentialStoreTypeName, configuration util.
|
||||
return nil, fmt.Errorf("failed to initialize credential store '%s': %v", storeName, err)
|
||||
}
|
||||
|
||||
if configuration != nil && configuration.GetBool("credential.encryption.enabled") {
|
||||
store = NewEncryptedCredentialStore(store, configuration.GetString("credential.encryption.key_id"))
|
||||
glog.V(0).Infof("Credential store '%s' persists secret keys KMS-encrypted", storeName)
|
||||
}
|
||||
|
||||
return &CredentialManager{
|
||||
Store: store,
|
||||
}, nil
|
||||
|
||||
@@ -1,415 +0,0 @@
|
||||
package credential
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/kms"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// CredentialEncryptionKeyID is the default KMS key used to wrap secret keys
|
||||
// when credential.toml enables encryption without naming one.
|
||||
const CredentialEncryptionKeyID = "seaweedfs-credentials"
|
||||
|
||||
// encryptedDataKeyField carries the KMS-wrapped data key inside the envelope.
|
||||
const encryptedDataKeyField = "encrypted_data_key"
|
||||
|
||||
// credentialEncryptionContext authenticates the data key wrapping so a blob
|
||||
// cannot be replayed from a different subsystem.
|
||||
var credentialEncryptionContext = map[string]string{"seaweedfs": "credential-store"}
|
||||
|
||||
// EncryptedCredentialStore wraps another credential store and encrypts secret
|
||||
// keys before they are persisted, decrypting them on reads. Secrets stored
|
||||
// without an envelope pass through unchanged, so existing plaintext
|
||||
// configurations keep working while new writes are encrypted.
|
||||
type EncryptedCredentialStore struct {
|
||||
CredentialStore
|
||||
keyID string
|
||||
}
|
||||
|
||||
var _ CredentialStore = &EncryptedCredentialStore{}
|
||||
|
||||
// NewEncryptedCredentialStore wraps an upstream store with secret encryption
|
||||
// under the named KMS key. An empty keyID uses CredentialEncryptionKeyID.
|
||||
func NewEncryptedCredentialStore(upstream CredentialStore, keyID string) CredentialStore {
|
||||
if keyID == "" {
|
||||
keyID = CredentialEncryptionKeyID
|
||||
}
|
||||
wrapped := &EncryptedCredentialStore{CredentialStore: upstream, keyID: keyID}
|
||||
if _, ok := upstream.(UserRenamer); ok {
|
||||
return &encryptedRenamerStore{wrapped}
|
||||
}
|
||||
return wrapped
|
||||
}
|
||||
|
||||
// encryptedRenamerStore adds RenameUser to the wrapper only when the upstream
|
||||
// store supports it, so wrapped stores keep their atomic rename capability.
|
||||
type encryptedRenamerStore struct {
|
||||
*EncryptedCredentialStore
|
||||
}
|
||||
|
||||
func (s *encryptedRenamerStore) RenameUser(ctx context.Context, oldName, newName string) error {
|
||||
return s.CredentialStore.(UserRenamer).RenameUser(ctx, oldName, newName)
|
||||
}
|
||||
|
||||
// SetFilerAddressFunc forwards a dynamic filer address to stores that need it.
|
||||
func (s *EncryptedCredentialStore) SetFilerAddressFunc(getFiler func() pb.ServerAddress, grpcDialOption grpc.DialOption) {
|
||||
if setter, ok := s.CredentialStore.(FilerAddressSetter); ok {
|
||||
setter.SetFilerAddressFunc(getFiler, grpcDialOption)
|
||||
}
|
||||
}
|
||||
|
||||
// The optional interface forwarders below return the same neutral results the
|
||||
// CredentialManager produces for stores without the capability, so wrapping a
|
||||
// store never changes which calls succeed.
|
||||
|
||||
func (s *EncryptedCredentialStore) PutUserInlinePolicy(ctx context.Context, userName, policyName string, document policy_engine.PolicyDocument) error {
|
||||
if store, ok := s.CredentialStore.(InlinePolicyStore); ok {
|
||||
return store.PutUserInlinePolicy(ctx, userName, policyName, document)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) GetUserInlinePolicy(ctx context.Context, userName, policyName string) (*policy_engine.PolicyDocument, error) {
|
||||
if store, ok := s.CredentialStore.(InlinePolicyStore); ok {
|
||||
return store.GetUserInlinePolicy(ctx, userName, policyName)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) DeleteUserInlinePolicy(ctx context.Context, userName, policyName string) error {
|
||||
if store, ok := s.CredentialStore.(InlinePolicyStore); ok {
|
||||
return store.DeleteUserInlinePolicy(ctx, userName, policyName)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) ListUserInlinePolicies(ctx context.Context, userName string) ([]string, error) {
|
||||
if store, ok := s.CredentialStore.(InlinePolicyStore); ok {
|
||||
return store.ListUserInlinePolicies(ctx, userName)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) LoadInlinePolicies(ctx context.Context) (map[string]map[string]policy_engine.PolicyDocument, error) {
|
||||
if loader, ok := s.CredentialStore.(InlinePoliciesLoader); ok {
|
||||
return loader.LoadInlinePolicies(ctx)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) PutGroupInlinePolicy(ctx context.Context, groupName, policyName string, document policy_engine.PolicyDocument) error {
|
||||
if store, ok := s.CredentialStore.(GroupInlinePolicyStore); ok {
|
||||
return store.PutGroupInlinePolicy(ctx, groupName, policyName, document)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) GetGroupInlinePolicy(ctx context.Context, groupName, policyName string) (*policy_engine.PolicyDocument, error) {
|
||||
if store, ok := s.CredentialStore.(GroupInlinePolicyStore); ok {
|
||||
return store.GetGroupInlinePolicy(ctx, groupName, policyName)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) DeleteGroupInlinePolicy(ctx context.Context, groupName, policyName string) error {
|
||||
if store, ok := s.CredentialStore.(GroupInlinePolicyStore); ok {
|
||||
return store.DeleteGroupInlinePolicy(ctx, groupName, policyName)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) ListGroupInlinePolicies(ctx context.Context, groupName string) ([]string, error) {
|
||||
if store, ok := s.CredentialStore.(GroupInlinePolicyStore); ok {
|
||||
return store.ListGroupInlinePolicies(ctx, groupName)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) LoadGroupInlinePolicies(ctx context.Context) (map[string]map[string]policy_engine.PolicyDocument, error) {
|
||||
if loader, ok := s.CredentialStore.(GroupInlinePoliciesLoader); ok {
|
||||
return loader.LoadGroupInlinePolicies(ctx)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) provider() (kms.KMSProvider, error) {
|
||||
provider := kms.GetGlobalKMS()
|
||||
if provider == nil {
|
||||
return nil, fmt.Errorf("credential encryption is enabled but no KMS provider is configured (see the [kms] section)")
|
||||
}
|
||||
return provider, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) encryptSecret(ctx context.Context, plaintext string) (string, error) {
|
||||
if plaintext == "" {
|
||||
return plaintext, nil
|
||||
}
|
||||
if envelope, err := kms.ParseEnvelope([]byte(plaintext)); err == nil && envelope.ProviderSpecific[encryptedDataKeyField] != nil {
|
||||
return plaintext, nil
|
||||
}
|
||||
provider, err := s.provider()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
keyID, err := provider.GetKeyID(ctx, s.keyID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve credential encryption key: %w", err)
|
||||
}
|
||||
dataKey, err := provider.GenerateDataKey(ctx, &kms.GenerateDataKeyRequest{
|
||||
KeyID: keyID,
|
||||
KeySpec: kms.KeySpecAES256,
|
||||
EncryptionContext: credentialEncryptionContext,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("generate credential data key: %w", err)
|
||||
}
|
||||
defer kms.ClearSensitiveData(dataKey.Plaintext)
|
||||
|
||||
aesgcm, err := newGCM(dataKey.Plaintext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
nonce := make([]byte, aesgcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return "", err
|
||||
}
|
||||
blob := aesgcm.Seal(nonce, nonce, []byte(plaintext), []byte(keyID))
|
||||
|
||||
envelope, err := kms.CreateEnvelope("kms", keyID, base64.StdEncoding.EncodeToString(blob), map[string]interface{}{
|
||||
encryptedDataKeyField: base64.StdEncoding.EncodeToString(dataKey.CiphertextBlob),
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(envelope), nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) decryptSecret(ctx context.Context, stored string) (string, error) {
|
||||
envelope, err := kms.ParseEnvelope([]byte(stored))
|
||||
if err != nil {
|
||||
return stored, nil
|
||||
}
|
||||
blob, err := base64.StdEncoding.DecodeString(envelope.Ciphertext)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("decode credential ciphertext: %w", err)
|
||||
}
|
||||
encDataKey, ok := envelope.ProviderSpecific[encryptedDataKeyField].(string)
|
||||
if !ok || encDataKey == "" {
|
||||
return "", fmt.Errorf("credential envelope missing %s", encryptedDataKeyField)
|
||||
}
|
||||
encDataKeyBytes, err := base64.StdEncoding.DecodeString(encDataKey)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("decode credential data key: %w", err)
|
||||
}
|
||||
|
||||
provider, err := s.provider()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
dataKey, err := provider.Decrypt(ctx, &kms.DecryptRequest{
|
||||
CiphertextBlob: encDataKeyBytes,
|
||||
EncryptionContext: credentialEncryptionContext,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("decrypt credential data key: %w", err)
|
||||
}
|
||||
defer kms.ClearSensitiveData(dataKey.Plaintext)
|
||||
|
||||
aesgcm, err := newGCM(dataKey.Plaintext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(blob) < aesgcm.NonceSize() {
|
||||
return "", fmt.Errorf("credential ciphertext too short")
|
||||
}
|
||||
plain, err := aesgcm.Open(nil, blob[:aesgcm.NonceSize()], blob[aesgcm.NonceSize():], []byte(envelope.KeyID))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("decrypt credential secret: %w", err)
|
||||
}
|
||||
return string(plain), nil
|
||||
}
|
||||
|
||||
func newGCM(dataKey []byte) (cipher.AEAD, error) {
|
||||
block, err := aes.NewCipher(dataKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cipher.NewGCM(block)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) encryptIdentity(ctx context.Context, identity *iam_pb.Identity) (*iam_pb.Identity, error) {
|
||||
cloned := proto.Clone(identity).(*iam_pb.Identity)
|
||||
for _, cred := range cloned.Credentials {
|
||||
encrypted, err := s.encryptSecret(ctx, cred.SecretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cred.SecretKey = encrypted
|
||||
}
|
||||
return cloned, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) decryptIdentity(ctx context.Context, identity *iam_pb.Identity) (*iam_pb.Identity, error) {
|
||||
if identity == nil {
|
||||
return nil, nil
|
||||
}
|
||||
for _, cred := range identity.Credentials {
|
||||
decrypted, err := s.decryptSecret(ctx, cred.SecretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cred.SecretKey = decrypted
|
||||
}
|
||||
return identity, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) encryptServiceAccount(ctx context.Context, sa *iam_pb.ServiceAccount) (*iam_pb.ServiceAccount, error) {
|
||||
cloned := proto.Clone(sa).(*iam_pb.ServiceAccount)
|
||||
if cloned.Credential != nil {
|
||||
encrypted, err := s.encryptSecret(ctx, cloned.Credential.SecretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cloned.Credential.SecretKey = encrypted
|
||||
}
|
||||
return cloned, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) decryptServiceAccount(ctx context.Context, sa *iam_pb.ServiceAccount) (*iam_pb.ServiceAccount, error) {
|
||||
if sa == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if sa.Credential != nil {
|
||||
decrypted, err := s.decryptSecret(ctx, sa.Credential.SecretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sa.Credential.SecretKey = decrypted
|
||||
}
|
||||
return sa, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3ApiConfiguration, error) {
|
||||
config, err := s.CredentialStore.LoadConfiguration(ctx)
|
||||
if err != nil || config == nil {
|
||||
return config, err
|
||||
}
|
||||
for _, identity := range config.Identities {
|
||||
if _, err := s.decryptIdentity(ctx, identity); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) SaveConfiguration(ctx context.Context, config *iam_pb.S3ApiConfiguration) error {
|
||||
cloned := proto.Clone(config).(*iam_pb.S3ApiConfiguration)
|
||||
for _, identity := range cloned.Identities {
|
||||
for _, cred := range identity.Credentials {
|
||||
encrypted, err := s.encryptSecret(ctx, cred.SecretKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cred.SecretKey = encrypted
|
||||
}
|
||||
}
|
||||
return s.CredentialStore.SaveConfiguration(ctx, cloned)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) CreateUser(ctx context.Context, identity *iam_pb.Identity) error {
|
||||
encrypted, err := s.encryptIdentity(ctx, identity)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.CredentialStore.CreateUser(ctx, encrypted)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) GetUser(ctx context.Context, username string) (*iam_pb.Identity, error) {
|
||||
identity, err := s.CredentialStore.GetUser(ctx, username)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.decryptIdentity(ctx, identity)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) UpdateUser(ctx context.Context, username string, identity *iam_pb.Identity) error {
|
||||
encrypted, err := s.encryptIdentity(ctx, identity)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.CredentialStore.UpdateUser(ctx, username, encrypted)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) GetUserByAccessKey(ctx context.Context, accessKey string) (*iam_pb.Identity, error) {
|
||||
identity, err := s.CredentialStore.GetUserByAccessKey(ctx, accessKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.decryptIdentity(ctx, identity)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) CreateAccessKey(ctx context.Context, username string, cred *iam_pb.Credential) error {
|
||||
cloned := proto.Clone(cred).(*iam_pb.Credential)
|
||||
encrypted, err := s.encryptSecret(ctx, cloned.SecretKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cloned.SecretKey = encrypted
|
||||
return s.CredentialStore.CreateAccessKey(ctx, username, cloned)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) CreateServiceAccount(ctx context.Context, sa *iam_pb.ServiceAccount) error {
|
||||
encrypted, err := s.encryptServiceAccount(ctx, sa)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.CredentialStore.CreateServiceAccount(ctx, encrypted)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) UpdateServiceAccount(ctx context.Context, id string, sa *iam_pb.ServiceAccount) error {
|
||||
encrypted, err := s.encryptServiceAccount(ctx, sa)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.CredentialStore.UpdateServiceAccount(ctx, id, encrypted)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) GetServiceAccount(ctx context.Context, id string) (*iam_pb.ServiceAccount, error) {
|
||||
sa, err := s.CredentialStore.GetServiceAccount(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.decryptServiceAccount(ctx, sa)
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) ListServiceAccounts(ctx context.Context) ([]*iam_pb.ServiceAccount, error) {
|
||||
accounts, err := s.CredentialStore.ListServiceAccounts(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, sa := range accounts {
|
||||
if _, err := s.decryptServiceAccount(ctx, sa); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
func (s *EncryptedCredentialStore) GetServiceAccountByAccessKey(ctx context.Context, accessKey string) (*iam_pb.ServiceAccount, error) {
|
||||
sa, err := s.CredentialStore.GetServiceAccountByAccessKey(ctx, accessKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.decryptServiceAccount(ctx, sa)
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
package credential
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/kms"
|
||||
"github.com/seaweedfs/seaweedfs/weed/kms/local"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// fakeStore is a minimal in-memory CredentialStore for exercising the
|
||||
// encryption wrapper; unneeded methods panic via the embedded nil interface.
|
||||
type fakeStore struct {
|
||||
CredentialStore
|
||||
config *iam_pb.S3ApiConfiguration
|
||||
users map[string]*iam_pb.Identity
|
||||
sas map[string]*iam_pb.ServiceAccount
|
||||
}
|
||||
|
||||
func newFakeStore() *fakeStore {
|
||||
return &fakeStore{users: map[string]*iam_pb.Identity{}, sas: map[string]*iam_pb.ServiceAccount{}}
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetName() CredentialStoreTypeName { return "fake" }
|
||||
|
||||
func (f *fakeStore) CreateUser(ctx context.Context, identity *iam_pb.Identity) error {
|
||||
f.users[identity.Name] = proto.Clone(identity).(*iam_pb.Identity)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetUser(ctx context.Context, username string) (*iam_pb.Identity, error) {
|
||||
if u, ok := f.users[username]; ok {
|
||||
return proto.Clone(u).(*iam_pb.Identity), nil
|
||||
}
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
|
||||
func (f *fakeStore) UpdateUser(ctx context.Context, username string, identity *iam_pb.Identity) error {
|
||||
return f.CreateUser(ctx, identity)
|
||||
}
|
||||
|
||||
func (f *fakeStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3ApiConfiguration, error) {
|
||||
return proto.Clone(f.config).(*iam_pb.S3ApiConfiguration), nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) SaveConfiguration(ctx context.Context, config *iam_pb.S3ApiConfiguration) error {
|
||||
f.config = proto.Clone(config).(*iam_pb.S3ApiConfiguration)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) CreateAccessKey(ctx context.Context, username string, cred *iam_pb.Credential) error {
|
||||
f.users[username].Credentials = append(f.users[username].Credentials, proto.Clone(cred).(*iam_pb.Credential))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) CreateServiceAccount(ctx context.Context, sa *iam_pb.ServiceAccount) error {
|
||||
f.sas[sa.Id] = proto.Clone(sa).(*iam_pb.ServiceAccount)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetServiceAccount(ctx context.Context, id string) (*iam_pb.ServiceAccount, error) {
|
||||
return proto.Clone(f.sas[id]).(*iam_pb.ServiceAccount), nil
|
||||
}
|
||||
|
||||
func setupKMS(t *testing.T) {
|
||||
t.Helper()
|
||||
provider, err := local.NewLocalKMSProvider(nil)
|
||||
require.NoError(t, err)
|
||||
kms.SetGlobalKMSProvider(provider)
|
||||
t.Cleanup(func() { kms.SetGlobalKMSProvider(nil) })
|
||||
}
|
||||
|
||||
func testIdentity() *iam_pb.Identity {
|
||||
return &iam_pb.Identity{
|
||||
Name: "alice",
|
||||
Credentials: []*iam_pb.Credential{
|
||||
{AccessKey: "AKIA_TEST", SecretKey: "secret-one"},
|
||||
},
|
||||
Actions: []string{"Read"},
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncryptedStoreRoundTrip(t *testing.T) {
|
||||
setupKMS(t)
|
||||
fake := newFakeStore()
|
||||
store := NewEncryptedCredentialStore(fake, "")
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, store.CreateUser(ctx, testIdentity()))
|
||||
|
||||
stored := fake.users["alice"].Credentials[0].SecretKey
|
||||
assert.NotEqual(t, "secret-one", stored)
|
||||
assert.True(t, strings.HasPrefix(stored, "{"), "stored secret should be an envelope: %s", stored)
|
||||
envelope, err := kms.ParseEnvelope([]byte(stored))
|
||||
require.NoError(t, err)
|
||||
assert.NotEmpty(t, envelope.Ciphertext)
|
||||
assert.NotEmpty(t, envelope.ProviderSpecific[encryptedDataKeyField])
|
||||
|
||||
got, err := store.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "secret-one", got.Credentials[0].SecretKey)
|
||||
assert.Equal(t, "AKIA_TEST", got.Credentials[0].AccessKey)
|
||||
}
|
||||
|
||||
func TestEncryptedStorePlaintextPassthrough(t *testing.T) {
|
||||
fake := newFakeStore()
|
||||
fake.users["bob"] = testIdentity()
|
||||
fake.users["bob"].Name = "bob"
|
||||
store := NewEncryptedCredentialStore(fake, "")
|
||||
|
||||
got, err := store.GetUser(context.Background(), "bob")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "secret-one", got.Credentials[0].SecretKey)
|
||||
}
|
||||
|
||||
func TestEncryptedStoreNoKMSFailsWrite(t *testing.T) {
|
||||
kms.SetGlobalKMSProvider(nil)
|
||||
fake := newFakeStore()
|
||||
store := NewEncryptedCredentialStore(fake, "")
|
||||
|
||||
err := store.CreateUser(context.Background(), testIdentity())
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "KMS provider")
|
||||
assert.Empty(t, fake.users, "failed writes must not persist plaintext secrets")
|
||||
}
|
||||
|
||||
func TestEncryptedStoreSaveLoadConfiguration(t *testing.T) {
|
||||
setupKMS(t)
|
||||
fake := newFakeStore()
|
||||
store := NewEncryptedCredentialStore(fake, "")
|
||||
ctx := context.Background()
|
||||
|
||||
config := &iam_pb.S3ApiConfiguration{Identities: []*iam_pb.Identity{testIdentity()}}
|
||||
require.NoError(t, store.SaveConfiguration(ctx, config))
|
||||
assert.Equal(t, "secret-one", config.Identities[0].Credentials[0].SecretKey,
|
||||
"the caller's config object must not be mutated")
|
||||
|
||||
loaded, err := store.LoadConfiguration(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "secret-one", loaded.Identities[0].Credentials[0].SecretKey)
|
||||
|
||||
stored := fake.config.Identities[0].Credentials[0].SecretKey
|
||||
assert.NotEqual(t, "secret-one", stored)
|
||||
}
|
||||
|
||||
func TestEncryptedStoreServiceAccount(t *testing.T) {
|
||||
setupKMS(t)
|
||||
fake := newFakeStore()
|
||||
store := NewEncryptedCredentialStore(fake, "")
|
||||
ctx := context.Background()
|
||||
|
||||
sa := &iam_pb.ServiceAccount{
|
||||
Id: "sa-1",
|
||||
ParentUser: "alice",
|
||||
Credential: &iam_pb.Credential{AccessKey: "SA_KEY", SecretKey: "sa-secret"},
|
||||
}
|
||||
require.NoError(t, store.CreateServiceAccount(ctx, sa))
|
||||
|
||||
assert.NotEqual(t, "sa-secret", fake.sas["sa-1"].Credential.SecretKey)
|
||||
|
||||
got, err := store.GetServiceAccount(ctx, "sa-1")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "sa-secret", got.Credential.SecretKey)
|
||||
}
|
||||
|
||||
func TestEncryptedStoreNoDoubleWrap(t *testing.T) {
|
||||
setupKMS(t)
|
||||
fake := newFakeStore()
|
||||
store := NewEncryptedCredentialStore(fake, "")
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, store.CreateUser(ctx, testIdentity()))
|
||||
storedOnce := fake.users["alice"].Credentials[0].SecretKey
|
||||
|
||||
// Saving an already-enveloped value must not wrap it again.
|
||||
identity := testIdentity()
|
||||
identity.Credentials[0].SecretKey = storedOnce
|
||||
require.NoError(t, store.UpdateUser(ctx, "alice", identity))
|
||||
assert.Equal(t, storedOnce, fake.users["alice"].Credentials[0].SecretKey)
|
||||
|
||||
got, err := store.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "secret-one", got.Credentials[0].SecretKey)
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3bucket"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/wildcard"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
@@ -1680,6 +1681,7 @@ func (iam *IdentityAccessManagement) Auth(f http.HandlerFunc, action Action) htt
|
||||
// succeeds but authZ denies, so the denied request still audits its
|
||||
// requester; a failed authN resolves no identity at all.
|
||||
identity, errCode, _ := iam.authRequestWithAuthType(r, action)
|
||||
errCode = refineDenialForBucketName(r, identity, errCode)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.V(3).Infof("auth error: %v", errCode)
|
||||
}
|
||||
@@ -1719,6 +1721,7 @@ func (iam *IdentityAccessManagement) AuthPostPolicy(f http.HandlerFunc, action A
|
||||
}
|
||||
}
|
||||
|
||||
errCode = refineDenialForBucketName(r, identity, errCode)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.V(3).Infof("auth error: %v", errCode)
|
||||
}
|
||||
@@ -1727,6 +1730,39 @@ func (iam *IdentityAccessManagement) AuthPostPolicy(f http.HandlerFunc, action A
|
||||
}
|
||||
}
|
||||
|
||||
// refineDenialForBucketName answers 400 InvalidBucketName, as AWS S3 does,
|
||||
// when an authenticated caller is denied on a bucket whose name breaks the S3
|
||||
// naming rules. The rules are public and the answer depends on the name alone,
|
||||
// so it tells the caller nothing about which buckets exist. Authentication
|
||||
// failures (no identity resolved) and every other answer are left unchanged.
|
||||
func refineDenialForBucketName(r *http.Request, identity *Identity, errCode s3err.ErrorCode) s3err.ErrorCode {
|
||||
if errCode != s3err.ErrAccessDenied || identity == nil {
|
||||
return errCode
|
||||
}
|
||||
bucket, _ := s3_constants.GetBucketAndObject(r)
|
||||
if bucket == "" {
|
||||
return errCode
|
||||
}
|
||||
if !isASCIIBucketName(bucket) || s3bucket.VerifyS3BucketName(bucket) != nil {
|
||||
return s3err.ErrInvalidBucketName
|
||||
}
|
||||
return errCode
|
||||
}
|
||||
|
||||
// isASCIIBucketName reports whether name uses only the characters S3 allows
|
||||
// in a bucket name. VerifyS3BucketName checks with unicode.IsLower and
|
||||
// unicode.IsNumber, which also accept letters such as 'ü' and digits such as
|
||||
// '²' that S3 refuses.
|
||||
func isASCIIBucketName(name string) bool {
|
||||
for i := 0; i < len(name); i++ {
|
||||
c := name[i]
|
||||
if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '.' || c == '-') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// recordIdentityInContext stores the authenticated identity, its name and its
|
||||
// principal ARN in the request context. An STS session's name is only an opaque
|
||||
// session subject, so the ARN is what carries the assumed role and session name
|
||||
@@ -3025,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
|
||||
@@ -3042,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 {
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
invalidNameTestAccessKey = "INVALIDNAMEKEY000001"
|
||||
invalidNameTestSecretKey = "invalid-name-secret-for-tests-only"
|
||||
invalidNameTestBucket = "readable-bucket"
|
||||
)
|
||||
|
||||
// newInvalidNameIAM has one identity that may read invalidNameTestBucket only
|
||||
// and a configured anonymous identity with no actions.
|
||||
func newInvalidNameIAM(t *testing.T) *IdentityAccessManagement {
|
||||
t.Helper()
|
||||
iam := &IdentityAccessManagement{hashes: make(map[string]*sync.Pool), hashCounters: make(map[string]*int32)}
|
||||
require.NoError(t, iam.loadS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{Name: "reader", Actions: []string{"Read:" + invalidNameTestBucket},
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: invalidNameTestAccessKey, SecretKey: invalidNameTestSecretKey}}},
|
||||
{Name: s3_constants.AccountAnonymousId},
|
||||
},
|
||||
}))
|
||||
require.True(t, iam.isEnabled())
|
||||
return iam
|
||||
}
|
||||
|
||||
func invalidNameRequest(t *testing.T, bucket string, sign bool) *http.Request {
|
||||
t.Helper()
|
||||
req := mustNewRequest(http.MethodGet, fmt.Sprintf("http://127.0.0.1:8333/%s/key", bucket), 0, nil, t)
|
||||
if sign {
|
||||
require.NoError(t, signRequestV4(req, invalidNameTestAccessKey, invalidNameTestSecretKey))
|
||||
}
|
||||
return mux.SetURLVars(req, map[string]string{"bucket": bucket, "object": "key"})
|
||||
}
|
||||
|
||||
func serveAuth(iam *IdentityAccessManagement, r *http.Request) (int, bool) {
|
||||
ran := false
|
||||
rec := httptest.NewRecorder()
|
||||
iam.Auth(func(w http.ResponseWriter, r *http.Request) { ran = true; w.WriteHeader(http.StatusOK) }, s3_constants.ACTION_READ).ServeHTTP(rec, r)
|
||||
return rec.Code, ran
|
||||
}
|
||||
|
||||
// A denied request on a malformed bucket name answers 400 InvalidBucketName,
|
||||
// as AWS S3 does; a denied request on a well-formed name stays 403.
|
||||
func TestAuthDeniedInvalidBucketName(t *testing.T) {
|
||||
iam := newInvalidNameIAM(t)
|
||||
|
||||
code, ran := serveAuth(iam, invalidNameRequest(t, invalidNameTestBucket, true))
|
||||
assert.True(t, ran, "the identity's own bucket is allowed")
|
||||
assert.Equal(t, http.StatusOK, code)
|
||||
|
||||
code, ran = serveAuth(iam, invalidNameRequest(t, "other-bucket", true))
|
||||
assert.False(t, ran)
|
||||
assert.Equal(t, http.StatusForbidden, code, "a well-formed name the caller may not read stays AccessDenied")
|
||||
|
||||
for _, bucket := range []string{"Bad_Bucket", "ab", "bucket..name", "bücket"} {
|
||||
for _, sign := range []bool{true, false} {
|
||||
code, ran = serveAuth(iam, invalidNameRequest(t, bucket, sign))
|
||||
assert.False(t, ran, bucket)
|
||||
assert.Equal(t, http.StatusBadRequest, code, "bucket %q signed=%v", bucket, sign)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefineDenialForBucketName(t *testing.T) {
|
||||
reader := &Identity{Name: "reader"}
|
||||
req := func(bucket string) *http.Request {
|
||||
return mux.SetURLVars(httptest.NewRequest(http.MethodGet, "/", nil), map[string]string{"bucket": bucket})
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
bucket string
|
||||
identity *Identity
|
||||
in, want s3err.ErrorCode
|
||||
}{
|
||||
{"space in the name", "bucket name", reader, s3err.ErrAccessDenied, s3err.ErrInvalidBucketName},
|
||||
{"non-ASCII letter", "bücket", reader, s3err.ErrAccessDenied, s3err.ErrInvalidBucketName},
|
||||
{"superscript digit", "b²cket", reader, s3err.ErrAccessDenied, s3err.ErrInvalidBucketName},
|
||||
{"too short", "ab", reader, s3err.ErrAccessDenied, s3err.ErrInvalidBucketName},
|
||||
{"well-formed name", "other-bucket", reader, s3err.ErrAccessDenied, s3err.ErrAccessDenied},
|
||||
{"no bucket in the request", "", reader, s3err.ErrAccessDenied, s3err.ErrAccessDenied},
|
||||
{"allowed", "Bad_Bucket", reader, s3err.ErrNone, s3err.ErrNone},
|
||||
{"authentication failed", "Bad_Bucket", nil, s3err.ErrAccessDenied, s3err.ErrAccessDenied},
|
||||
{"bad signature", "Bad_Bucket", nil, s3err.ErrSignatureDoesNotMatch, s3err.ErrSignatureDoesNotMatch},
|
||||
}
|
||||
for _, c := range cases {
|
||||
assert.Equal(t, c.want, refineDenialForBucketName(req(c.bucket), c.identity, c.in), c.name)
|
||||
}
|
||||
}
|
||||
|
||||
// signedPostForm builds a multipart POST Object request for bucket, its policy
|
||||
// signed with secret under postAuthzAccessKey.
|
||||
func signedPostForm(t *testing.T, bucket, key, secret string) *http.Request {
|
||||
t.Helper()
|
||||
now := time.Now().UTC()
|
||||
amzDate := now.Format(iso8601Format)
|
||||
day := now.Format(yyyymmdd)
|
||||
credential := fmt.Sprintf("%s/%s/%s/%s/aws4_request", postAuthzAccessKey, day, postAuthzRegion, postAuthzService)
|
||||
policyJSON := fmt.Sprintf(`{"expiration":"%s","conditions":[["eq","$bucket","%s"],["eq","$key","%s"],`+
|
||||
`["eq","$x-amz-credential","%s"],["eq","$x-amz-algorithm","AWS4-HMAC-SHA256"],["eq","$x-amz-date","%s"]]}`,
|
||||
now.Add(time.Hour).Format("2006-01-02T15:04:05.000Z"), bucket, key, credential, amzDate)
|
||||
encodedPolicy := base64.StdEncoding.EncodeToString([]byte(policyJSON))
|
||||
signature := getSignature(getSigningKey(secret, day, postAuthzRegion, postAuthzService), encodedPolicy)
|
||||
|
||||
var buf bytes.Buffer
|
||||
writer := multipart.NewWriter(&buf)
|
||||
for _, field := range [][2]string{{"bucket", bucket}, {"key", key}, {"x-amz-credential", credential},
|
||||
{"x-amz-algorithm", "AWS4-HMAC-SHA256"}, {"x-amz-date", amzDate}, {"policy", encodedPolicy}, {"x-amz-signature", signature}} {
|
||||
require.NoError(t, writer.WriteField(field[0], field[1]))
|
||||
}
|
||||
filePart, err := writer.CreateFormFile("file", "payload.txt")
|
||||
require.NoError(t, err)
|
||||
_, err = filePart.Write([]byte("payload"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, writer.Close())
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/"+bucket, &buf)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
return mux.SetURLVars(req, map[string]string{"bucket": bucket})
|
||||
}
|
||||
|
||||
// A browser POST upload authenticates in the handler, after AuthPostPolicy has
|
||||
// delegated it, so its denials are refined there: a verified form denied on a
|
||||
// malformed bucket name answers 400, a bad signature or a well-formed name 403.
|
||||
func TestPostPolicyDeniedInvalidBucketName(t *testing.T) {
|
||||
s3a := newPostAuthzServer(t)
|
||||
for _, bucket := range []string{"Bad_Bucket", "other-bucket"} {
|
||||
s3a.bucketRegistry.setMetadataCache(&BucketMetaData{Name: bucket})
|
||||
}
|
||||
// A second identity may write Bad_Bucket, except under denied/.
|
||||
require.NoError(t, s3a.iam.loadS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{Name: "tester", Actions: []string{"Write:" + postAuthzBucket},
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: postAuthzAccessKey, SecretKey: postAuthzSecretKey}}},
|
||||
},
|
||||
}))
|
||||
require.NoError(t, s3a.policyEngine.engine.SetBucketPolicy("Bad_Bucket", `{"Version":"2012-10-17","Statement":[`+
|
||||
`{"Effect":"Deny","Principal":"*","Action":["s3:PutObject"],"Resource":["arn:aws:s3:::Bad_Bucket/denied/*"]}]}`))
|
||||
|
||||
serve := func(r *http.Request) *httptest.ResponseRecorder {
|
||||
rec := httptest.NewRecorder()
|
||||
s3a.iam.AuthPostPolicy(s3a.PostPolicyBucketHandler, s3_constants.ACTION_WRITE).ServeHTTP(rec, r)
|
||||
return rec
|
||||
}
|
||||
|
||||
rec := serve(signedPostForm(t, "Bad_Bucket", "k", postAuthzSecretKey))
|
||||
assert.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
|
||||
assert.Contains(t, rec.Body.String(), "InvalidBucketName")
|
||||
|
||||
rec = serve(signedPostForm(t, "Bad_Bucket", "k", "not-the-secret"))
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String())
|
||||
assert.Contains(t, rec.Body.String(), "SignatureDoesNotMatch", "a form that fails verification is not refined")
|
||||
|
||||
rec = serve(signedPostForm(t, "other-bucket", "k", postAuthzSecretKey))
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String())
|
||||
assert.Contains(t, rec.Body.String(), "AccessDenied")
|
||||
|
||||
// The per-key authorization after the coarse Write check is refined too.
|
||||
require.NoError(t, s3a.iam.loadS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{Name: "tester", Actions: []string{"Write:Bad_Bucket"},
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: postAuthzAccessKey, SecretKey: postAuthzSecretKey}}},
|
||||
},
|
||||
}))
|
||||
rec = serve(signedPostForm(t, "Bad_Bucket", "denied/k", postAuthzSecretKey))
|
||||
assert.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
|
||||
assert.Contains(t, rec.Body.String(), "InvalidBucketName")
|
||||
}
|
||||
|
||||
// Unsigned GET/HEAD object reads are authorized inside the object handlers, not
|
||||
// by Auth; their denial on a malformed bucket name answers 400 as well.
|
||||
func TestAnonymousReadDeniedInvalidBucketName(t *testing.T) {
|
||||
read := func(s3a *S3ApiServer, method, bucket string) int {
|
||||
r := httptest.NewRequest(method, "/"+bucket+"/key", nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": bucket, "object": "key"})
|
||||
handler := s3a.GetObjectHandler
|
||||
if method == http.MethodHead {
|
||||
handler = s3a.HeadObjectHandler
|
||||
}
|
||||
rr := httptest.NewRecorder()
|
||||
s3a.AuthWithPublicRead(handler, s3_constants.ACTION_READ)(rr, r)
|
||||
return rr.Code
|
||||
}
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
s3a, _ := newAnonymousReadTestServer(t)
|
||||
s3a.iam.identityAnonymous = &Identity{Name: s3_constants.AccountAnonymousId}
|
||||
assert.Equal(t, http.StatusBadRequest, read(s3a, method, "Bad_Bucket"), method)
|
||||
assert.Equal(t, http.StatusForbidden, read(s3a, method, "other-bucket"), "%s: a well-formed missing bucket stays masked", method)
|
||||
|
||||
// No anonymous identity configured: no identity resolves, as in Auth.
|
||||
s3a, _ = newAnonymousReadTestServer(t)
|
||||
assert.Equal(t, http.StatusForbidden, read(s3a, method, "Bad_Bucket"), method)
|
||||
}
|
||||
}
|
||||
|
||||
// An existing private key and a missing key in the same malformed-name bucket
|
||||
// must answer alike, or the status code tells an anonymous caller which keys
|
||||
// exist.
|
||||
func TestAnonymousReadDeniedInvalidBucketNameExistingKey(t *testing.T) {
|
||||
const bucket = "bücket"
|
||||
read := func(s3a *S3ApiServer, method, object string) int {
|
||||
r := httptest.NewRequest(method, "/"+bucket+"/"+object, nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": bucket, "object": object})
|
||||
handler := s3a.GetObjectHandler
|
||||
if method == http.MethodHead {
|
||||
handler = s3a.HeadObjectHandler
|
||||
}
|
||||
rr := httptest.NewRecorder()
|
||||
s3a.AuthWithPublicRead(handler, s3_constants.ACTION_READ)(rr, r)
|
||||
return rr.Code
|
||||
}
|
||||
setup := func(anonymous bool) *S3ApiServer {
|
||||
s3a, f := newAnonymousReadTestServer(t)
|
||||
if anonymous {
|
||||
s3a.iam.identityAnonymous = &Identity{Name: s3_constants.AccountAnonymousId}
|
||||
}
|
||||
s3a.bucketConfigCache.Set(bucket, &BucketConfig{Name: bucket, Ownership: s3_constants.OwnershipObjectWriter})
|
||||
f.entries["/buckets/"+bucket+"/private"] = anonymousReadEntry([]byte(`[]`))
|
||||
f.entries["/buckets/"+bucket+"/public"] = anonymousReadEntry(anonymousReadGrant("READ"))
|
||||
return s3a
|
||||
}
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
s3a := setup(true)
|
||||
assert.Equal(t, http.StatusOK, read(s3a, method, "public"), "%s: a public key is still served", method)
|
||||
assert.Equal(t, http.StatusBadRequest, read(s3a, method, "missing"), method)
|
||||
assert.Equal(t, http.StatusBadRequest, read(s3a, method, "private"), "%s: an existing private key answers like a missing one", method)
|
||||
|
||||
// No anonymous identity configured: both stay 403, as in Auth.
|
||||
s3a = setup(false)
|
||||
assert.Equal(t, http.StatusForbidden, read(s3a, method, "missing"), method)
|
||||
assert.Equal(t, http.StatusForbidden, read(s3a, method, "private"), method)
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
@@ -95,11 +94,6 @@ func (iam *IdentityAccessManagement) doesPolicySignatureV2Match(formValues http.
|
||||
return nil, s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
bucket := formValues.Get("bucket")
|
||||
if !identity.CanDo(s3_constants.ACTION_WRITE, bucket, "") {
|
||||
return nil, s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
policy := formValues.Get("Policy")
|
||||
if policy == "" {
|
||||
return nil, s3err.ErrMissingFields
|
||||
|
||||
@@ -858,11 +858,6 @@ func (iam *IdentityAccessManagement) doesPolicySignatureV4Match(formValues http.
|
||||
return nil, s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
bucket := formValues.Get("bucket")
|
||||
if !identity.CanDo(s3_constants.ACTION_WRITE, bucket, "") {
|
||||
return nil, s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
// Get signing key.
|
||||
signingKey := getSigningKey(cred.SecretKey, credHeader.scope.date.Format(yyyymmdd), credHeader.scope.region, credHeader.scope.service)
|
||||
|
||||
|
||||
@@ -2,8 +2,12 @@ package s3api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"path"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -83,6 +87,117 @@ func (s3a *S3ApiServer) validateTableBucketObjectPath(bucket, object string) err
|
||||
return nil
|
||||
}
|
||||
|
||||
// volumeVerifyKey matches the object Snowflake writes, reads, lists and
|
||||
// deletes at the base of an S3-compatible external volume before it creates
|
||||
// or writes Iceberg tables there (SYSTEM$VERIFY_EXTERNAL_VOLUME, also run
|
||||
// implicitly): <base>/verify_<epoch milliseconds>_<number>, a 21-byte body.
|
||||
// A table bucket refuses every key outside the Iceberg layout, so without
|
||||
// this exception Snowflake cannot use a table bucket as an external volume.
|
||||
//
|
||||
// The exception is narrow so that it cannot be used to store data:
|
||||
// - only at the bucket root: nothing can be encoded in a prefix, written
|
||||
// into a hidden tree or take a namespace or table name;
|
||||
// - one shape: 13 digits of epoch milliseconds, then 1-10 digits;
|
||||
// - never a directory: a namespace may carry a name of that shape, and the
|
||||
// key then names its directory (volumeVerifyKeyIsDirectory);
|
||||
// - a PUT must be dated within volumeVerifyWindow of the server's clock,
|
||||
// declare a Content-Length of at most volumeVerifyMaxBytes (no chunked or
|
||||
// undeclared body), and carry no user metadata, tagging, stored content
|
||||
// headers or extraction request (volumeVerifyPutAllowed). Reads and
|
||||
// deletes take a key of any date, so an object a check left behind can
|
||||
// still be removed.
|
||||
//
|
||||
// Only the calls the check makes (PUT, GET, HEAD, DELETE, DeleteObjects)
|
||||
// accept the key; multipart, copy, rename, ACL, tagging and POST policy keep
|
||||
// the plain layout rule.
|
||||
var volumeVerifyKey = regexp.MustCompile(`^verify_([0-9]{13})_[0-9]{1,10}$`)
|
||||
|
||||
const (
|
||||
volumeVerifyMaxBytes = 1024
|
||||
volumeVerifyWindow = time.Hour
|
||||
)
|
||||
|
||||
// volumeVerifyNow is the clock a PUT's key is checked against.
|
||||
var volumeVerifyNow = time.Now
|
||||
|
||||
// volumeVerifyKeyTime is the time a verification key is dated, and whether
|
||||
// the object has the key's shape.
|
||||
func volumeVerifyKeyTime(object string) (time.Time, bool) {
|
||||
m := volumeVerifyKey.FindStringSubmatch(strings.TrimPrefix(object, "/"))
|
||||
if m == nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
ms, err := strconv.ParseInt(m[1], 10, 64)
|
||||
if err != nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return time.UnixMilli(ms), true
|
||||
}
|
||||
|
||||
func isVolumeVerifyKey(object string) bool {
|
||||
_, ok := volumeVerifyKeyTime(object)
|
||||
return ok
|
||||
}
|
||||
|
||||
// volumeVerifyLookup reads the entry a verification key names.
|
||||
var volumeVerifyLookup = func(s3a *S3ApiServer, dir, name string) (*filer_pb.Entry, error) {
|
||||
return s3a.getEntry(dir, name)
|
||||
}
|
||||
|
||||
// volumeVerifyKeyIsDirectory reports whether the key names a directory (a
|
||||
// namespace), or whether that cannot be known.
|
||||
func (s3a *S3ApiServer) volumeVerifyKeyIsDirectory(bucket, object string) bool {
|
||||
entry, err := volumeVerifyLookup(s3a, s3a.bucketDir(bucket), strings.TrimPrefix(object, "/"))
|
||||
if err != nil {
|
||||
return !errors.Is(err, filer_pb.ErrNotFound)
|
||||
}
|
||||
return entry != nil && entry.IsDirectory
|
||||
}
|
||||
|
||||
// validateTableBucketObjectPathOrVerify is validateTableBucketObjectPath that
|
||||
// also accepts the external-volume verification key, and reports it so the
|
||||
// PUT handler can apply its limits.
|
||||
func (s3a *S3ApiServer) validateTableBucketObjectPathOrVerify(bucket, object string) (isVerify bool, err error) {
|
||||
if !s3a.isTableBucket(bucket) {
|
||||
return false, nil
|
||||
}
|
||||
if isVolumeVerifyKey(object) && !s3a.volumeVerifyKeyIsDirectory(bucket, object) {
|
||||
return true, nil
|
||||
}
|
||||
return false, s3a.validateTableBucketObjectPath(bucket, object)
|
||||
}
|
||||
|
||||
// volumeVerifyPutAllowed reports whether a PUT to the verification key is
|
||||
// dated now, declares a small body and stores nothing beside it.
|
||||
func volumeVerifyPutAllowed(r *http.Request, object string) bool {
|
||||
at, ok := volumeVerifyKeyTime(object)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if d := volumeVerifyNow().Sub(at); d > volumeVerifyWindow || d < -volumeVerifyWindow {
|
||||
return false
|
||||
}
|
||||
if r.ContentLength < 0 || r.ContentLength > volumeVerifyMaxBytes || len(r.TransferEncoding) > 0 {
|
||||
return false
|
||||
}
|
||||
if isExtractZip(r) {
|
||||
return false
|
||||
}
|
||||
for name, values := range r.Header {
|
||||
n := strings.ToLower(name)
|
||||
if strings.HasPrefix(n, "x-amz-meta-") || n == "x-amz-tagging" || n == "content-disposition" ||
|
||||
n == "response-content-disposition" || n == "content-language" ||
|
||||
n == "cache-control" || n == "expires" || n == "x-amz-website-redirect-location" {
|
||||
return false
|
||||
}
|
||||
// aws-chunked only frames the body; any other coding is stored.
|
||||
if n == "content-encoding" && storedContentEncoding(values) != "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) bucketPrefix(bucket string) string {
|
||||
return s3a.bucketDir(bucket) + "/"
|
||||
}
|
||||
|
||||
@@ -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 == "" {
|
||||
@@ -397,7 +401,7 @@ func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) {
|
||||
if cleanupErr := s.deleteMetadataFile(r.Context(), metadataBucket, metadataPath, metadataFileName); cleanupErr != nil {
|
||||
glog.V(1).Infof("Iceberg: failed to cleanup metadata file %s after update failure: %v", newMetadataLocation, cleanupErr)
|
||||
}
|
||||
glog.Errorf("Iceberg: CommitTable UpdateTable error: %v", err)
|
||||
logManagerError("CommitTable UpdateTable", err)
|
||||
writeManagerError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -140,7 +140,7 @@ func (s *Server) handleCreateNamespace(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusConflict, "AlreadyExistsException", err.Error())
|
||||
return
|
||||
}
|
||||
glog.Errorf("Iceberg: CreateNamespace error: %v", err)
|
||||
logManagerError("CreateNamespace", err)
|
||||
writeManagerError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -109,7 +109,7 @@ func (s *Server) handleCommitTransaction(w http.ResponseWriter, r *http.Request)
|
||||
writeError(w, http.StatusConflict, "CommitFailedException", "Version token mismatch")
|
||||
return
|
||||
}
|
||||
glog.Errorf("Iceberg: CommitTransaction UpdateTable error: %v", err)
|
||||
logManagerError("CommitTransaction UpdateTable", err)
|
||||
writeManagerError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
func TestLogManagerErrorRefusalsAreNotErrors(t *testing.T) {
|
||||
var refusals, faults []string
|
||||
oldR, oldF := logManagerRefusal, logManagerFault
|
||||
logManagerRefusal = func(f string, a ...interface{}) { refusals = append(refusals, fmt.Sprintf(f, a...)) }
|
||||
logManagerFault = func(f string, a ...interface{}) { faults = append(faults, fmt.Sprintf(f, a...)) }
|
||||
defer func() { logManagerRefusal, logManagerFault = oldR, oldF }()
|
||||
for _, c := range []struct {
|
||||
err error
|
||||
fault bool
|
||||
}{
|
||||
{&s3tables.S3TablesError{Type: s3tables.ErrCodeAccessDenied, Message: "not authorized to create namespace in this bucket"}, false},
|
||||
{&s3tables.S3TablesError{Type: s3tables.ErrCodeNoSuchNamespace, Message: "no such namespace"}, false},
|
||||
{&s3tables.S3TablesError{Type: s3tables.ErrCodeNamespaceAlreadyExists, Message: "exists"}, false},
|
||||
{errors.New("filer: connection refused"), true}, // positive control: a real fault stays at ERROR
|
||||
} {
|
||||
refusals, faults = nil, nil
|
||||
logManagerError("CreateNamespace", c.err)
|
||||
wantFaults, wantRefusals := 0, 1
|
||||
if c.fault {
|
||||
wantFaults, wantRefusals = 1, 0
|
||||
}
|
||||
if len(faults) != wantFaults || len(refusals) != wantRefusals {
|
||||
t.Errorf("%v: %d ERROR and %d refusal log(s), want %d and %d (refusals %v, faults %v)", c.err, len(faults), len(refusals), wantFaults, wantRefusals, refusals, faults)
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
-16
@@ -158,7 +158,9 @@ func nameValidationError(err error) bool {
|
||||
// errors (400) and must carry the reason -- a variant field without
|
||||
// format-version 3 otherwise reads as a bare 500 with "variant is not supported
|
||||
// until v3" only in the log. Anything else is a server fault (500).
|
||||
func writeManagerError(w http.ResponseWriter, err error) {
|
||||
// classifyManagerError maps a storage-layer error to the HTTP status, the
|
||||
// Iceberg error type and the message the catalog answers with.
|
||||
func classifyManagerError(err error) (int, string, string) {
|
||||
switch {
|
||||
case nameValidationError(err),
|
||||
errors.Is(err, iceberg.ErrInvalidSchema),
|
||||
@@ -166,8 +168,7 @@ func writeManagerError(w http.ResponseWriter, err error) {
|
||||
errors.Is(err, iceberg.ErrInvalidTypeString),
|
||||
errors.Is(err, iceberg.ErrInvalidTransform),
|
||||
errors.Is(err, iceberg.ErrInvalidArgument):
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", err.Error())
|
||||
return
|
||||
return http.StatusBadRequest, "BadRequestException", err.Error()
|
||||
}
|
||||
// Storage-layer failures are mostly the client's, not the server's. Reporting
|
||||
// a missing namespace or a name conflict as a 500 makes the catalog look
|
||||
@@ -179,31 +180,49 @@ func writeManagerError(w http.ResponseWriter, err error) {
|
||||
// The storage-layer message names the resolved bucket, which for a
|
||||
// client that sent no warehouse at all is the default one it never
|
||||
// asked for, so say how to select a real table bucket.
|
||||
writeError(w, http.StatusNotFound, "NoSuchNamespaceException",
|
||||
fmt.Sprintf("%s: each table bucket is a separate catalog, select one with warehouse=s3://<table-bucket>/ or /v1/<table-bucket>/", tableErr.Message))
|
||||
return http.StatusNotFound, "NoSuchNamespaceException",
|
||||
fmt.Sprintf("%s: each table bucket is a separate catalog, select one with warehouse=s3://<table-bucket>/ or /v1/<table-bucket>/", tableErr.Message)
|
||||
case s3tables.ErrCodeNoSuchNamespace:
|
||||
writeError(w, http.StatusNotFound, "NoSuchNamespaceException", tableErr.Message)
|
||||
return http.StatusNotFound, "NoSuchNamespaceException", tableErr.Message
|
||||
case s3tables.ErrCodeNoSuchTable:
|
||||
writeError(w, http.StatusNotFound, "NoSuchTableException", tableErr.Message)
|
||||
return http.StatusNotFound, "NoSuchTableException", tableErr.Message
|
||||
case s3tables.ErrCodeNoSuchView:
|
||||
writeError(w, http.StatusNotFound, "NoSuchViewException", tableErr.Message)
|
||||
return http.StatusNotFound, "NoSuchViewException", tableErr.Message
|
||||
case s3tables.ErrCodeNamespaceAlreadyExists, s3tables.ErrCodeBucketAlreadyExists,
|
||||
s3tables.ErrCodeTableAlreadyExists, s3tables.ErrCodeViewAlreadyExists:
|
||||
writeError(w, http.StatusConflict, "AlreadyExistsException", tableErr.Message)
|
||||
return http.StatusConflict, "AlreadyExistsException", tableErr.Message
|
||||
case s3tables.ErrCodeNamespaceNotEmpty, s3tables.ErrCodeBucketNotEmpty:
|
||||
writeError(w, http.StatusConflict, "AlreadyExistsException", tableErr.Message)
|
||||
return http.StatusConflict, "AlreadyExistsException", tableErr.Message
|
||||
case s3tables.ErrCodeConflict:
|
||||
writeError(w, http.StatusConflict, "CommitFailedException", tableErr.Message)
|
||||
return http.StatusConflict, "CommitFailedException", tableErr.Message
|
||||
case s3tables.ErrCodeAccessDenied:
|
||||
writeError(w, http.StatusForbidden, "ForbiddenException", tableErr.Message)
|
||||
return http.StatusForbidden, "ForbiddenException", tableErr.Message
|
||||
case s3tables.ErrCodeInvalidRequest, s3tables.ErrCodeInvalidIcebergLayout:
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", tableErr.Message)
|
||||
default:
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", err.Error())
|
||||
return http.StatusBadRequest, "BadRequestException", tableErr.Message
|
||||
}
|
||||
}
|
||||
return http.StatusInternalServerError, "InternalServerError", err.Error()
|
||||
}
|
||||
|
||||
func writeManagerError(w http.ResponseWriter, err error) {
|
||||
status, typ, msg := classifyManagerError(err)
|
||||
writeError(w, status, typ, msg)
|
||||
}
|
||||
|
||||
// A storage-layer error the catalog answers with a 4xx (access denied, not
|
||||
// found, already exists, not empty, a conflict) is the API refusing a request
|
||||
// as intended, not a server fault; it is logged at V(1). A 5xx stays at ERROR.
|
||||
var (
|
||||
logManagerRefusal = func(format string, args ...interface{}) { glog.V(1).Infof(format, args...) }
|
||||
logManagerFault = glog.Errorf
|
||||
)
|
||||
|
||||
func logManagerError(op string, err error) {
|
||||
if status, _, _ := classifyManagerError(err); status >= 400 && status < 500 {
|
||||
logManagerRefusal("Iceberg: %s refused (%d): %v", op, status, err)
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "InternalServerError", err.Error())
|
||||
logManagerFault("Iceberg: %s error: %v", op, err)
|
||||
}
|
||||
|
||||
// resolveWarehouseBucket maps a client-supplied warehouse value to a table
|
||||
|
||||
@@ -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"))
|
||||
}
|
||||
@@ -171,10 +171,12 @@ func (s3a *S3ApiServer) authorizeAnonymousBucketList(r *http.Request, bucket str
|
||||
|
||||
// writeAnonymousAwareNotFound keeps missing-bucket and missing-key misses
|
||||
// indistinguishable from denied reads for anonymous callers: a 404 only
|
||||
// reaches the wire when the bucket is anonymously listable.
|
||||
// reaches the wire when the bucket is anonymously listable. The denial is
|
||||
// refined like Auth's, so a malformed bucket name answers InvalidBucketName.
|
||||
func (s3a *S3ApiServer) writeAnonymousAwareNotFound(w http.ResponseWriter, r *http.Request, bucket string, code s3err.ErrorCode) {
|
||||
if isAnonymousObjectRead(r) && s3a.authorizeAnonymousBucketList(r, bucket) != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
identity, _ := s3_constants.GetIdentityFromContext(r).(*Identity)
|
||||
s3err.WriteErrorResponse(w, r, refineDenialForBucketName(r, identity, s3err.ErrAccessDenied))
|
||||
return
|
||||
}
|
||||
s3err.WriteErrorResponse(w, r, code)
|
||||
|
||||
@@ -299,7 +299,9 @@ func TestAnonymousObjectACLConfiguredIdentity(t *testing.T) {
|
||||
}{
|
||||
{"legacy anonymous permission", false, []Action{s3_constants.ACTION_READ}, "", false, 200},
|
||||
{"identity policy allow", false, nil, `{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::b/*"}`, false, 200},
|
||||
{"identity deny beats object ACL", true, nil, `{"Effect":"Deny","Action":"s3:GetObject","Resource":"arn:aws:s3:::b/*"}`, false, 403},
|
||||
// The fixture bucket "b" is shorter than S3's three-character minimum,
|
||||
// so a denial for a resolved identity answers InvalidBucketName.
|
||||
{"identity deny beats object ACL", true, nil, `{"Effect":"Deny","Action":"s3:GetObject","Resource":"arn:aws:s3:::b/*"}`, false, 400},
|
||||
{"disabled identity cannot grant", false, []Action{s3_constants.ACTION_READ}, "", true, 403},
|
||||
{"public ACL does not require identity", true, nil, "", true, 200},
|
||||
} {
|
||||
|
||||
@@ -804,7 +804,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
bucket, object := s3_constants.GetBucketAndObject(r)
|
||||
glog.V(3).Infof("GetObjectHandler %s %s", bucket, object)
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object); err != nil {
|
||||
if _, err := s3a.validateTableBucketObjectPathOrVerify(bucket, object); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
@@ -2499,7 +2499,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
|
||||
bucket, object := s3_constants.GetBucketAndObject(r)
|
||||
glog.V(3).Infof("HeadObjectHandler %s %s", bucket, object)
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object); err != nil {
|
||||
if _, err := s3a.validateTableBucketObjectPathOrVerify(bucket, object); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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/s3err"
|
||||
@@ -375,6 +376,63 @@ func TestCopyObjectPartInlineContent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The handler must route an inline-Content source away from the raw chunk
|
||||
// copy — CopyObjectPartHandler has to send it through the plaintext stream
|
||||
// path or the part lands as zeros.
|
||||
func TestCopyObjectPartHandlerInlineContent(t *testing.T) {
|
||||
volume := startFakeVolumeServer(t)
|
||||
filerImpl := &ambiguousPutFiler{volume: volume, apply: true, entries: map[string]*filer_pb.Entry{}}
|
||||
s3a := newPutTestServer(t, startFakeFiler(t, filerImpl))
|
||||
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
|
||||
util_http.InitGlobalHttpClient()
|
||||
|
||||
content := []byte("inline-content")
|
||||
uploadID := s3a.generateUploadID("dst")
|
||||
filerImpl.entries["/buckets/b"] = &filer_pb.Entry{Name: "b", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}}
|
||||
filerImpl.entries["/buckets/b/src"] = &filer_pb.Entry{
|
||||
Name: "src",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: uint64(len(content))},
|
||||
Content: content,
|
||||
}
|
||||
filerImpl.entries["/buckets/b/.uploads/"+uploadID] = &filer_pb.Entry{
|
||||
Name: uploadID,
|
||||
IsDirectory: true,
|
||||
Extended: map[string][]byte{s3_constants.ExtMultipartObjectKey: []byte("dst")},
|
||||
}
|
||||
|
||||
r := httptest.NewRequest(http.MethodPut, "/b/dst?partNumber=1&uploadId="+uploadID, nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": "b", "object": "dst"})
|
||||
r.Header.Set("X-Amz-Copy-Source", "/b/src")
|
||||
r.Header.Set("x-amz-copy-source-range", "bytes=2-5")
|
||||
w := httptest.NewRecorder()
|
||||
s3a.CopyObjectPartHandler(w, r)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("CopyObjectPartHandler = %d %s, want 200", w.Code, w.Body.String())
|
||||
}
|
||||
wantMd5 := fmt.Sprintf("%x", md5.Sum(content[2:6]))
|
||||
if !strings.Contains(w.Body.String(), wantMd5) {
|
||||
t.Errorf("response %q does not contain copied-range ETag %q", w.Body.String(), wantMd5)
|
||||
}
|
||||
var partEntry *filer_pb.Entry
|
||||
for key, e := range filerImpl.entries {
|
||||
if strings.Contains(key, uploadID) && !e.IsDirectory {
|
||||
partEntry = e
|
||||
}
|
||||
}
|
||||
if partEntry == nil || len(partEntry.Chunks) == 0 {
|
||||
t.Fatalf("no part entry with chunks stored: %+v", filerImpl.entries)
|
||||
}
|
||||
found := false
|
||||
for _, stored := range volume.stored {
|
||||
if bytes.Contains(stored, content[2:6]) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("destination volume does not hold the copied content bytes")
|
||||
}
|
||||
}
|
||||
|
||||
// An empty part must carry the empty-body MD5 on the stored entry too, so
|
||||
// ListParts and complete's composite ETag see the same digest CopyPartResult
|
||||
// reported.
|
||||
|
||||
@@ -210,7 +210,7 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
|
||||
// The filer ops below each retry, and a failover walk runs the whole set
|
||||
// once per filer, so the backoff comes out of one allowance held here.
|
||||
r = r.WithContext(withFilerRetryBudget(r.Context(), filerRetryRequestBudget))
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object); err != nil {
|
||||
if _, err := s3a.validateTableBucketObjectPathOrVerify(bucket, object); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
@@ -479,7 +479,7 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
|
||||
deleteErrors = append(deleteErrors, deleteErrorFromCode(validationCode, object.Key, object.VersionId))
|
||||
continue
|
||||
}
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object.Key); err != nil {
|
||||
if _, err := s3a.validateTableBucketObjectPathOrVerify(bucket, object.Key); err != nil {
|
||||
deleteErrors = append(deleteErrors, deleteErrorFromCode(s3err.ErrAccessDenied, object.Key, object.VersionId))
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -540,18 +540,6 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsReq
|
||||
}
|
||||
dirName, entryName, _ := entryUrlEncode(dir, entry.Name, encodingTypeUrl)
|
||||
if entry.IsDirectory {
|
||||
if cursor.emitDirAsCommonPrefix {
|
||||
cursor.emitDirAsCommonPrefix = false
|
||||
dirPrefix := fmt.Sprintf("%s/%s/", dir, entry.Name)[len(bucketPrefix):]
|
||||
commonPrefixes = append(commonPrefixes, PrefixEntry{
|
||||
Prefix: dirPrefix,
|
||||
})
|
||||
cursor.maxKeys--
|
||||
lastEntryWasCommonPrefix = true
|
||||
lastCommonPrefix = dirPrefix
|
||||
lastPrefixNullBackers, lastPrefixConfirmed = nil, true
|
||||
return
|
||||
}
|
||||
if originalPrefix != "" {
|
||||
normalizedPrefix := strings.TrimPrefix(strings.TrimSuffix(originalPrefix, "/"), "/")
|
||||
if normalizedPrefix != "" {
|
||||
@@ -806,9 +794,6 @@ type ListingCursor struct {
|
||||
// resolvePendingNulls settles trailing null objects whose .versions sibling
|
||||
// has not streamed yet before a page is declared full.
|
||||
resolvePendingNulls func() error
|
||||
// emitDirAsCommonPrefix marks the next directory entry passed to the entry
|
||||
// callback for reporting as a CommonPrefix rather than a Contents key.
|
||||
emitDirAsCommonPrefix bool
|
||||
// prefixObjectKeyOnly limits the next prefix-object entry passed to the entry
|
||||
// callback to its plain key; its "<name>/" CommonPrefix is deferred to the
|
||||
// directory's own block position.
|
||||
@@ -1024,10 +1009,8 @@ func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.
|
||||
}
|
||||
isKeyObject := e.IsDirectoryKeyObject() && !e.IsPrefixObject()
|
||||
if delimiter != "/" || cursor.prefixEndsOnDelimiter {
|
||||
// A trailing-slash prefix (e.g. "logs/") names one directory and asks
|
||||
// whether it exists, so a real but empty directory must be reported for
|
||||
// that probe.
|
||||
explicitDirProbe := cursor.prefixEndsOnDelimiter
|
||||
// A trailing-slash prefix (e.g. "logs/") names one directory, so the
|
||||
// recursion below answers whether it exists and what it holds.
|
||||
if cursor.prefixEndsOnDelimiter {
|
||||
cursor.prefixEndsOnDelimiter = false
|
||||
}
|
||||
@@ -1036,13 +1019,7 @@ func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.
|
||||
// appear as regular keys in recursive listing mode.
|
||||
eachEntryFn(dir, emitEntry)
|
||||
}
|
||||
// Recurse into subdirectory to list any children, noting whether the
|
||||
// subtree produced any entries.
|
||||
childEmitted := false
|
||||
subNextMarker, subErr := s3a.doListFilerEntries(ctx, client, listDirectoryRequest{dir: dir + "/" + e.Name, marker: subMarker, delimiter: delimiter, bucket: bucket}, cursor, func(d string, ent *filer_pb.Entry) {
|
||||
childEmitted = true
|
||||
eachEntryFn(d, ent)
|
||||
})
|
||||
subNextMarker, subErr := s3a.doListFilerEntries(ctx, client, listDirectoryRequest{dir: dir + "/" + e.Name, marker: subMarker, delimiter: delimiter, bucket: bucket}, cursor, eachEntryFn)
|
||||
if subErr != nil {
|
||||
return fmt.Errorf("doListFilerEntries2: %w", subErr)
|
||||
}
|
||||
@@ -1052,26 +1029,10 @@ func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.
|
||||
// keep a resume position that re-enters it.
|
||||
cursor.isTruncated = true
|
||||
}
|
||||
// A real but empty directory (created out of band via mount, mkdir or
|
||||
// the filer API, so it carries no MIME) is otherwise invisible to S3
|
||||
// clients that detect directories by listing it under its own "<dir>/"
|
||||
// prefix. Answer that explicit probe so tools like hadoop-aws can find
|
||||
// the directory: a delimited listing reports it as a CommonPrefix --
|
||||
// a real key in Contents would look like an object a client can read --
|
||||
// while a recursive listing keeps the directory marker key it used.
|
||||
// Plain listings are left untouched, so empty directories left behind
|
||||
// by deleted objects are not shown as keys.
|
||||
// A directory that still holds version history no longer names anything,
|
||||
// so it gets no marker either.
|
||||
if explicitDirProbe && !isKeyObject && !childEmitted && !cursor.isTruncated && e.Attributes != nil &&
|
||||
!s3a.dirHoldsOnlyHiddenEntries(ctx, client, bucket, dir+"/"+e.Name, cursor) {
|
||||
if delimiter == "/" {
|
||||
cursor.emitDirAsCommonPrefix = true
|
||||
} else {
|
||||
emitEntry.Attributes.Mime = s3_constants.FolderMimeType
|
||||
}
|
||||
eachEntryFn(dir, emitEntry)
|
||||
}
|
||||
// An empty directory gets no marker under its own "<dir>/" prefix:
|
||||
// that listing enumerates children, where S3 returns nothing for an
|
||||
// empty prefix, and a fake entry is read back as a real object by
|
||||
// clients that enumerate locks or similar.
|
||||
// println("doListFilerEntries2 dir", dir+"/"+e.Name, "subNextMarker", subNextMarker)
|
||||
if cursor.isTruncated || matchedPrefixDir {
|
||||
stopped = true
|
||||
|
||||
@@ -65,12 +65,11 @@ func TestDirectoryListedAsCommonPrefix(t *testing.T) {
|
||||
assert.Empty(t, seenFiles, "No files should be seen, only the directory")
|
||||
}
|
||||
|
||||
// TestEmptyDirectorySurfacedAsMarker reproduces the hadoop-aws / Spark case where a
|
||||
// real but empty directory (created via mount, mkdir or the filer API, so it has no
|
||||
// MIME) must be visible to S3 clients that detect directories by listing under the
|
||||
// "<dir>/" prefix. Under a delimiter it is reported as a CommonPrefix, which the
|
||||
// probe accepts, instead of a key a client might try to read.
|
||||
func TestEmptyDirectorySurfacedAsMarker(t *testing.T) {
|
||||
// TestEmptyDirectoryNotListedUnderOwnPrefix covers the explicit "<dir>/" probe
|
||||
// on a real but empty directory (created via mount, mkdir or the filer API, so
|
||||
// it has no MIME): it is listed under its own prefix in neither delimited nor
|
||||
// recursive mode, matching S3 where an empty prefix has no key to return.
|
||||
func TestEmptyDirectoryNotListedUnderOwnPrefix(t *testing.T) {
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{BucketsPath: "/buckets"},
|
||||
}
|
||||
@@ -87,20 +86,15 @@ func TestEmptyDirectorySurfacedAsMarker(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
// Mirrors the getFileStatus probe: prefix "logs/" with delimiter "/".
|
||||
cursor := &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: true}
|
||||
var seen []*filer_pb.Entry
|
||||
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test", prefix: "logs", delimiter: "/", bucket: "test"}, cursor,
|
||||
func(dir string, entry *filer_pb.Entry) {
|
||||
seen = append(seen, entry)
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, seen, 1, "empty directory must be surfaced under the logs/ prefix") {
|
||||
assert.True(t, cursor.emitDirAsCommonPrefix,
|
||||
"a delimited probe reports the empty directory as a common prefix")
|
||||
assert.Empty(t, seen[0].Attributes.Mime,
|
||||
"the entry must not be dressed as a directory key object")
|
||||
for _, delimiter := range []string{"/", ""} {
|
||||
cursor := &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: true}
|
||||
var seen []*filer_pb.Entry
|
||||
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test", prefix: "logs", delimiter: delimiter, bucket: "test"}, cursor,
|
||||
func(dir string, entry *filer_pb.Entry) {
|
||||
seen = append(seen, entry)
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, seen, "an empty directory reports nothing under its own prefix (delimiter %q)", delimiter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,10 +179,10 @@ func TestEmptyDirectoryHiddenInFlatListing(t *testing.T) {
|
||||
assert.Equal(t, []string{"foo"}, seen, "flat listing must hide the empty directory and return only real objects")
|
||||
}
|
||||
|
||||
// A trailing-slash delimited listing of an empty directory reports the
|
||||
// directory as a CommonPrefix, not as a Contents key: clients that treat
|
||||
// every returned key as an object (e.g. lock listings) skip prefixes.
|
||||
func TestEmptyDirectoryListedAsCommonPrefix(t *testing.T) {
|
||||
// A trailing-slash delimited listing of an empty directory enumerates its
|
||||
// children, so it returns nothing: the directory is neither a readable Contents
|
||||
// key nor a CommonPrefix of its own.
|
||||
func TestEmptyDirectoryHiddenInDelimitedSelfListing(t *testing.T) {
|
||||
filer := &fakeBucketDeleteFiler{entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/test": {
|
||||
{Name: "locks", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
@@ -208,6 +202,5 @@ func TestEmptyDirectoryListedAsCommonPrefix(t *testing.T) {
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, response.Contents, "an empty directory is not a readable key")
|
||||
require.Len(t, response.CommonPrefixes, 1)
|
||||
assert.Equal(t, "locks/", response.CommonPrefixes[0].Prefix)
|
||||
assert.Empty(t, response.CommonPrefixes, "an empty directory has no prefixes to fold into")
|
||||
}
|
||||
@@ -82,7 +82,7 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
|
||||
// Verify policy signature.
|
||||
identity, errCode := s3a.iam.doesPolicySignatureMatch(formValues)
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
s3err.WriteErrorResponse(w, r, refineDenialForBucketName(r, identity, errCode))
|
||||
return
|
||||
}
|
||||
if identity != nil {
|
||||
@@ -140,7 +140,7 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
|
||||
|
||||
// Authorize the object like the PUT path; the coarse Write check above does not consult the bucket policy.
|
||||
if errCode := s3a.iam.AuthorizeObjectWrite(r, identity, bucket, object); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
s3err.WriteErrorResponse(w, r, refineDenialForBucketName(r, identity, errCode))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -362,10 +362,24 @@ func getRedirectPostRawQuery(bucket, key, etag string) string {
|
||||
}
|
||||
|
||||
// Check to see if Policy is signed correctly, returning the signing identity.
|
||||
// The identity's Write permission on the bucket is checked only once the
|
||||
// signature verifies, as on the header-signed path, so a form that fails
|
||||
// verification learns nothing about the key's permissions. A verified identity
|
||||
// that may not write is returned with ErrAccessDenied.
|
||||
func (iam *IdentityAccessManagement) doesPolicySignatureMatch(formValues http.Header) (*Identity, s3err.ErrorCode) {
|
||||
var identity *Identity
|
||||
var errCode s3err.ErrorCode
|
||||
// For SignV2 - Signature field will be valid
|
||||
if _, ok := formValues["Signature"]; ok {
|
||||
return iam.doesPolicySignatureV2Match(formValues)
|
||||
identity, errCode = iam.doesPolicySignatureV2Match(formValues)
|
||||
} else {
|
||||
identity, errCode = iam.doesPolicySignatureV4Match(formValues)
|
||||
}
|
||||
return iam.doesPolicySignatureV4Match(formValues)
|
||||
if errCode != s3err.ErrNone {
|
||||
return nil, errCode
|
||||
}
|
||||
if !identity.CanDo(s3_constants.ACTION_WRITE, formValues.Get("bucket"), "") {
|
||||
return identity, s3err.ErrAccessDenied
|
||||
}
|
||||
return identity, s3err.ErrNone
|
||||
}
|
||||
@@ -112,7 +112,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrKeyTooLongError)
|
||||
return
|
||||
}
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object); err != nil {
|
||||
if isVerify, err := s3a.validateTableBucketObjectPathOrVerify(bucket, object); err != nil || (isVerify && !volumeVerifyPutAllowed(r, object)) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
@@ -991,7 +991,11 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
|
||||
}
|
||||
glog.V(3).Infof("putToFiler: Calling CreateEntry for %s", filePath)
|
||||
err := filer_pb.CreateEntry(context.Background(), client, req)
|
||||
if errors.Is(err, filer_pb.ErrExistingIsDirectory) && !isReservedDirectoryName(entry.Name) {
|
||||
// A verification key in a table bucket never becomes a prefix
|
||||
// object: the directory it meets is a namespace, created after the
|
||||
// handler looked.
|
||||
if errors.Is(err, filer_pb.ErrExistingIsDirectory) && !isReservedDirectoryName(entry.Name) &&
|
||||
!(isVolumeVerifyKey(object) && s3a.isTableBucket(bucket)) {
|
||||
// Other keys are nested under this one. S3 keys are flat, so the key is
|
||||
// stored on the directory they live under rather than refused.
|
||||
entry.MarkPrefixObject()
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -661,7 +661,10 @@ func (s3a *S3ApiServer) checkPolicyWithEntry(r *http.Request, bucket, object, ac
|
||||
// Returns s3err.ErrNone if allowed, or an error code if denied or on error.
|
||||
func (s3a *S3ApiServer) recheckPolicyWithObjectEntry(r *http.Request, bucket, object, action string, objectEntry map[string][]byte, handlerName string) s3err.ErrorCode {
|
||||
if isAnonymousObjectRead(r) {
|
||||
return s3a.authorizeAnonymousObjectRead(r, bucket, object, objectEntry)
|
||||
// Refined like writeAnonymousAwareNotFound's masked miss, so a denied
|
||||
// existing key and a missing key answer alike on a malformed name.
|
||||
identity, _ := GetIdentityFromContext(r).(*Identity)
|
||||
return refineDenialForBucketName(r, identity, s3a.authorizeAnonymousObjectRead(r, bucket, object, objectEntry))
|
||||
}
|
||||
identityRaw := GetIdentityFromContext(r)
|
||||
var identity *Identity
|
||||
@@ -678,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
|
||||
|
||||
@@ -127,6 +127,10 @@ func (h *S3TablesHandler) HandleRequest(w http.ResponseWriter, r *http.Request,
|
||||
|
||||
glog.V(3).Infof("S3Tables: handling operation %s", operation)
|
||||
|
||||
// the status the handler answers decides how its error is logged (logRequestError)
|
||||
sw := &statusRecorder{ResponseWriter: w}
|
||||
w = sw
|
||||
|
||||
var err error
|
||||
switch operation {
|
||||
// Table Bucket operations
|
||||
@@ -223,10 +227,51 @@ func (h *S3TablesHandler) HandleRequest(w http.ResponseWriter, r *http.Request,
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
glog.Errorf("S3Tables: error handling %s: %v", operation, err)
|
||||
logRequestError(operation, sw.status, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A refusal the handler answered with a 4xx (access denied, not authorized,
|
||||
// not found, already exists, not empty) is the API working as intended, not a
|
||||
// server fault; it is logged at V(1). A 5xx, or an error returned without any
|
||||
// status written, stays at ERROR.
|
||||
var (
|
||||
logClientRefusal = func(format string, args ...interface{}) { glog.V(1).Infof(format, args...) }
|
||||
logServerError = glog.Errorf
|
||||
)
|
||||
|
||||
func logRequestError(operation string, status int, err error) {
|
||||
if status >= 400 && status < 500 {
|
||||
logClientRefusal("S3Tables: %s refused (%d): %v", operation, status, err)
|
||||
return
|
||||
}
|
||||
logServerError("S3Tables: error handling %s: %v", operation, err)
|
||||
}
|
||||
|
||||
// statusRecorder remembers the first status written through it.
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (s *statusRecorder) WriteHeader(code int) {
|
||||
if s.status == 0 {
|
||||
s.status = code
|
||||
}
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (s *statusRecorder) Write(b []byte) (int, error) {
|
||||
if s.status == 0 {
|
||||
s.status = http.StatusOK
|
||||
}
|
||||
return s.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
// Unwrap lets http.NewResponseController reach the underlying writer, so it
|
||||
// flushes (or reports ErrNotSupported) exactly as that writer does.
|
||||
func (s *statusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
|
||||
|
||||
// Principal/authorization helpers
|
||||
|
||||
// getAccountID returns a stable caller identifier for ownership and permission checks.
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package s3tables
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
)
|
||||
|
||||
// captureLogs swaps the two log sinks for recorders and restores them when the test ends.
|
||||
func captureLogs(t *testing.T) (refusals, serverErrors *[]string) {
|
||||
t.Helper()
|
||||
var r, s []string
|
||||
oldR, oldS := logClientRefusal, logServerError
|
||||
logClientRefusal = func(f string, a ...interface{}) { r = append(r, fmt.Sprintf(f, a...)) }
|
||||
logServerError = func(f string, a ...interface{}) { s = append(s, fmt.Sprintf(f, a...)) }
|
||||
t.Cleanup(func() { logClientRefusal, logServerError = oldR, oldS })
|
||||
return &r, &s
|
||||
}
|
||||
|
||||
// A refusal the API answers with a 4xx is not a server error.
|
||||
func TestRequestRefusedWith4xxIsNotLoggedAsError(t *testing.T) {
|
||||
refusals, serverErrors := captureLogs(t)
|
||||
h := NewS3TablesHandler()
|
||||
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("not json"))
|
||||
req.Header.Set("X-Amz-Target", "S3Tables.ListNamespaces")
|
||||
rec := httptest.NewRecorder()
|
||||
h.HandleRequest(rec, req, nil)
|
||||
if rec.Code < 400 || rec.Code >= 500 {
|
||||
t.Fatalf("the probe request must be refused with a 4xx for this test to mean anything, got %d", rec.Code) // positive control
|
||||
}
|
||||
if len(*serverErrors) != 0 {
|
||||
t.Fatalf("a %d refusal was logged at ERROR: %v", rec.Code, *serverErrors)
|
||||
}
|
||||
if len(*refusals) != 1 || !strings.Contains((*refusals)[0], "ListNamespaces refused") {
|
||||
t.Fatalf("the refusal must still be logged once (at V(1)), got %v", *refusals)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogRequestErrorByStatus(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
status int
|
||||
wantError bool
|
||||
}{{http.StatusForbidden, false}, {http.StatusNotFound, false}, {http.StatusConflict, false},
|
||||
{http.StatusInternalServerError, true}, {http.StatusServiceUnavailable, true}, {0, true}} {
|
||||
refusals, serverErrors := captureLogs(t)
|
||||
logRequestError("Op", c.status, errors.New("boom"))
|
||||
if gotError := len(*serverErrors) == 1 && len(*refusals) == 0; gotError != c.wantError {
|
||||
t.Errorf("status %d: ERROR=%v, want %v (refusals %v, errors %v)", c.status, gotError, c.wantError, *refusals, *serverErrors)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusRecorderKeepsTheFirstStatus(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
sw := &statusRecorder{ResponseWriter: rec}
|
||||
_, _ = sw.Write([]byte("x"))
|
||||
sw.WriteHeader(http.StatusInternalServerError)
|
||||
if sw.status != http.StatusOK {
|
||||
t.Fatalf("an implicit 200 by Write must win, got %d", sw.status)
|
||||
}
|
||||
sw2 := &statusRecorder{ResponseWriter: httptest.NewRecorder()}
|
||||
sw2.WriteHeader(http.StatusForbidden)
|
||||
if sw2.status != http.StatusForbidden {
|
||||
t.Fatalf("got %d", sw2.status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusRecorderUnwrapsForResponseController(t *testing.T) {
|
||||
sw := &statusRecorder{ResponseWriter: httptest.NewRecorder()}
|
||||
if err := http.NewResponseController(sw).Flush(); err != nil {
|
||||
t.Fatalf("ResponseController through the recorder: %v", err)
|
||||
}
|
||||
if sw.Unwrap() == nil {
|
||||
t.Fatal("Unwrap must return the wrapped writer")
|
||||
}
|
||||
}
|
||||
|
||||
// A malformed CreateNamespace body is answered with a 400; neither the
|
||||
// dispatcher nor the handler itself may log it at ERROR.
|
||||
func TestMalformedCreateNamespaceIsNotLoggedAsError(t *testing.T) {
|
||||
refusals, serverErrors := captureLogs(t)
|
||||
|
||||
before := glog.Stats.Error.Lines()
|
||||
glog.Errorf("S3Tables test: positive control for the ERROR line counter")
|
||||
if glog.Stats.Error.Lines() != before+1 {
|
||||
t.Fatal("the ERROR line counter did not see a direct glog.Errorf") // positive control
|
||||
}
|
||||
|
||||
h := NewS3TablesHandler()
|
||||
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("not json"))
|
||||
req.Header.Set("X-Amz-Target", "S3Tables.CreateNamespace")
|
||||
rec := httptest.NewRecorder()
|
||||
before = glog.Stats.Error.Lines()
|
||||
h.HandleRequest(rec, req, nil)
|
||||
errorLines := glog.Stats.Error.Lines() - before
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("a malformed body must be refused with 400, got %d", rec.Code)
|
||||
}
|
||||
if errorLines != 0 || len(*serverErrors) != 0 {
|
||||
t.Fatalf("a 400 refusal was logged at ERROR: %d direct line(s), dispatcher %v", errorLines, *serverErrors)
|
||||
}
|
||||
if len(*refusals) != 1 || !strings.Contains((*refusals)[0], "CreateNamespace refused") {
|
||||
t.Fatalf("the refusal must still be logged once (at V(1)), got %v", *refusals)
|
||||
}
|
||||
}
|
||||
|
||||
// The recorder must not claim to flush a writer that cannot.
|
||||
func TestStatusRecorderFlushFollowsTheWrappedWriter(t *testing.T) {
|
||||
type plainWriter struct{ http.ResponseWriter }
|
||||
sw := &statusRecorder{ResponseWriter: plainWriter{httptest.NewRecorder()}}
|
||||
if err := http.NewResponseController(sw).Flush(); !errors.Is(err, http.ErrNotSupported) {
|
||||
t.Fatalf("Flush through a recorder over a non-flushing writer: %v, want ErrNotSupported", err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
if err := http.NewResponseController(&statusRecorder{ResponseWriter: rec}).Flush(); err != nil || !rec.Flushed {
|
||||
t.Fatalf("Flush through a recorder over a flushing writer: err=%v flushed=%v", err, rec.Flushed) // positive control
|
||||
}
|
||||
}
|
||||
@@ -36,10 +36,9 @@ func (h *S3TablesHandler) mayRepairOwnerlessBucket(r *http.Request) bool {
|
||||
|
||||
// handleCreateNamespace creates a new namespace in a table bucket
|
||||
func (h *S3TablesHandler) handleCreateNamespace(w http.ResponseWriter, r *http.Request, filerClient FilerClient) error {
|
||||
glog.Errorf("S3Tables: handleCreateNamespace called")
|
||||
glog.V(3).Infof("S3Tables: handleCreateNamespace called")
|
||||
var req CreateNamespaceRequest
|
||||
if err := h.readRequestBody(r, &req); err != nil {
|
||||
glog.Errorf("S3Tables: handleCreateNamespace failed to read request body: %v", err)
|
||||
h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package s3tables
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// glog.Errorf with a constant message and no format verb is a trace, not an
|
||||
// error report: every CreateNamespace call logged
|
||||
// "S3Tables: handleCreateNamespace called" at ERROR.
|
||||
func TestNoTraceLoggedAtErrorLevel(t *testing.T) {
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil || len(files) == 0 {
|
||||
t.Fatalf("no sources found (%v)", err) // positive control: the scan must see the package
|
||||
}
|
||||
re := regexp.MustCompile(`glog\.Errorf\("([^"]*)"\)`)
|
||||
scanned := 0
|
||||
for _, f := range files {
|
||||
if strings.HasSuffix(f, "_test.go") {
|
||||
continue
|
||||
}
|
||||
b, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
scanned++
|
||||
for _, m := range re.FindAllStringSubmatch(string(b), -1) {
|
||||
if !strings.Contains(m[1], "%") {
|
||||
t.Errorf("%s: glog.Errorf(%q) logs a constant trace at ERROR; use glog.V(n).Infof", f, m[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
if scanned < 5 {
|
||||
t.Fatalf("scanned only %d source files", scanned)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
const verifyTestBucket = "tables"
|
||||
|
||||
// verifyTestNow is the server clock the tests pin; keys are dated around it.
|
||||
const verifyTestNow = 1790000000000
|
||||
|
||||
func newVerifyTestServer(t *testing.T) *S3ApiServer {
|
||||
t.Helper()
|
||||
saved := volumeVerifyNow
|
||||
volumeVerifyNow = func() time.Time { return time.UnixMilli(verifyTestNow) }
|
||||
savedLookup := volumeVerifyLookup
|
||||
volumeVerifyLookup = func(*S3ApiServer, string, string) (*filer_pb.Entry, error) { return nil, filer_pb.ErrNotFound }
|
||||
t.Cleanup(func() { volumeVerifyNow, volumeVerifyLookup = saved, savedLookup })
|
||||
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
|
||||
s3a.bucketRegistry = NewBucketRegistry(s3a)
|
||||
s3a.bucketRegistry.setMetadataCache(&BucketMetaData{Name: verifyTestBucket, IsTableBucket: true})
|
||||
s3a.bucketRegistry.setMetadataCache(&BucketMetaData{Name: "plain", IsTableBucket: false})
|
||||
return s3a
|
||||
}
|
||||
|
||||
func TestTableBucketAcceptsExternalVolumeVerifyKey(t *testing.T) {
|
||||
s3a := newVerifyTestServer(t)
|
||||
for _, key := range []string{
|
||||
"verify_1790000000000_1081846483",
|
||||
"/verify_1790000000000_1",
|
||||
"verify_1790003300000_42", // 55 minutes later: inside the window
|
||||
"verify_1789996700000_42", // 55 minutes earlier
|
||||
// reads and deletes take a key of any date (PUT limits it)
|
||||
"verify_1789992000000_1",
|
||||
"verify_1790008000000_1",
|
||||
} {
|
||||
isVerify, err := s3a.validateTableBucketObjectPathOrVerify(verifyTestBucket, key)
|
||||
assert.True(t, isVerify, key)
|
||||
assert.NoError(t, err, key)
|
||||
// the handlers that keep the plain rule still refuse it
|
||||
assert.Error(t, s3a.validateTableBucketObjectPath(verifyTestBucket, key), key)
|
||||
}
|
||||
// the Iceberg layout is unchanged: the positive control
|
||||
isVerify, err := s3a.validateTableBucketObjectPathOrVerify(verifyTestBucket, "ns/t/data/part-00000.parquet")
|
||||
assert.False(t, isVerify)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestTableBucketRefusesVerifyKeyLookalikes(t *testing.T) {
|
||||
s3a := newVerifyTestServer(t)
|
||||
for _, key := range []string{
|
||||
// the bucket root only
|
||||
"base/verify_1790000000000_1",
|
||||
"ns/verify_1790000000000_1",
|
||||
".uploads/verify_1790000000000_1",
|
||||
".uploads/abc/verify_1790000000000_1",
|
||||
// the exact shape only
|
||||
"verify_1790000000000_1.txt",
|
||||
"verify_1790000000000",
|
||||
"verify_179000000000_1", // 12-digit timestamp
|
||||
"verify_1790000000000_12345678901", // 11-digit number
|
||||
"verify_abc_123",
|
||||
"verify_1790000000000_1/x",
|
||||
"xverify_1790000000000_1",
|
||||
// ordinary non-Iceberg keys
|
||||
"notes.txt",
|
||||
"ns/t/data/notes.txt",
|
||||
} {
|
||||
isVerify, err := s3a.validateTableBucketObjectPathOrVerify(verifyTestBucket, key)
|
||||
assert.False(t, isVerify, key)
|
||||
assert.Error(t, err, key)
|
||||
}
|
||||
// a bucket that is not a table bucket is unaffected
|
||||
isVerify, err := s3a.validateTableBucketObjectPathOrVerify("plain", "verify_1790000000000_1")
|
||||
assert.False(t, isVerify)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func verifyPutRequest(key string) *http.Request {
|
||||
req := httptest.NewRequest(http.MethodPut, "/"+verifyTestBucket+"/"+key, strings.NewReader("x"))
|
||||
return mux.SetURLVars(req, map[string]string{"bucket": verifyTestBucket, "object": key})
|
||||
}
|
||||
|
||||
// A PUT to the verification key cannot store data: a small declared body and
|
||||
// nothing stored beside it.
|
||||
func TestTableBucketVerifyKeyPutLimits(t *testing.T) {
|
||||
s3a := newVerifyTestServer(t)
|
||||
const key = "verify_1790000000000_1081846483"
|
||||
for name, mutate := range map[string]func(*http.Request){
|
||||
"too large": func(r *http.Request) { r.ContentLength = volumeVerifyMaxBytes + 1 },
|
||||
"content-language": func(r *http.Request) { r.ContentLength = 0; r.Header.Set("Content-Language", "fr") },
|
||||
"content-encoding": func(r *http.Request) { r.ContentLength = 0; r.Header.Set("Content-Encoding", "gzip") },
|
||||
"response-content-disposition": func(r *http.Request) { r.ContentLength = 0; r.Header.Set("Response-Content-Disposition", "attachment") },
|
||||
"extract query": func(r *http.Request) { r.ContentLength = 0; r.URL.RawQuery = "extract=zip" },
|
||||
"extract header": func(r *http.Request) { r.ContentLength = 0; r.Header.Set(s3_constants.SeaweedFSExtract, "zip") },
|
||||
"undeclared length": func(r *http.Request) { r.ContentLength = -1 },
|
||||
"chunked": func(r *http.Request) { r.ContentLength = 0; r.TransferEncoding = []string{"chunked"} },
|
||||
"user metadata": func(r *http.Request) { r.ContentLength = 0; r.Header.Set("X-Amz-Meta-Note", "x") },
|
||||
"tagging": func(r *http.Request) { r.ContentLength = 0; r.Header.Set("X-Amz-Tagging", "a=b") },
|
||||
"content-disposition": func(r *http.Request) { r.ContentLength = 0; r.Header.Set("Content-Disposition", "attachment") },
|
||||
"website redirect": func(r *http.Request) { r.ContentLength = 0; r.Header.Set("X-Amz-Website-Redirect-Location", "/x") },
|
||||
} {
|
||||
req := verifyPutRequest(key)
|
||||
mutate(req)
|
||||
assert.False(t, volumeVerifyPutAllowed(req, key), name)
|
||||
rec := httptest.NewRecorder()
|
||||
s3a.PutObjectHandler(rec, req)
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code, name)
|
||||
}
|
||||
ok := verifyPutRequest(key)
|
||||
ok.ContentLength = 21
|
||||
ok.Header.Set("Content-Type", "application/octet-stream")
|
||||
ok.Header.Set("Content-Encoding", "aws-chunked")
|
||||
assert.True(t, volumeVerifyPutAllowed(ok, key), "the verification object itself")
|
||||
|
||||
// a PUT is dated within the window of the server's clock
|
||||
for _, old := range []string{"verify_1789992000000_1", "verify_1790008000000_1"} {
|
||||
req := verifyPutRequest(old)
|
||||
req.ContentLength = 21
|
||||
assert.False(t, volumeVerifyPutAllowed(req, old), old)
|
||||
rec := httptest.NewRecorder()
|
||||
s3a.PutObjectHandler(rec, req)
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code, old)
|
||||
}
|
||||
}
|
||||
|
||||
// A namespace may carry a name of the key's shape; the key then names its
|
||||
// directory and gets the plain layout rule, as does a key whose entry cannot
|
||||
// be read.
|
||||
func TestTableBucketVerifyKeyNamingDirectoryIsRefused(t *testing.T) {
|
||||
s3a := newVerifyTestServer(t)
|
||||
const key = "verify_1790000000000_7"
|
||||
for name, lookup := range map[string]func(*S3ApiServer, string, string) (*filer_pb.Entry, error){
|
||||
"namespace directory": func(*S3ApiServer, string, string) (*filer_pb.Entry, error) {
|
||||
return &filer_pb.Entry{Name: key, IsDirectory: true}, nil
|
||||
},
|
||||
"lookup failure": func(*S3ApiServer, string, string) (*filer_pb.Entry, error) {
|
||||
return nil, errors.New("filer unavailable")
|
||||
},
|
||||
} {
|
||||
volumeVerifyLookup = lookup
|
||||
isVerify, err := s3a.validateTableBucketObjectPathOrVerify(verifyTestBucket, key)
|
||||
assert.False(t, isVerify, name)
|
||||
assert.Error(t, err, name)
|
||||
}
|
||||
// the control: an existing verification object is a file
|
||||
volumeVerifyLookup = func(*S3ApiServer, string, string) (*filer_pb.Entry, error) {
|
||||
return &filer_pb.Entry{Name: key}, nil
|
||||
}
|
||||
isVerify, err := s3a.validateTableBucketObjectPathOrVerify(verifyTestBucket, key)
|
||||
assert.True(t, isVerify)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
@@ -110,6 +110,8 @@ func (vs *VolumeServer) VolumeTierMoveDatToRemote(req *volume_server_pb.VolumeTi
|
||||
if err := v.LoadRemoteFile(); err != nil {
|
||||
return fmt.Errorf("volume %d failed to load remote file: %v", v.Id, err)
|
||||
}
|
||||
// Deletes must reach the index now, not only after the next restart.
|
||||
v.MarkTieredDeletable()
|
||||
|
||||
if !req.KeepLocalDatFile {
|
||||
os.Remove(v.FileName(".dat"))
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// tierUploadForDeletes writes 10 needles into volume 1 of a new store, marks it
|
||||
// read-only as volume.tier.upload does, and moves its .dat to the tier.
|
||||
func tierUploadForDeletes(t *testing.T, replication string) *storage.Store {
|
||||
t.Helper()
|
||||
backend.BackendStorages[tierTimestampTestBackendName] = &tierTimestampTestBackend{root: t.TempDir()}
|
||||
t.Cleanup(func() { delete(backend.BackendStorages, tierTimestampTestBackendName) })
|
||||
store := storage.NewStore(nil, "localhost", 8080, 18080, "http://localhost:8080", "store-id",
|
||||
[]string{t.TempDir()}, []int32{10}, []util.MinFreeSpace{{}}, "", storage.NeedleMapInMemory,
|
||||
[]types.DiskType{types.HardDriveType}, nil, 0, stats.DefaultDiskIOProbeConfig())
|
||||
t.Cleanup(store.Close)
|
||||
if err := store.AddVolume(1, "", storage.NeedleMapInMemory, replication, "", 0, needle.Version3, 0, types.HardDriveType, 0); err != nil {
|
||||
t.Fatalf("add volume: %v", err)
|
||||
}
|
||||
for i := 1; i <= 10; i++ {
|
||||
n := &needle.Needle{Id: types.Uint64ToNeedleId(uint64(i)), Cookie: 7, Data: bytes.Repeat([]byte{byte(i)}, 1024)}
|
||||
n.Checksum = needle.NewCRC(n.Data)
|
||||
if _, err := store.WriteVolumeNeedle(1, n, false, false); err != nil {
|
||||
t.Fatalf("write %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
if err := store.MarkVolumeReadonly(1, false, false); err != nil {
|
||||
t.Fatalf("mark read-only: %v", err)
|
||||
}
|
||||
vs := &VolumeServer{store: store}
|
||||
if err := vs.VolumeTierMoveDatToRemote(&volume_server_pb.VolumeTierMoveDatToRemoteRequest{
|
||||
VolumeId: 1, DestinationBackendName: tierTimestampTestBackendName,
|
||||
}, &discardServerStream[volume_server_pb.VolumeTierMoveDatToRemoteResponse]{}); err != nil {
|
||||
t.Fatalf("tier upload: %v", err)
|
||||
}
|
||||
return store
|
||||
}
|
||||
|
||||
// A single-copy volume takes deletes as soon as it is tiered, as it would
|
||||
// after a restart. Before, they were refused ("volume 1 is read only") until
|
||||
// then, leaving the needles live in the index.
|
||||
func TestTierUploadAcceptsDeletesOnASingleCopyVolume(t *testing.T) {
|
||||
store := tierUploadForDeletes(t, "000")
|
||||
if _, err := store.DeleteVolumeNeedle(1, &needle.Needle{Id: 2}); err != nil {
|
||||
t.Fatalf("delete on the freshly tiered volume: %v", err)
|
||||
}
|
||||
if _, err := store.ReadVolumeNeedle(1, &needle.Needle{Id: 2}, nil, nil); err == nil {
|
||||
t.Fatalf("the deleted needle still reads")
|
||||
}
|
||||
if _, err := store.ReadVolumeNeedle(1, &needle.Needle{Id: 3}, nil, nil); err != nil {
|
||||
t.Fatalf("a live needle does not read: %v", err)
|
||||
}
|
||||
n := &needle.Needle{Id: 99, Cookie: 7, Data: []byte("x")}
|
||||
n.Checksum = needle.NewCRC(n.Data)
|
||||
if _, err := store.WriteVolumeNeedle(1, n, false, false); err == nil {
|
||||
t.Fatalf("a write to a tiered volume succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
// A replicated volume keeps refusing deletes: the shell copies the uploaded
|
||||
// replica's .idx and .vif to the others after the upload, and a tombstone
|
||||
// written before that copy would reach one replica only.
|
||||
func TestTierUploadKeepsRefusingDeletesOnAReplicatedVolume(t *testing.T) {
|
||||
store := tierUploadForDeletes(t, "001")
|
||||
if _, err := store.DeleteVolumeNeedle(1, &needle.Needle{Id: 2}); err == nil {
|
||||
t.Fatalf("a replicated volume accepted a delete right after the tier upload")
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package s3_backend
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -44,6 +45,7 @@ type S3BackendStorage struct {
|
||||
forcePathStyle bool
|
||||
uploadConcurrency int
|
||||
downloadConcurrency int
|
||||
httpOptions httpOptions
|
||||
conn s3iface.S3API
|
||||
}
|
||||
|
||||
@@ -59,11 +61,16 @@ func newS3BackendStorage(configuration backend.StringProperties, configPrefix st
|
||||
s.forcePathStyle = util.ParseBool(configuration.GetString(configPrefix+"force_path_style"), true)
|
||||
s.uploadConcurrency = parseConcurrency(configuration.GetString(configPrefix+"upload_concurrency"), defaultUploadConcurrency)
|
||||
s.downloadConcurrency = parseConcurrency(configuration.GetString(configPrefix+"download_concurrency"), defaultDownloadConcurrency)
|
||||
s.httpOptions = httpOptions{
|
||||
disableHTTP2: util.ParseBool(configuration.GetString(configPrefix+"disable_http2"), false),
|
||||
maxConnsPerHost: parseNonNegative(configuration.GetString(configPrefix+"max_connections"), "max_connections"),
|
||||
idleConnTimeout: parseIdleConnTimeout(configuration.GetString(configPrefix + "idle_connection_timeout_seconds")),
|
||||
}
|
||||
if s.storageClass == "" {
|
||||
s.storageClass = "STANDARD_IA"
|
||||
}
|
||||
|
||||
s.conn, err = createSession(s.aws_access_key_id, s.aws_secret_access_key, s.region, s.endpoint, s.forcePathStyle)
|
||||
s.conn, err = createSession(s.aws_access_key_id, s.aws_secret_access_key, s.region, s.endpoint, s.forcePathStyle, s.httpOptions)
|
||||
|
||||
glog.V(0).Infof("created backend storage s3.%s for region %s bucket %s", s.id, s.region, s.bucket)
|
||||
return
|
||||
@@ -80,6 +87,9 @@ func (s *S3BackendStorage) ToProperties() map[string]string {
|
||||
m["force_path_style"] = util.BoolToString(s.forcePathStyle)
|
||||
m["upload_concurrency"] = strconv.Itoa(s.uploadConcurrency)
|
||||
m["download_concurrency"] = strconv.Itoa(s.downloadConcurrency)
|
||||
m["disable_http2"] = util.BoolToString(s.httpOptions.disableHTTP2)
|
||||
m["max_connections"] = strconv.Itoa(s.httpOptions.maxConnsPerHost)
|
||||
m["idle_connection_timeout_seconds"] = strconv.FormatInt(int64(s.httpOptions.idleConnTimeout/time.Second), 10)
|
||||
return m
|
||||
}
|
||||
|
||||
@@ -99,6 +109,42 @@ func parseConcurrency(value string, def int) int {
|
||||
return def
|
||||
}
|
||||
|
||||
// parseNonNegative reads an optional non-negative integer setting; empty or
|
||||
// invalid means 0 (the default).
|
||||
func parseNonNegative(value, name string) int {
|
||||
if value == "" {
|
||||
return 0
|
||||
}
|
||||
if n, err := strconv.Atoi(value); err == nil && n >= 0 {
|
||||
return n
|
||||
}
|
||||
glog.Warningf("invalid %s value %q, using the default", name, value)
|
||||
return 0
|
||||
}
|
||||
|
||||
// maxIdleConnTimeoutSeconds is the largest number of seconds a time.Duration
|
||||
// can hold.
|
||||
const maxIdleConnTimeoutSeconds = math.MaxInt64 / int64(time.Second)
|
||||
|
||||
// parseIdleConnTimeout reads idle_connection_timeout_seconds; empty, invalid
|
||||
// or too large to represent as a time.Duration means 0 (the default). It
|
||||
// parses 64-bit seconds so the range is the same on 32-bit platforms.
|
||||
func parseIdleConnTimeout(value string) time.Duration {
|
||||
if value == "" {
|
||||
return 0
|
||||
}
|
||||
seconds, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || seconds < 0 {
|
||||
glog.Warningf("invalid idle_connection_timeout_seconds value %q, using the default", value)
|
||||
return 0
|
||||
}
|
||||
if seconds > maxIdleConnTimeoutSeconds {
|
||||
glog.Warningf("idle_connection_timeout_seconds %q is out of range, using the default", value)
|
||||
return 0
|
||||
}
|
||||
return time.Duration(seconds) * time.Second
|
||||
}
|
||||
|
||||
func (s *S3BackendStorage) NewStorageFile(key string, tierInfo *volume_server_pb.VolumeInfo) backend.BackendStorageFile {
|
||||
if strings.HasPrefix(key, "/") {
|
||||
key = key[1:]
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package s3_backend
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
@@ -18,12 +21,49 @@ var (
|
||||
sessionsLock sync.Mutex
|
||||
)
|
||||
|
||||
func createSession(awsAccessKeyId, awsSecretAccessKey, region, endpoint string, forcePathStyle bool) (s3iface.S3API, error) {
|
||||
// httpOptions tunes the HTTP transport of the tier backend's S3 client. The
|
||||
// zero value keeps the SDK's default client.
|
||||
type httpOptions struct {
|
||||
// disableHTTP2 keeps the client on HTTP/1.1. Over HTTP/2 every upload and
|
||||
// range read to the endpoint shares one connection and its flow-control
|
||||
// window, which some S3-compatible services keep small.
|
||||
disableHTTP2 bool
|
||||
// maxConnsPerHost caps the connections to the endpoint (0 = no cap), for
|
||||
// services that limit parallel connections per client address.
|
||||
maxConnsPerHost int
|
||||
// idleConnTimeout closes idle connections sooner than Go's default 90s,
|
||||
// for services that drop idle connections earlier (0 = default).
|
||||
idleConnTimeout time.Duration
|
||||
}
|
||||
|
||||
// newTransport returns the transport for the options, or nil for the default.
|
||||
func (o httpOptions) newTransport() *http.Transport {
|
||||
if o == (httpOptions{}) {
|
||||
return nil
|
||||
}
|
||||
t := http.DefaultTransport.(*http.Transport).Clone()
|
||||
if o.disableHTTP2 {
|
||||
t.ForceAttemptHTTP2 = false
|
||||
t.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{}
|
||||
}
|
||||
if o.maxConnsPerHost > 0 {
|
||||
t.MaxConnsPerHost = o.maxConnsPerHost
|
||||
}
|
||||
if o.idleConnTimeout > 0 {
|
||||
t.IdleConnTimeout = o.idleConnTimeout
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func createSession(awsAccessKeyId, awsSecretAccessKey, region, endpoint string, forcePathStyle bool, httpOpts httpOptions) (s3iface.S3API, error) {
|
||||
|
||||
sessionsLock.Lock()
|
||||
defer sessionsLock.Unlock()
|
||||
|
||||
cacheKey := fmt.Sprintf("%s|%s", region, endpoint)
|
||||
if httpOpts != (httpOptions{}) {
|
||||
cacheKey = fmt.Sprintf("%s|%+v", cacheKey, httpOpts)
|
||||
}
|
||||
if t, found := s3Sessions[cacheKey]; found {
|
||||
return t, nil
|
||||
}
|
||||
@@ -34,6 +74,9 @@ func createSession(awsAccessKeyId, awsSecretAccessKey, region, endpoint string,
|
||||
S3ForcePathStyle: aws.Bool(forcePathStyle),
|
||||
S3DisableContentMD5Validation: aws.Bool(true),
|
||||
}
|
||||
if t := httpOpts.newTransport(); t != nil {
|
||||
config.HTTPClient = &http.Client{Transport: t}
|
||||
}
|
||||
if awsAccessKeyId != "" && awsSecretAccessKey != "" {
|
||||
config.Credentials = credentials.NewStaticCredentials(awsAccessKeyId, awsSecretAccessKey, "")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
package s3_backend
|
||||
|
||||
import (
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
)
|
||||
|
||||
func backendTransport(t *testing.T, s *S3BackendStorage) *http.Transport {
|
||||
t.Helper()
|
||||
client, ok := s.conn.(*s3.S3)
|
||||
if !ok {
|
||||
t.Fatalf("unexpected client type %T", s.conn)
|
||||
}
|
||||
httpClient := client.Client.Config.HTTPClient
|
||||
if httpClient == nil {
|
||||
return nil
|
||||
}
|
||||
transport, _ := httpClient.Transport.(*http.Transport)
|
||||
return transport
|
||||
}
|
||||
|
||||
func TestS3BackendHTTPOptionsReachTheClient(t *testing.T) {
|
||||
s, err := newS3BackendStorage(testProperties{
|
||||
"endpoint": "http://127.0.0.1:1",
|
||||
"disable_http2": "true",
|
||||
"max_connections": "64",
|
||||
"idle_connection_timeout_seconds": "50",
|
||||
}, "", "http-options")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
transport := backendTransport(t, s)
|
||||
if transport == nil {
|
||||
t.Fatal("configured HTTP options did not reach the S3 client")
|
||||
}
|
||||
if transport.ForceAttemptHTTP2 || transport.TLSNextProto == nil || len(transport.TLSNextProto) != 0 {
|
||||
t.Errorf("HTTP/2 not disabled: ForceAttemptHTTP2=%v TLSNextProto=%v", transport.ForceAttemptHTTP2, transport.TLSNextProto)
|
||||
}
|
||||
if transport.MaxConnsPerHost != 64 {
|
||||
t.Errorf("MaxConnsPerHost = %d, want 64", transport.MaxConnsPerHost)
|
||||
}
|
||||
if transport.IdleConnTimeout != 50*time.Second {
|
||||
t.Errorf("IdleConnTimeout = %v, want 50s", transport.IdleConnTimeout)
|
||||
}
|
||||
|
||||
props := s.ToProperties()
|
||||
if props["disable_http2"] != "true" || props["max_connections"] != "64" || props["idle_connection_timeout_seconds"] != "50" {
|
||||
t.Errorf("ToProperties: %v", props)
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3BackendDefaultHTTPClientUnchanged(t *testing.T) {
|
||||
s, err := newS3BackendStorage(testProperties{"endpoint": "http://127.0.0.1:2"}, "", "http-defaults")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if transport := backendTransport(t, s); transport != nil && transport != http.DefaultTransport {
|
||||
t.Fatalf("no options set, yet the client got a custom transport %+v", transport)
|
||||
}
|
||||
if (httpOptions{}).newTransport() != nil {
|
||||
t.Fatal("zero options must keep the default client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3BackendSessionsDifferByHTTPOptions(t *testing.T) {
|
||||
a, err := createSession("", "", "us-east-1", "http://127.0.0.1:3", true, httpOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := createSession("", "", "us-east-1", "http://127.0.0.1:3", true, httpOptions{disableHTTP2: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a == b {
|
||||
t.Fatal("backends with different HTTP options share one client")
|
||||
}
|
||||
c, err := createSession("", "", "us-east-1", "http://127.0.0.1:3", true, httpOptions{disableHTTP2: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b != c {
|
||||
t.Fatal("the same endpoint and options must reuse the cached client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseNonNegative(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
in string
|
||||
want int
|
||||
}{{"", 0}, {"0", 0}, {"12", 12}, {"-1", 0}, {"x", 0}} {
|
||||
if got := parseNonNegative(c.in, "test"); got != c.want {
|
||||
t.Errorf("parseNonNegative(%q) = %d, want %d", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3BackendIdleTimeoutOverflowFallsBackToDefault(t *testing.T) {
|
||||
maxSeconds := int64(math.MaxInt64 / int64(time.Second))
|
||||
for i, c := range []struct {
|
||||
in string
|
||||
want time.Duration
|
||||
}{
|
||||
{strconv.FormatInt(maxSeconds, 10), time.Duration(maxSeconds) * time.Second},
|
||||
{strconv.FormatInt(maxSeconds+1, 10), 0},
|
||||
{"10000000000", 0},
|
||||
{"-1", 0},
|
||||
{"x", 0},
|
||||
} {
|
||||
s, err := newS3BackendStorage(testProperties{
|
||||
"endpoint": "http://127.0.0.1:4",
|
||||
"idle_connection_timeout_seconds": c.in,
|
||||
}, "", "idle-overflow-"+strconv.Itoa(i))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.httpOptions.idleConnTimeout != c.want {
|
||||
t.Errorf("idle_connection_timeout_seconds=%s: timeout %v, want %v", c.in, s.httpOptions.idleConnTimeout, c.want)
|
||||
}
|
||||
want := strconv.FormatInt(int64(c.want/time.Second), 10)
|
||||
if got := s.ToProperties()["idle_connection_timeout_seconds"]; got != want {
|
||||
t.Errorf("idle_connection_timeout_seconds=%s: ToProperties exports %s, want %s", c.in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
+10
-11
@@ -880,7 +880,10 @@ func (s *Store) WriteVolumeNeedle(i needle.VolumeId, n *needle.Needle, checkCook
|
||||
|
||||
func (s *Store) DeleteVolumeNeedle(i needle.VolumeId, n *needle.Needle) (Size, error) {
|
||||
if v := s.findVolume(i); v != nil {
|
||||
if v.noWriteOrDelete {
|
||||
v.noWriteLock.RLock()
|
||||
noWriteOrDelete := v.noWriteOrDelete
|
||||
v.noWriteLock.RUnlock()
|
||||
if noWriteOrDelete {
|
||||
return 0, fmt.Errorf("volume %d is read only", i)
|
||||
}
|
||||
return v.deleteNeedle2(n)
|
||||
@@ -986,10 +989,10 @@ func (s *Store) MarkVolumeWritable(i needle.VolumeId) error {
|
||||
prevNoWriteOrDelete := v.noWriteOrDelete
|
||||
prevNoWriteCanDelete := v.noWriteCanDelete
|
||||
v.noWriteOrDelete = false
|
||||
// Remote-tiered volumes must stay noWriteCanDelete regardless of marks.
|
||||
if !v.HasRemoteFile() {
|
||||
v.noWriteCanDelete = false
|
||||
}
|
||||
// A remote-tiered volume keeps the delete-only mode load() derives: its
|
||||
// .dat cannot take appends, so "writable" resolves to can-delete rather
|
||||
// than advertising writable with no local data file.
|
||||
v.noWriteCanDelete = v.HasRemoteFile()
|
||||
persistErr := v.PersistReadOnly(false, false)
|
||||
if persistErr != nil {
|
||||
var ndErr *volume_info.NotCrashDurableError
|
||||
@@ -1338,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
|
||||
}
|
||||
@@ -238,7 +238,7 @@ func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind
|
||||
glog.V(2).Infof("readSuperBlock volume %d version %v", v.Id, v.SuperBlock.Version)
|
||||
if v.HasRemoteFile() {
|
||||
// maybe temporary network problem
|
||||
glog.Errorf("readSuperBlock remote volume %d: %v", v.Id, err)
|
||||
logRemoteSuperBlockErr(v.Id, err)
|
||||
err = nil
|
||||
}
|
||||
} else {
|
||||
@@ -434,3 +434,11 @@ func datFileLoadError(fileName string, err error) error {
|
||||
}
|
||||
return fmt.Errorf("cannot load volume data %s: %v", fileName, err)
|
||||
}
|
||||
|
||||
var logRemoteSuperBlockFault = glog.Errorf
|
||||
|
||||
func logRemoteSuperBlockErr(id needle.VolumeId, err error) {
|
||||
if err != nil {
|
||||
logRemoteSuperBlockFault("readSuperBlock remote volume %d: %v", id, err)
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,33 @@ func TestMarkVolumeWritable_ReopensPersistedReadOnly(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A remote-tiered volume marked writable keeps the delete-only mode load()
|
||||
// derives — the remote .dat cannot take appends, so "writable" resolves to
|
||||
// can-delete even when the mark left noWriteOrDelete without noWriteCanDelete.
|
||||
func TestMarkVolumeWritableOnATieredVolumeKeepsDeletesOnly(t *testing.T) {
|
||||
b := newLocalDirBackend(t)
|
||||
registerTestBackend(t, b)
|
||||
|
||||
v, _ := tierUpVolumeLive(t, t.TempDir(), 86, b)
|
||||
defer v.Close()
|
||||
// the upload-time mark as a refused MarkTieredDeletable leaves it
|
||||
v.noWriteOrDelete = true
|
||||
v.noWriteCanDelete = false
|
||||
|
||||
location := newTestLocation(10, false, 0)
|
||||
location.SetVolume(86, v)
|
||||
s := &Store{Locations: []*DiskLocation{location}}
|
||||
if err := s.MarkVolumeWritable(86); err != nil {
|
||||
t.Fatalf("mark writable: %v", err)
|
||||
}
|
||||
|
||||
readOnly, orDelete, canDelete, _ := v.ReadOnlyReasons()
|
||||
if orDelete || !canDelete || !readOnly {
|
||||
t.Fatalf("a tiered volume resolves writable to delete-only, got readOnly=%v orDelete=%v canDelete=%v",
|
||||
readOnly, orDelete, canDelete)
|
||||
}
|
||||
}
|
||||
|
||||
// reopenIdxForWrite must be a no-op when the volume already has a writable
|
||||
// needle map — otherwise repeated MarkVolumeWritable calls would churn the
|
||||
// index file handle for no reason.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRemoteSuperBlockLogOnlyOnError(t *testing.T) {
|
||||
var logged int
|
||||
old := logRemoteSuperBlockFault
|
||||
logRemoteSuperBlockFault = func(string, ...interface{}) { logged++ }
|
||||
defer func() { logRemoteSuperBlockFault = old }()
|
||||
logRemoteSuperBlockErr(219, nil)
|
||||
if logged != 0 {
|
||||
t.Fatalf("a nil error was logged at ERROR (the \"readSuperBlock remote volume 219: <nil>\" line)")
|
||||
}
|
||||
logRemoteSuperBlockErr(219, errors.New("timeout")) // positive control
|
||||
if logged != 1 {
|
||||
t.Fatalf("a real error must still be logged, got %d", logged)
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,41 @@ func (v *Volume) LoadRemoteFile() error {
|
||||
return v.loadRemoteFileLocked()
|
||||
}
|
||||
|
||||
// MarkTieredDeletable gives a volume whose data has just moved to the remote
|
||||
// tier the flags a restart gives it (load(): a tiered volume refuses writes and
|
||||
// accepts deletes). volume.tier.upload marks the volume read-only without
|
||||
// deletes before the upload; left that way, every delete until the next
|
||||
// restart is refused, the filer drops it, and the needle's bytes stay in the
|
||||
// remote object where no vacuum can find them.
|
||||
//
|
||||
// Only for a single-copy volume: the shell copies the uploaded replica's .idx
|
||||
// and .vif to the other replicas after the upload, and a tombstone written
|
||||
// before that copy would reach one replica only; a replicated volume keeps
|
||||
// refusing deletes until its next load, as before. An I/O quarantine is left
|
||||
// alone, and so is a volume past the I/O error tolerance that the next
|
||||
// heartbeat will quarantine. Otherwise the flags are the ones load() gives
|
||||
// every tiered volume.
|
||||
func (v *Volume) MarkTieredDeletable() bool {
|
||||
if rp := v.SuperBlock.ReplicaPlacement; rp != nil && rp.GetCopyCount() > 1 {
|
||||
return false
|
||||
}
|
||||
// Check the I/O state under noWriteLock: CollectHeartbeat marks the
|
||||
// quarantine before it takes noWriteLock to refuse deletes, so either the
|
||||
// check below sees the quarantine, or the heartbeat's refusal lands after
|
||||
// this change and stays.
|
||||
v.noWriteLock.Lock()
|
||||
defer v.noWriteLock.Unlock()
|
||||
if !v.HasRemoteFile() {
|
||||
return false
|
||||
}
|
||||
if ioErr, ioCount, quarantined := v.getIoErrorState(); quarantined || (ioErr != nil && ioCount >= IoErrorTolerance) {
|
||||
return false
|
||||
}
|
||||
v.noWriteOrDelete = false
|
||||
v.noWriteCanDelete = true
|
||||
return true
|
||||
}
|
||||
|
||||
// loadRemoteFileLocked swaps the data backend to the remote tier object. The
|
||||
// caller must hold dataFileAccessLock or be single-threaded (load() during
|
||||
// construction or a compaction-commit reload). It marks the volume tiered in the
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// MarkTieredDeletable gives a freshly tiered single-copy volume the flags a
|
||||
// restart gives it, and leaves an I/O quarantine alone.
|
||||
func TestMarkTieredDeletable(t *testing.T) {
|
||||
b := newLocalDirBackend(t)
|
||||
registerTestBackend(t, b)
|
||||
|
||||
v, _ := tierUpVolumeLive(t, t.TempDir(), 81, b)
|
||||
defer v.Close()
|
||||
v.noWriteOrDelete = true // as volume.tier.upload's mark leaves it
|
||||
require.True(t, v.MarkTieredDeletable())
|
||||
require.False(t, v.noWriteOrDelete)
|
||||
require.True(t, v.noWriteCanDelete)
|
||||
|
||||
w, _ := tierUpVolumeLive(t, t.TempDir(), 82, b)
|
||||
defer w.Close()
|
||||
w.noWriteOrDelete = true
|
||||
w.markIoQuarantined()
|
||||
require.False(t, w.MarkTieredDeletable())
|
||||
require.True(t, w.noWriteOrDelete, "an I/O quarantine is not the tier upload's to lift")
|
||||
}
|
||||
|
||||
// MarkTieredDeletable is only for a tiered volume: a stray call on a local
|
||||
// volume must not pin it read-only-can-delete.
|
||||
func TestMarkTieredDeletableLeavesANonTieredVolume(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
v, err := NewVolume(dir, dir, "", 86, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
|
||||
require.NoError(t, err)
|
||||
defer v.Close()
|
||||
|
||||
require.False(t, v.MarkTieredDeletable())
|
||||
require.False(t, v.noWriteOrDelete)
|
||||
require.False(t, v.noWriteCanDelete)
|
||||
}
|
||||
|
||||
// A heartbeat that quarantines the volume while MarkTieredDeletable waits for
|
||||
// noWriteLock must keep its refusal: the quarantine check and the flag change
|
||||
// happen under the same lock.
|
||||
func TestMarkTieredDeletableKeepsAConcurrentQuarantine(t *testing.T) {
|
||||
b := newLocalDirBackend(t)
|
||||
registerTestBackend(t, b)
|
||||
|
||||
v, _ := tierUpVolumeLive(t, t.TempDir(), 83, b)
|
||||
defer v.Close()
|
||||
v.noWriteOrDelete = true
|
||||
|
||||
v.noWriteLock.Lock()
|
||||
done := make(chan bool)
|
||||
go func() { done <- v.MarkTieredDeletable() }()
|
||||
time.Sleep(100 * time.Millisecond) // let it reach noWriteLock
|
||||
// What CollectHeartbeat does: mark the quarantine, then refuse writes and deletes.
|
||||
v.markIoQuarantined()
|
||||
v.noWriteOrDelete = true
|
||||
v.noWriteLock.Unlock()
|
||||
|
||||
require.False(t, <-done, "a volume quarantined before the flags changed must not be made deletable")
|
||||
v.noWriteLock.RLock()
|
||||
defer v.noWriteLock.RUnlock()
|
||||
require.True(t, v.noWriteOrDelete, "the heartbeat's refusal was overwritten")
|
||||
}
|
||||
|
||||
// A volume past the I/O error tolerance is about to be quarantined by the next
|
||||
// heartbeat; it is not made deletable in the meantime.
|
||||
func TestMarkTieredDeletableRefusesAVolumePastIoErrorTolerance(t *testing.T) {
|
||||
b := newLocalDirBackend(t)
|
||||
registerTestBackend(t, b)
|
||||
|
||||
v, _ := tierUpVolumeLive(t, t.TempDir(), 84, b)
|
||||
defer v.Close()
|
||||
v.noWriteOrDelete = true
|
||||
for i := 0; i < IoErrorTolerance; i++ {
|
||||
v.noteIoError(syscall.EIO)
|
||||
}
|
||||
require.False(t, v.MarkTieredDeletable())
|
||||
require.True(t, v.noWriteOrDelete)
|
||||
|
||||
v.clearIoError() // positive control: below the tolerance it is made deletable
|
||||
require.True(t, v.MarkTieredDeletable())
|
||||
require.False(t, v.noWriteOrDelete)
|
||||
}
|
||||
|
||||
// DeleteVolumeNeedle reads the read-only flags under noWriteLock, so a delete
|
||||
// that races the tier upload's flag change is not a data race (run with -race).
|
||||
func TestDeleteVolumeNeedleRacesMarkTieredDeletable(t *testing.T) {
|
||||
b := newLocalDirBackend(t)
|
||||
registerTestBackend(t, b)
|
||||
|
||||
v, _ := tierUpVolumeLive(t, t.TempDir(), 85, b)
|
||||
defer v.Close()
|
||||
v.noWriteOrDelete = true
|
||||
location := newTestLocation(10, false, 0)
|
||||
location.SetVolume(85, v)
|
||||
s := &Store{Locations: []*DiskLocation{location}}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for i := 0; i < 100; i++ {
|
||||
v.MarkTieredDeletable()
|
||||
}
|
||||
}()
|
||||
for i := 0; i < 100; i++ {
|
||||
_, _ = s.DeleteVolumeNeedle(85, &needle.Needle{Id: types.Uint64ToNeedleId(1000)})
|
||||
}
|
||||
<-done
|
||||
|
||||
// Positive control: once deletable, a delete of a live needle goes through.
|
||||
size, err := s.DeleteVolumeNeedle(85, &needle.Needle{Id: types.Uint64ToNeedleId(1)})
|
||||
require.NoError(t, err)
|
||||
require.NotZero(t, size)
|
||||
}
|
||||
@@ -300,6 +300,14 @@ func (h *Handler) compactDataFiles(
|
||||
glog.Warningf("iceberg compact: failed to merge bin %d (%d files): %v", binIdx, len(bin.Entries), err)
|
||||
goto binDone
|
||||
}
|
||||
// A default-CRS geometry column declares no CRS (geometry_crs.go). A
|
||||
// footer that cannot be rewritten leaves the file as written: valid,
|
||||
// only labelled differently.
|
||||
if fixed, _, crsErr := withDefaultGeometryCRSUnset(mergedData, schema); crsErr != nil {
|
||||
glog.Warningf("iceberg compact: geometry CRS left as written in bin %d: %v", binIdx, crsErr)
|
||||
} else {
|
||||
mergedData = fixed
|
||||
}
|
||||
|
||||
// Write merged file to filer
|
||||
if err := ensureFilerDir(ctx, filerClient, dataDir); err != nil {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/apache/iceberg-go"
|
||||
"github.com/parquet-go/parquet-go/deprecated"
|
||||
"github.com/parquet-go/parquet-go/encoding/thrift"
|
||||
"github.com/parquet-go/parquet-go/format"
|
||||
)
|
||||
|
||||
// A GEOMETRY column whose Iceberg type has the default CRS (OGC:CRS84) is
|
||||
// written with no CRS in the Parquet logical type, as the input files from
|
||||
// most writers declare it. parquet-go spells the default out when it writes
|
||||
// such a column, even when the column it read declared none. Both mean the
|
||||
// same, but a reader may then see the file column as a different type from
|
||||
// the table column (DuckDB casts it and no longer prunes row groups by their
|
||||
// statistics). An explicit CRS is left as it is.
|
||||
//
|
||||
// The footer is changed after the file is written rather than by giving the
|
||||
// writer another column type: parquet-go refuses to convert between two
|
||||
// GEOMETRY types that both mean the default, and its sorting writer
|
||||
// converts. Only the footer's schema elements change; the data, the page
|
||||
// indexes and every offset into the file stay byte for byte.
|
||||
|
||||
var parquetMagic = []byte("PAR1")
|
||||
|
||||
// withDefaultGeometryCRSUnset returns data with the CRS of every GEOMETRY
|
||||
// column whose Iceberg type has the default CRS left unset in the footer, and
|
||||
// whether anything changed. A file that needs no change comes back as it was;
|
||||
// so does one whose footer cannot be read (encrypted, not Parquet), with an
|
||||
// error. A changed file is written into data's buffer when it fits, so the
|
||||
// caller uses the result in place of data.
|
||||
func withDefaultGeometryCRSUnset(data []byte, schema *iceberg.Schema) ([]byte, bool, error) {
|
||||
if schema == nil || !hasDefaultCRSGeometry(schema) {
|
||||
return data, false, nil
|
||||
}
|
||||
n := len(data)
|
||||
if n < 12 || !bytes.Equal(data[n-4:], parquetMagic) || !bytes.Equal(data[:4], parquetMagic) {
|
||||
return data, false, fmt.Errorf("not a plaintext parquet file")
|
||||
}
|
||||
footerLen := int(binary.LittleEndian.Uint32(data[n-8 : n-4]))
|
||||
footerStart := n - 8 - footerLen
|
||||
if footerLen <= 0 || footerStart < 4 {
|
||||
return data, false, fmt.Errorf("footer length %d out of range", footerLen)
|
||||
}
|
||||
var protocol thrift.CompactProtocol
|
||||
var md format.FileMetaData
|
||||
if err := thrift.Unmarshal(&protocol, data[footerStart:n-8], &md); err != nil {
|
||||
return data, false, fmt.Errorf("decode footer: %w", err)
|
||||
}
|
||||
changed := false
|
||||
for i, path := range schemaElementPaths(md.Schema) {
|
||||
el := &md.Schema[i]
|
||||
g, ok := el.LogicalType.Value.(*format.GeometryType)
|
||||
if !ok || g.CRS != iceberg.DefaultGeoCRS {
|
||||
continue
|
||||
}
|
||||
var field iceberg.NestedField
|
||||
if el.FieldID > 0 {
|
||||
field, ok = schema.FindFieldByID(int(el.FieldID))
|
||||
} else {
|
||||
field, ok = schema.FindFieldByName(strings.Join(path, "."))
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if gt, isGeo := field.Type.(iceberg.GeometryType); !isGeo || gt.CRS() != iceberg.DefaultGeoCRS {
|
||||
continue
|
||||
}
|
||||
el.LogicalType = format.LogicalType{Value: &format.GeometryType{}}
|
||||
changed = true
|
||||
}
|
||||
if !changed {
|
||||
return data, false, nil
|
||||
}
|
||||
footer, err := thrift.Marshal(&protocol, &md)
|
||||
if err != nil {
|
||||
return data, false, fmt.Errorf("encode footer: %w", err)
|
||||
}
|
||||
// The new footer is written over the old one in data's own buffer when it
|
||||
// fits, as it does when a CRS is removed: the file is as large as a
|
||||
// compaction target, and copying it would double the memory it takes.
|
||||
out := data[:footerStart]
|
||||
if cap(data) < footerStart+len(footer)+8 {
|
||||
out = make([]byte, footerStart, footerStart+len(footer)+8)
|
||||
copy(out, data[:footerStart])
|
||||
}
|
||||
out = append(out, footer...)
|
||||
out = binary.LittleEndian.AppendUint32(out, uint32(len(footer)))
|
||||
out = append(out, parquetMagic...)
|
||||
return out, true, nil
|
||||
}
|
||||
|
||||
func hasDefaultCRSGeometry(schema *iceberg.Schema) bool {
|
||||
for _, f := range schema.Fields() {
|
||||
if typeHasDefaultCRSGeometry(f.Type) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// typeHasDefaultCRSGeometry reports whether the type is, or nests, a geometry
|
||||
// with the default CRS.
|
||||
func typeHasDefaultCRSGeometry(t iceberg.Type) bool {
|
||||
switch v := t.(type) {
|
||||
case iceberg.GeometryType:
|
||||
return v.CRS() == iceberg.DefaultGeoCRS
|
||||
case *iceberg.StructType:
|
||||
for _, f := range v.FieldList {
|
||||
if typeHasDefaultCRSGeometry(f.Type) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
case *iceberg.ListType:
|
||||
return typeHasDefaultCRSGeometry(v.Element)
|
||||
case *iceberg.MapType:
|
||||
return typeHasDefaultCRSGeometry(v.KeyType) || typeHasDefaultCRSGeometry(v.ValueType)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// schemaElementPaths is each flattened schema element's Iceberg field path
|
||||
// from the root (the root's is empty): the footer lists the tree depth first,
|
||||
// every group followed by its num_children children. The repeated group of a
|
||||
// LIST or MAP is not an Iceberg field, so it takes its parent's path; under it
|
||||
// a list's element is named "element" and a map's two children "key" and
|
||||
// "value", as Iceberg names them, whatever the writer called them.
|
||||
func schemaElementPaths(elements []format.SchemaElement) [][]string {
|
||||
paths := make([][]string, len(elements))
|
||||
var walk func(i int, path []string) int
|
||||
// children walks the n children of a group whose own path is path,
|
||||
// naming the k-th by name(k) when name is set.
|
||||
children := func(next, n int, path []string, name func(k int, el *format.SchemaElement) string) int {
|
||||
for c := 0; c < n && next < len(elements); c++ {
|
||||
child := path
|
||||
if name != nil {
|
||||
child = append(append([]string{}, path...), name(c, &elements[next]))
|
||||
} else {
|
||||
child = append(append([]string{}, path...), elements[next].Name)
|
||||
}
|
||||
next = walk(next, child)
|
||||
}
|
||||
return next
|
||||
}
|
||||
walk = func(i int, path []string) int {
|
||||
if i >= len(elements) {
|
||||
return i
|
||||
}
|
||||
paths[i] = path
|
||||
el := &elements[i]
|
||||
n := int(el.NumChildren.V)
|
||||
if n != 1 || i+1 >= len(elements) {
|
||||
return children(i+1, n, path, nil)
|
||||
}
|
||||
repeated := &elements[i+1]
|
||||
if rt, ok := repeated.RepetitionType.Get(); !ok || rt != format.Repeated {
|
||||
return children(i+1, n, path, nil)
|
||||
}
|
||||
switch {
|
||||
case isListAnnotated(el):
|
||||
// A repeated group of one field wraps the element, unless its
|
||||
// name marks the legacy form where the group is the element.
|
||||
if rn := int(repeated.NumChildren.V); rn == 1 && repeated.Name != "array" && repeated.Name != el.Name+"_tuple" {
|
||||
paths[i+1] = path
|
||||
return children(i+2, 1, path, func(int, *format.SchemaElement) string { return "element" })
|
||||
}
|
||||
return children(i+1, 1, path, func(int, *format.SchemaElement) string { return "element" })
|
||||
case isMapAnnotated(el):
|
||||
if int(repeated.NumChildren.V) == 2 {
|
||||
paths[i+1] = path
|
||||
return children(i+2, 2, path, func(k int, _ *format.SchemaElement) string {
|
||||
if k == 0 {
|
||||
return "key"
|
||||
}
|
||||
return "value"
|
||||
})
|
||||
}
|
||||
}
|
||||
return children(i+1, n, path, nil)
|
||||
}
|
||||
walk(0, nil)
|
||||
return paths
|
||||
}
|
||||
|
||||
func isListAnnotated(el *format.SchemaElement) bool {
|
||||
if _, ok := el.LogicalType.Value.(*format.ListType); ok {
|
||||
return true
|
||||
}
|
||||
ct, ok := el.ConvertedType.Get()
|
||||
return ok && ct == deprecated.List
|
||||
}
|
||||
|
||||
func isMapAnnotated(el *format.SchemaElement) bool {
|
||||
if _, ok := el.LogicalType.Value.(*format.MapType); ok {
|
||||
return true
|
||||
}
|
||||
ct, ok := el.ConvertedType.Get()
|
||||
return ok && (ct == deprecated.Map || ct == deprecated.MapKeyValue)
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/apache/iceberg-go"
|
||||
"github.com/apache/iceberg-go/table"
|
||||
"github.com/parquet-go/parquet-go"
|
||||
"github.com/parquet-go/parquet-go/compress/zstd"
|
||||
"github.com/parquet-go/parquet-go/format"
|
||||
)
|
||||
|
||||
// unsetDefaultCRS makes an input file declare the default CRS as no CRS at
|
||||
// all, as DuckDB and other writers do; parquet.Geometry("") spells it out.
|
||||
func unsetDefaultCRS(t *testing.T, data []byte) []byte {
|
||||
t.Helper()
|
||||
out, changed, err := withDefaultGeometryCRSUnset(data, geoTestSchema(iceberg.GeometryType{}))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("unset the input's default CRS: changed %v, %v", changed, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func fiveGeoFiles() []geoFile {
|
||||
var files []geoFile
|
||||
for f := 0; f < 5; f++ {
|
||||
var rows []geoRow
|
||||
for i := 0; i < 40; i++ {
|
||||
id := int64(f*40 + i)
|
||||
rows = append(rows, geoRow{ID: id, Geom: wkbPoint(float64(id%20)-10, float64(id/20)-5)})
|
||||
}
|
||||
files = append(files, geoFile{Name: fmt.Sprintf("g%d.parquet", f), Rows: rows})
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
// The Parquet CRS of a default-CRS geometry column survives compaction as the
|
||||
// inputs declared it: none. The control shows what parquet-go does with the
|
||||
// same schema on its own: it spells the default out.
|
||||
func TestCompactWritesDefaultCRSGeometryWithoutCRS(t *testing.T) {
|
||||
control := unsetDefaultCRS(t, writeGeoParquet(t, []geoRow{{1, wkbPoint(1, 2)}}, ""))
|
||||
if crs, ok := footerGeometryCRS(t, control, "geom"); !ok || crs != "" {
|
||||
t.Fatalf("setup: an input file declares CRS %q (geometry %v), want none", crs, ok)
|
||||
}
|
||||
f, err := parquet.OpenFile(bytes.NewReader(control), int64(len(control)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var plain bytes.Buffer
|
||||
w := parquet.NewWriter(&plain, f.Schema())
|
||||
if _, err := w.WriteRows([]parquet.Row{{parquet.ByteArrayValue(wkbPoint(1, 2)).Level(0, 1, 0), parquet.Int64Value(1).Level(0, 0, 1)}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if crs, _ := footerGeometryCRS(t, plain.Bytes(), "geom"); crs != iceberg.DefaultGeoCRS {
|
||||
t.Fatalf("control: parquet-go copied the schema with CRS %q; the fix is for %q", crs, iceberg.DefaultGeoCRS)
|
||||
}
|
||||
|
||||
for _, strategy := range []string{"binpack", "sort"} {
|
||||
t.Run(strategy, func(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"}
|
||||
opt := geoTableOptions{fixup: unsetDefaultCRS}
|
||||
config := Config{}
|
||||
if strategy == "sort" {
|
||||
so, err := table.NewSortOrder(1, []table.SortField{{SourceIDs: []int{geoTestIDField}, Transform: iceberg.IdentityTransform{}, Direction: table.SortASC, NullOrder: table.NullsFirst}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
opt.sortOrder = &so
|
||||
config.RewriteStrategy, config.SortBufferRows = "sort", minSortBufferRows
|
||||
}
|
||||
files := fiveGeoFiles()
|
||||
files[2].ParquetCRSSet = true // an input that spells the default out
|
||||
populateGeoTable(t, fs, setup, files, opt)
|
||||
if result := compactGeo(t, client, setup, config); !strings.Contains(result, "compacted 5 files") {
|
||||
t.Fatalf("result %q", result)
|
||||
}
|
||||
for name, data := range compactedFiles(t, fs, setup) {
|
||||
if crs, ok := footerGeometryCRS(t, data, "geom"); !ok || crs != "" {
|
||||
t.Errorf("%s: geometry column declares CRS %q (geometry %v), want none", name, crs, ok)
|
||||
}
|
||||
got, err := parquet.Read[struct {
|
||||
ID int64 `parquet:"id"`
|
||||
}](bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil || len(got) != 200 {
|
||||
t.Errorf("%s: the rewritten file reads %d rows, %v", name, len(got), err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An explicit CRS is not the default: it is written as the input declared it.
|
||||
func TestCompactKeepsExplicitGeometryCRS(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"}
|
||||
g, err := iceberg.GeometryTypeOf("EPSG:2913")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
populateGeoTable(t, fs, setup, fiveGeoFiles(), geoTableOptions{icebergType: g, parquetCRS: "EPSG:2913"})
|
||||
compactGeo(t, client, setup, Config{})
|
||||
for name, data := range compactedFiles(t, fs, setup) {
|
||||
if crs, ok := footerGeometryCRS(t, data, "geom"); !ok || crs != "EPSG:2913" {
|
||||
t.Errorf("%s: geometry CRS %q (geometry %v), want EPSG:2913", name, crs, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A default-CRS geometry nested in a struct is written without a CRS too.
|
||||
func TestDefaultCRSUnsetForNestedGeometry(t *testing.T) {
|
||||
schema := parquet.NewSchema("table", parquet.Group{
|
||||
"id": parquet.FieldID(parquet.Compressed(parquet.Int(64), &zstd.Codec{}), 1),
|
||||
"loc": parquet.FieldID(parquet.Group{"geom": parquet.FieldID(parquet.Optional(parquet.Geometry("")), 3)}, 2),
|
||||
})
|
||||
var buf bytes.Buffer
|
||||
w := parquet.NewGenericWriter[any](&buf, schema)
|
||||
cols := map[string]int{}
|
||||
for i, p := range schema.Columns() {
|
||||
cols[strings.Join(p, ".")] = i
|
||||
}
|
||||
row := make(parquet.Row, 2)
|
||||
row[cols["id"]] = parquet.Int64Value(1).Level(0, 0, cols["id"])
|
||||
row[cols["loc.geom"]] = parquet.ByteArrayValue(wkbPoint(1, 2)).Level(0, 1, cols["loc.geom"])
|
||||
if _, err := w.WriteRows([]parquet.Row{row}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if crs, ok := footerGeometryCRS(t, buf.Bytes(), "geom"); !ok || crs != iceberg.DefaultGeoCRS {
|
||||
t.Fatalf("setup: the nested column declares %q (geometry %v); the control is the spelled-out default", crs, ok)
|
||||
}
|
||||
ice := iceberg.NewSchema(0,
|
||||
iceberg.NestedField{ID: 1, Type: iceberg.PrimitiveTypes.Int64, Name: "id", Required: true},
|
||||
iceberg.NestedField{ID: 2, Name: "loc", Type: &iceberg.StructType{FieldList: []iceberg.NestedField{{ID: 3, Name: "geom", Type: iceberg.GeometryType{}}}}})
|
||||
out, changed, err := withDefaultGeometryCRSUnset(buf.Bytes(), ice)
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("changed %v, %v", changed, err)
|
||||
}
|
||||
if crs, ok := footerGeometryCRS(t, out, "geom"); !ok || crs != "" {
|
||||
t.Errorf("the nested geometry declares CRS %q (geometry %v), want none", crs, ok)
|
||||
}
|
||||
got, err := parquet.Read[struct {
|
||||
ID int64 `parquet:"id"`
|
||||
}](bytes.NewReader(out), int64(len(out)))
|
||||
if err != nil || len(got) != 1 || got[0].ID != 1 {
|
||||
t.Errorf("the rewritten file reads %v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// footerGeometryCRSs is the CRS of every GEOMETRY element in the footer, by
|
||||
// schema element index and name.
|
||||
func footerGeometryCRSs(t *testing.T, data []byte) map[string]string {
|
||||
t.Helper()
|
||||
f, err := parquet.OpenFile(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
out := map[string]string{}
|
||||
for i, el := range f.Metadata().Schema {
|
||||
if g, ok := el.LogicalType.Value.(*format.GeometryType); ok {
|
||||
out[fmt.Sprintf("%d:%s", i, el.Name)] = g.CRS
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// A file without field ids is matched to the table by name: through the
|
||||
// LIST and MAP wrapper groups too, which Iceberg's field names leave out.
|
||||
func TestDefaultCRSUnsetWithoutFieldIDs(t *testing.T) {
|
||||
geom := func() parquet.Node { return parquet.Optional(parquet.Geometry("")) }
|
||||
element := func(id int, typ iceberg.Type) *iceberg.ListType {
|
||||
return &iceberg.ListType{ElementID: id, Element: typ, ElementRequired: false}
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
parquet parquet.Group
|
||||
iceberg []iceberg.NestedField
|
||||
}{
|
||||
{"top level", parquet.Group{"id": parquet.Int(64), "geom": geom()},
|
||||
[]iceberg.NestedField{{ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true}, {ID: 2, Name: "geom", Type: iceberg.GeometryType{}}}},
|
||||
{"list", parquet.Group{"shapes": parquet.Optional(parquet.List(geom()))},
|
||||
[]iceberg.NestedField{{ID: 1, Name: "shapes", Type: element(2, iceberg.GeometryType{})}}},
|
||||
{"list of structs", parquet.Group{"items": parquet.Optional(parquet.List(parquet.Group{"geom": geom()}))},
|
||||
[]iceberg.NestedField{{ID: 1, Name: "items", Type: element(2, &iceberg.StructType{FieldList: []iceberg.NestedField{{ID: 3, Name: "geom", Type: iceberg.GeometryType{}}}})}}},
|
||||
{"map", parquet.Group{"attrs": parquet.Optional(parquet.Map(parquet.String(), geom()))},
|
||||
[]iceberg.NestedField{{ID: 1, Name: "attrs", Type: &iceberg.MapType{KeyID: 2, KeyType: iceberg.PrimitiveTypes.String, ValueID: 3, ValueType: iceberg.GeometryType{}}}}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
w := parquet.NewGenericWriter[any](&buf, parquet.NewSchema("table", tc.parquet))
|
||||
if err := w.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := footerGeometryCRSs(t, buf.Bytes())
|
||||
if len(before) != 1 {
|
||||
t.Fatalf("setup: geometry columns %v, want one", before)
|
||||
}
|
||||
for path, crs := range before {
|
||||
if crs != iceberg.DefaultGeoCRS {
|
||||
t.Fatalf("setup: %s declares %q; the control is the spelled-out default", path, crs)
|
||||
}
|
||||
}
|
||||
out, changed, err := withDefaultGeometryCRSUnset(buf.Bytes(), iceberg.NewSchema(0, tc.iceberg...))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("changed %v, %v", changed, err)
|
||||
}
|
||||
for path, crs := range footerGeometryCRSs(t, out) {
|
||||
if crs != "" {
|
||||
t.Errorf("%s declares CRS %q, want none", path, crs)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The footer is replaced inside the file's own buffer: a compacted file can be
|
||||
// as large as the target file size, and a copy of it would double the memory
|
||||
// the rewrite needs.
|
||||
func TestDefaultCRSUnsetReusesBuffer(t *testing.T) {
|
||||
data := writeGeoParquet(t, []geoRow{{1, wkbPoint(1, 2)}, {2, wkbPoint(3, 4)}}, "")
|
||||
if crs, ok := footerGeometryCRS(t, data, "geom"); !ok || crs != iceberg.DefaultGeoCRS {
|
||||
t.Fatalf("setup: CRS %q (geometry %v); the control is the spelled-out default", crs, ok)
|
||||
}
|
||||
first := &data[0]
|
||||
out, changed, err := withDefaultGeometryCRSUnset(data, geoTestSchema(iceberg.GeometryType{}))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("changed %v, %v", changed, err)
|
||||
}
|
||||
if &out[0] != first {
|
||||
t.Errorf("the rewrite copied the file into a new buffer")
|
||||
}
|
||||
if crs, ok := footerGeometryCRS(t, out, "geom"); !ok || crs != "" {
|
||||
t.Errorf("geometry declares CRS %q (geometry %v), want none", crs, ok)
|
||||
}
|
||||
got, err := parquet.Read[struct {
|
||||
ID int64 `parquet:"id"`
|
||||
Geom []byte `parquet:"geom,optional"`
|
||||
}](bytes.NewReader(out), int64(len(out)))
|
||||
if err != nil || len(got) != 2 || got[1].ID != 2 || !bytes.Equal(got[1].Geom, wkbPoint(3, 4)) {
|
||||
t.Errorf("the rewritten file reads %v, %v", got, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/apache/iceberg-go"
|
||||
"github.com/apache/iceberg-go/table"
|
||||
"github.com/parquet-go/parquet-go"
|
||||
"github.com/parquet-go/parquet-go/compress/zstd"
|
||||
"github.com/parquet-go/parquet-go/format"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
// Fixtures for v3 tables with a geometry column: Parquet files with field
|
||||
// ids, ZSTD and a native GEOMETRY column, and manifests that carry the v3
|
||||
// geometry bounds of each file, as DuckDB writes them.
|
||||
|
||||
const (
|
||||
geoTestIDField = 1
|
||||
geoTestGeomField = 2
|
||||
)
|
||||
|
||||
func wkbPoint(x, y float64) []byte {
|
||||
b := make([]byte, 21)
|
||||
b[0] = 1 // little endian
|
||||
binary.LittleEndian.PutUint32(b[1:], 1)
|
||||
binary.LittleEndian.PutUint64(b[5:], math.Float64bits(x))
|
||||
binary.LittleEndian.PutUint64(b[13:], math.Float64bits(y))
|
||||
return b
|
||||
}
|
||||
|
||||
// wkbBox is the polygon of one closed ring around the box.
|
||||
func wkbBox(xmin, ymin, xmax, ymax float64) []byte {
|
||||
ring := [][2]float64{{xmin, ymin}, {xmax, ymin}, {xmax, ymax}, {xmin, ymax}, {xmin, ymin}}
|
||||
b := make([]byte, 0, 13+16*len(ring))
|
||||
b = append(b, 1)
|
||||
b = binary.LittleEndian.AppendUint32(b, 3)
|
||||
b = binary.LittleEndian.AppendUint32(b, 1)
|
||||
b = binary.LittleEndian.AppendUint32(b, uint32(len(ring)))
|
||||
for _, p := range ring {
|
||||
b = binary.LittleEndian.AppendUint64(b, math.Float64bits(p[0]))
|
||||
b = binary.LittleEndian.AppendUint64(b, math.Float64bits(p[1]))
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func geoLE64(v int64) []byte {
|
||||
b := make([]byte, 8)
|
||||
binary.LittleEndian.PutUint64(b, uint64(v))
|
||||
return b
|
||||
}
|
||||
|
||||
func xyBound(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
|
||||
}
|
||||
|
||||
func decodeXYBound(t *testing.T, b []byte) (float64, float64) {
|
||||
t.Helper()
|
||||
if len(b) < 16 {
|
||||
t.Fatalf("geometry bound of %d bytes, want 16", len(b))
|
||||
}
|
||||
return math.Float64frombits(binary.LittleEndian.Uint64(b)), math.Float64frombits(binary.LittleEndian.Uint64(b[8:]))
|
||||
}
|
||||
|
||||
type geoRow struct {
|
||||
ID int64
|
||||
Geom []byte // nil: a null geometry
|
||||
}
|
||||
|
||||
type geoFile struct {
|
||||
Name string
|
||||
Rows []geoRow
|
||||
ParquetCRSSet bool // declare the default CRS in the Parquet logical type
|
||||
}
|
||||
|
||||
type geoTableOptions struct {
|
||||
icebergType iceberg.Type // the geometry column's Iceberg type (default: geometry with the default CRS)
|
||||
parquetCRS string // the CRS of the Parquet GEOMETRY type
|
||||
sortOrder *table.SortOrder // nil: unsorted
|
||||
properties iceberg.Properties
|
||||
// fixup, when set, rewrites each input file after it is written
|
||||
fixup func(t *testing.T, data []byte) []byte
|
||||
}
|
||||
|
||||
func geoTestSchema(geomType iceberg.Type) *iceberg.Schema {
|
||||
return iceberg.NewSchema(0,
|
||||
iceberg.NestedField{ID: geoTestIDField, Type: iceberg.PrimitiveTypes.Int64, Name: "id", Required: true},
|
||||
iceberg.NestedField{ID: geoTestGeomField, Type: geomType, Name: "geom", Required: false},
|
||||
)
|
||||
}
|
||||
|
||||
func writeGeoParquet(t *testing.T, rows []geoRow, crs string) []byte {
|
||||
t.Helper()
|
||||
schema := parquet.NewSchema("table", parquet.Group{
|
||||
"id": parquet.FieldID(parquet.Compressed(parquet.Int(64), &zstd.Codec{}), geoTestIDField),
|
||||
"geom": parquet.FieldID(parquet.Compressed(parquet.Optional(parquet.Geometry(crs)), &zstd.Codec{}), geoTestGeomField),
|
||||
})
|
||||
geomCol, idCol := -1, -1
|
||||
for i, p := range schema.Columns() {
|
||||
switch strings.Join(p, ".") {
|
||||
case "geom":
|
||||
geomCol = i
|
||||
case "id":
|
||||
idCol = i
|
||||
}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
w := parquet.NewGenericWriter[any](&buf, schema)
|
||||
for _, r := range rows {
|
||||
row := make(parquet.Row, 2)
|
||||
if r.Geom == nil {
|
||||
row[geomCol] = parquet.NullValue().Level(0, 0, geomCol)
|
||||
} else {
|
||||
row[geomCol] = parquet.ByteArrayValue(r.Geom).Level(0, 1, geomCol)
|
||||
}
|
||||
row[idCol] = parquet.Int64Value(r.ID).Level(0, 0, idCol)
|
||||
if _, err := w.WriteRows([]parquet.Row{row}); err != nil {
|
||||
t.Fatalf("write row: %v", err)
|
||||
}
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
t.Fatalf("close writer: %v", err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// footerGeoBox is the union of the file's row-group geometry boxes.
|
||||
func footerGeoBox(t *testing.T, data []byte) (xmin, ymin, xmax, ymax float64, ok bool) {
|
||||
t.Helper()
|
||||
f, err := parquet.OpenFile(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
xmin, ymin, xmax, ymax = math.Inf(1), math.Inf(1), math.Inf(-1), math.Inf(-1)
|
||||
for _, rg := range f.Metadata().RowGroups {
|
||||
for _, c := range rg.Columns {
|
||||
if strings.Join(c.MetaData.PathInSchema, ".") != "geom" || len(c.MetaData.GeospatialStatistics.GeoSpatialTypes) == 0 {
|
||||
continue
|
||||
}
|
||||
bb := c.MetaData.GeospatialStatistics.BBox
|
||||
xmin, ymin = math.Min(xmin, bb.XMin), math.Min(ymin, bb.YMin)
|
||||
xmax, ymax = math.Max(xmax, bb.XMax), math.Max(ymax, bb.YMax)
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// footerGeometryCRS is the CRS the file's GEOMETRY logical type declares, and
|
||||
// whether the column is GEOMETRY at all.
|
||||
func footerGeometryCRS(t *testing.T, data []byte, column string) (string, bool) {
|
||||
t.Helper()
|
||||
f, err := parquet.OpenFile(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
for _, el := range f.Metadata().Schema {
|
||||
if el.Name != column {
|
||||
continue
|
||||
}
|
||||
if g, ok := el.LogicalType.Value.(*format.GeometryType); ok {
|
||||
return g.CRS, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
t.Fatalf("no column %s in the footer", column)
|
||||
return "", false
|
||||
}
|
||||
|
||||
// populateGeoTable writes a v3 geometry table with one append snapshot and
|
||||
// one manifest per file.
|
||||
func populateGeoTable(t *testing.T, fs *fakeFilerServer, setup tableSetup, files []geoFile, opt geoTableOptions) table.Metadata {
|
||||
t.Helper()
|
||||
geomType := opt.icebergType
|
||||
if geomType == nil {
|
||||
geomType = iceberg.GeometryType{}
|
||||
}
|
||||
schema := geoTestSchema(geomType)
|
||||
spec := *iceberg.UnpartitionedSpec
|
||||
location := "s3://" + setup.BucketName + "/" + setup.dataPath()
|
||||
props := iceberg.Properties{"format-version": "3"}
|
||||
for k, v := range opt.properties {
|
||||
props[k] = v
|
||||
}
|
||||
sortOrder := table.UnsortedSortOrder
|
||||
if opt.sortOrder != nil {
|
||||
sortOrder = *opt.sortOrder
|
||||
}
|
||||
meta, err := table.NewMetadata(schema, &spec, sortOrder, location, props)
|
||||
if err != nil {
|
||||
t.Fatalf("create metadata: %v", err)
|
||||
}
|
||||
bucketPath := path.Join(s3tables.TablesPath, setup.BucketName)
|
||||
tableFilerPath := path.Join(bucketPath, setup.dataPath())
|
||||
metaDir := path.Join(tableFilerPath, "metadata")
|
||||
dataDir := path.Join(tableFilerPath, "data")
|
||||
putFile := func(dir, name string, data []byte) {
|
||||
fs.putEntry(dir, name, &filer_pb.Entry{Name: name, Content: data,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: time.Now().Unix(), FileSize: uint64(len(data))}})
|
||||
}
|
||||
snapID := int64(1)
|
||||
var manifests []iceberg.ManifestFile
|
||||
for i, f := range files {
|
||||
crs := opt.parquetCRS
|
||||
if f.ParquetCRSSet && crs == "" {
|
||||
crs = iceberg.DefaultGeoCRS
|
||||
}
|
||||
data := writeGeoParquet(t, f.Rows, crs)
|
||||
if opt.fixup != nil && !f.ParquetCRSSet {
|
||||
data = opt.fixup(t, data)
|
||||
}
|
||||
putFile(dataDir, f.Name, data)
|
||||
dfb, err := iceberg.NewDataFileBuilder(spec, iceberg.EntryContentData, setup.fileRef("data", f.Name), iceberg.ParquetFile, map[int]any{}, nil, nil, int64(len(f.Rows)), int64(len(data)))
|
||||
if err != nil {
|
||||
t.Fatalf("data file %s: %v", f.Name, err)
|
||||
}
|
||||
lo, hi := int64(math.MaxInt64), int64(math.MinInt64)
|
||||
for _, r := range f.Rows {
|
||||
lo, hi = min(lo, r.ID), max(hi, r.ID)
|
||||
}
|
||||
lower := map[int][]byte{geoTestIDField: geoLE64(lo)}
|
||||
upper := map[int][]byte{geoTestIDField: geoLE64(hi)}
|
||||
if xmin, ymin, xmax, ymax, ok := footerGeoBox(t, data); ok {
|
||||
lower[geoTestGeomField], upper[geoTestGeomField] = xyBound(xmin, ymin), xyBound(xmax, ymax)
|
||||
}
|
||||
dfb.LowerBoundValues(lower)
|
||||
dfb.UpperBoundValues(upper)
|
||||
entry := iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dfb.Build())
|
||||
name := fmt.Sprintf("data-manifest-%d.avro", i)
|
||||
var buf bytes.Buffer
|
||||
mf, err := iceberg.WriteManifest(setup.fileRef("metadata", name), &buf, 3, spec, schema, snapID, []iceberg.ManifestEntry{entry})
|
||||
if err != nil {
|
||||
t.Fatalf("write manifest: %v", err)
|
||||
}
|
||||
putFile(metaDir, name, buf.Bytes())
|
||||
manifests = append(manifests, mf)
|
||||
}
|
||||
var mlBuf bytes.Buffer
|
||||
mlw, err := iceberg.NewManifestListWriterV3(&mlBuf, snapID, 1, 0, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("manifest list writer: %v", err)
|
||||
}
|
||||
if err := mlw.AddManifests(manifests); err != nil {
|
||||
t.Fatalf("add manifests: %v", err)
|
||||
}
|
||||
if err := mlw.Close(); err != nil {
|
||||
t.Fatalf("close manifest list: %v", err)
|
||||
}
|
||||
putFile(metaDir, "snap-1.avro", mlBuf.Bytes())
|
||||
firstRowID := int64(0)
|
||||
addedRows := *mlw.NextRowID()
|
||||
snap := table.Snapshot{SnapshotID: snapID, SequenceNumber: 1, TimestampMs: time.Now().UnixMilli(),
|
||||
ManifestList: setup.fileRef("metadata", "snap-1.avro"),
|
||||
Summary: &table.Summary{Operation: table.OpAppend, Properties: map[string]string{}},
|
||||
FirstRowID: &firstRowID, AddedRows: &addedRows}
|
||||
builder, err := table.MetadataBuilderFromBase(meta, location)
|
||||
if err != nil {
|
||||
t.Fatalf("metadata builder: %v", err)
|
||||
}
|
||||
if err := builder.AddSnapshot(&snap); err != nil {
|
||||
t.Fatalf("add snapshot: %v", err)
|
||||
}
|
||||
if err := builder.SetSnapshotRef(table.MainBranch, snapID, table.BranchRef); err != nil {
|
||||
t.Fatalf("set ref: %v", err)
|
||||
}
|
||||
if meta, err = builder.Build(); err != nil {
|
||||
t.Fatalf("build metadata: %v", err)
|
||||
}
|
||||
full, _ := json.Marshal(meta)
|
||||
xattr, _ := json.Marshal(map[string]interface{}{
|
||||
"metadataVersion": 1,
|
||||
"metadataLocation": setup.fileRef("metadata", "v1.metadata.json"),
|
||||
"metadata": map[string]interface{}{"fullMetadata": json.RawMessage(full)},
|
||||
})
|
||||
fs.putEntry(s3tables.TablesPath, setup.BucketName, &filer_pb.Entry{
|
||||
Name: setup.BucketName, IsDirectory: true, Extended: map[string][]byte{s3tables.ExtendedKeyTableBucket: []byte("true")},
|
||||
})
|
||||
fs.putEntry(bucketPath, setup.Namespace, &filer_pb.Entry{Name: setup.Namespace, IsDirectory: true})
|
||||
fs.putEntry(path.Join(bucketPath, setup.Namespace), setup.TableName, &filer_pb.Entry{
|
||||
Name: setup.TableName, IsDirectory: true, Extended: map[string][]byte{s3tables.ExtendedKeyMetadata: xattr},
|
||||
})
|
||||
return meta
|
||||
}
|
||||
|
||||
func compactGeo(t *testing.T, client filer_pb.SeaweedFilerClient, setup tableSetup, config Config) string {
|
||||
t.Helper()
|
||||
if config.TargetFileSizeBytes == 0 {
|
||||
config.TargetFileSizeBytes = 256 * 1024 * 1024
|
||||
}
|
||||
if config.MinInputFiles == 0 {
|
||||
config.MinInputFiles = 2
|
||||
}
|
||||
if config.MaxCommitRetries == 0 {
|
||||
config.MaxCommitRetries = 3
|
||||
}
|
||||
config.ApplyDeletes = true
|
||||
result, _, err := NewHandler(nil).compactDataFiles(context.Background(), client, setup.BucketName, setup.tablePath(), config, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("compactDataFiles: %v", err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// compactedFiles is every compact-*.parquet in the table's data directory.
|
||||
func compactedFiles(t *testing.T, fs *fakeFilerServer, setup tableSetup) map[string][]byte {
|
||||
t.Helper()
|
||||
out := map[string][]byte{}
|
||||
for _, e := range fs.listDir(path.Join(s3tables.TablesPath, setup.BucketName, setup.tablePath(), "data")) {
|
||||
if strings.HasPrefix(e.Name, "compact-") {
|
||||
out[e.Name] = e.Content
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
t.Fatal("no compacted file")
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// currentDataEntries is every entry of the current snapshot's data manifests.
|
||||
func currentDataEntries(t *testing.T, client filer_pb.SeaweedFilerClient, setup tableSetup) []iceberg.ManifestEntry {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
state, err := loadCurrentMetadata(ctx, client, setup.BucketName, setup.tablePath())
|
||||
if err != nil {
|
||||
t.Fatalf("loadCurrentMetadata: %v", err)
|
||||
}
|
||||
manifests, err := loadCurrentManifests(ctx, client, setup.BucketName, state.DataPath, state.Metadata)
|
||||
if err != nil {
|
||||
t.Fatalf("loadCurrentManifests: %v", err)
|
||||
}
|
||||
var out []iceberg.ManifestEntry
|
||||
for _, mf := range manifests {
|
||||
if mf.ManifestContent() != iceberg.ManifestContentData {
|
||||
continue
|
||||
}
|
||||
data, err := loadFileByIcebergPath(ctx, client, setup.BucketName, state.DataPath, mf.FilePath())
|
||||
if err != nil {
|
||||
t.Fatalf("load manifest: %v", err)
|
||||
}
|
||||
entries, err := iceberg.ReadManifest(mf, bytes.NewReader(data), true)
|
||||
if err != nil {
|
||||
t.Fatalf("read manifest: %v", err)
|
||||
}
|
||||
out = append(out, entries...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"github.com/apache/iceberg-go"
|
||||
"github.com/apache/iceberg-go/table"
|
||||
"github.com/parquet-go/parquet-go"
|
||||
"github.com/parquet-go/parquet-go/compress"
|
||||
"github.com/parquet-go/parquet-go/compress/zstd"
|
||||
)
|
||||
|
||||
// Row lineage (Iceberg v3, spec "Row Lineage" and "Snapshot Row IDs").
|
||||
@@ -170,9 +172,16 @@ func newLineageLayout(reference *parquet.Schema) (*lineageLayout, error) {
|
||||
offsets = append(offsets, leaves)
|
||||
leaves += leafCount(f)
|
||||
}
|
||||
// The lineage columns are compressed like the reference's data columns
|
||||
// (not like a lineage column it already has): a leaf that declares no
|
||||
// codec is written uncompressed, 16 bytes a row.
|
||||
codec := lineageCodec(base)
|
||||
lineageLeaf := func(id int) parquet.Node {
|
||||
return parquet.FieldID(parquet.Compressed(parquet.Optional(parquet.Leaf(parquet.Int64Type)), codec), id)
|
||||
}
|
||||
fields := append(append([]parquet.Field{}, base...),
|
||||
lineageField{Node: parquet.FieldID(parquet.Optional(parquet.Leaf(parquet.Int64Type)), iceberg.RowIDFieldID), name: iceberg.RowIDColumnName},
|
||||
lineageField{Node: parquet.FieldID(parquet.Optional(parquet.Leaf(parquet.Int64Type)), iceberg.LastUpdatedSequenceNumberFieldID), name: iceberg.LastUpdatedSequenceNumberColumnName},
|
||||
lineageField{Node: lineageLeaf(iceberg.RowIDFieldID), name: iceberg.RowIDColumnName},
|
||||
lineageField{Node: lineageLeaf(iceberg.LastUpdatedSequenceNumberFieldID), name: iceberg.LastUpdatedSequenceNumberColumnName},
|
||||
)
|
||||
return &lineageLayout{
|
||||
schema: parquet.NewSchema(reference.Name(), &orderedGroup{Node: reference, fields: fields}),
|
||||
@@ -392,3 +401,26 @@ func mergedFileFirstRowID(data []byte) (*int64, error) {
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// lineageCodec is the codec of the first data column leaf that declares one,
|
||||
// ZSTD when none does.
|
||||
func lineageCodec(base []parquet.Field) compress.Codec {
|
||||
for _, f := range base {
|
||||
if c := columnCodec(f); c != nil {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return &zstd.Codec{}
|
||||
}
|
||||
|
||||
func columnCodec(n parquet.Node) compress.Codec {
|
||||
if n.Leaf() {
|
||||
return n.Compression()
|
||||
}
|
||||
for _, f := range n.Fields() {
|
||||
if c := columnCodec(f); c != nil {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
|
||||
"github.com/apache/iceberg-go"
|
||||
"github.com/parquet-go/parquet-go"
|
||||
"github.com/parquet-go/parquet-go/compress/zstd"
|
||||
"github.com/parquet-go/parquet-go/format"
|
||||
|
||||
filer_pb "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
@@ -382,3 +384,59 @@ func TestCompactDataFilesV3RowLineageManifestRead(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The lineage columns a v3 compaction adds are compressed like the data
|
||||
// columns.
|
||||
func TestCompactCompressesLineageColumns(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
setup := tableSetup{BucketName: "tb", Namespace: "ns", TableName: "geo"}
|
||||
populateGeoTable(t, fs, setup, fiveGeoFiles(), geoTableOptions{})
|
||||
compactGeo(t, client, setup, Config{})
|
||||
for name, data := range compactedFiles(t, fs, setup) {
|
||||
f, err := parquet.OpenFile(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seen := 0
|
||||
for _, rg := range f.Metadata().RowGroups {
|
||||
for _, c := range rg.Columns {
|
||||
col := strings.Join(c.MetaData.PathInSchema, ".")
|
||||
if col != iceberg.RowIDColumnName && col != iceberg.LastUpdatedSequenceNumberColumnName {
|
||||
continue
|
||||
}
|
||||
seen++
|
||||
if c.MetaData.Codec != format.Zstd {
|
||||
t.Errorf("%s: %s written with codec %v, want ZSTD like the data columns", name, col, c.MetaData.Codec)
|
||||
}
|
||||
}
|
||||
}
|
||||
if seen == 0 {
|
||||
t.Errorf("%s: no lineage column", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The lineage codec follows the data columns: an input whose own _row_id
|
||||
// comes first and is uncompressed does not leave the new lineage columns
|
||||
// uncompressed.
|
||||
func TestLineageCodecFollowsDataColumns(t *testing.T) {
|
||||
schema := parquet.NewSchema("table", parquet.Group{
|
||||
iceberg.RowIDColumnName: parquet.FieldID(parquet.Compressed(parquet.Optional(parquet.Int(64)), &parquet.Uncompressed), iceberg.RowIDFieldID),
|
||||
"id": parquet.FieldID(parquet.Compressed(parquet.Int(64), &zstd.Codec{}), 1),
|
||||
})
|
||||
if first := schema.Fields()[0].Name(); first != iceberg.RowIDColumnName {
|
||||
t.Fatalf("setup: first column %s, want %s", first, iceberg.RowIDColumnName)
|
||||
}
|
||||
layout, err := newLineageLayout(schema)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, f := range layout.schema.Fields() {
|
||||
if f.Name() != iceberg.RowIDColumnName && f.Name() != iceberg.LastUpdatedSequenceNumberColumnName {
|
||||
continue
|
||||
}
|
||||
if c := f.Compression(); c == nil || c.CompressionCodec() != format.Zstd {
|
||||
t.Errorf("%s compressed with %v, want ZSTD like the data column", f.Name(), c)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user