mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98a045824a | ||
|
|
8059c67458 | ||
|
|
039ee7a2fb | ||
|
|
0e256276e0 | ||
|
|
20764e1a82 | ||
|
|
5525fd829b | ||
|
|
63ee4c4b07 | ||
|
|
3b3fe1699f | ||
|
|
f453a37a26 | ||
|
|
ea4987f941 | ||
|
|
e6afa30579 | ||
|
|
aa3a9e8770 | ||
|
|
49d15f4287 | ||
|
|
c127f065d0 | ||
|
|
a5925906c8 | ||
|
|
e680a78d68 | ||
|
|
f8cfea0dcf | ||
|
|
c90da999f2 | ||
|
|
379abbe278 | ||
|
|
c601712cc4 | ||
|
|
ab738bfd33 | ||
|
|
222e96d6ab | ||
|
|
a724f4296c | ||
|
|
f05d743459 | ||
|
|
03a75cbc52 | ||
|
|
efa9d304d2 | ||
|
|
b7f5d04428 | ||
|
|
ece2f7a7c2 | ||
|
|
610346ae8c | ||
|
|
df89afbef4 | ||
|
|
1253b97303 | ||
|
|
a1d8739464 | ||
|
|
1cfd9bbb4c | ||
|
|
0de6347b11 | ||
|
|
6936bbdc3e | ||
|
|
4d06742664 |
No files matched your search
@@ -225,7 +225,7 @@ The full operation list is in [Amazon S3 API][AmazonS3API], and [Supported APIs
|
||||
|
||||
SeaweedFS is a lakehouse in one system. [S3 Table Buckets][S3TableBucket] hold Apache Iceberg tables by default, or [Lance][LanceCatalog] tables for vectors and multimodal data, and the built-in [Iceberg REST Catalog][IcebergCatalog] and Lance namespace serve them directly. There is no Hive Metastore, Glue, or separate catalog service to deploy, secure, and back up.
|
||||
|
||||
* Query engines operate on the same tables at the same time: [Spark][SparkIceberg], [Trino][TrinoIceberg], [Dremio][DremioIceberg], [DuckDB][DuckDBIceberg], [Apache Doris][DorisIceberg], [RisingWave][RisingWaveIceberg], ClickHouse, and [LanceDB][LanceDB]. Catalog commits are atomic compare-and-swap, so concurrent writers are safe. [Lakekeeper][Lakekeeper] can front the same storage with STS-vended credentials. [OLake][OLake] replicates PostgreSQL, MySQL, and MongoDB into the same tables with change data capture.
|
||||
* Query engines operate on the same tables at the same time: [Spark][SparkIceberg], [Trino][TrinoIceberg], [Dremio][DremioIceberg], [DuckDB][DuckDBIceberg], [Apache Doris][DorisIceberg], [RisingWave][RisingWaveIceberg], ClickHouse, and [LanceDB][LanceDB]. Catalog commits are atomic compare-and-swap, so concurrent writers are safe. [Lakekeeper][Lakekeeper] can front the same storage with STS-vended credentials. [OLake Go][OLake] is a high-performance, open-source EL (Extract–Load) platform that bridges operational databases and open lakehouse storage - writing Apache Iceberg tables or Parquet files on Amazon S3.
|
||||
* [Automated table maintenance][IcebergMaintenance]: compaction, snapshot expiration, orphan file removal, and manifest rewriting, configured per bucket or table through the S3 Tables maintenance APIs, and the same for [Lance][LanceMaintenance].
|
||||
* IAM at the bucket, namespace, and table level with standard bucket policies, see [S3 Tables Security][S3TablesSecurity].
|
||||
* A [Hadoop compatible file system][Hadoop] for Spark, Flink, and HBase.
|
||||
@@ -487,7 +487,7 @@ Your support will be really appreciated by me and other supporters!
|
||||
[RisingWaveIceberg]: https://github.com/seaweedfs/seaweedfs/wiki/RisingWave-Iceberg-Integration
|
||||
[LanceDB]: https://github.com/seaweedfs/seaweedfs/wiki/LanceDB-Integration
|
||||
[Lakekeeper]: https://github.com/seaweedfs/seaweedfs/wiki/Lakekeeper-Iceberg-Integration
|
||||
[OLake]: https://github.com/seaweedfs/seaweedfs/wiki/OLake-Iceberg-Integration
|
||||
[OLake]: https://github.com/seaweedfs/seaweedfs/wiki/OLake-Go-Iceberg-Integration
|
||||
[IcebergMaintenance]: https://github.com/seaweedfs/seaweedfs/wiki/Iceberg-Table-Maintenance
|
||||
[LanceMaintenance]: https://github.com/seaweedfs/seaweedfs/wiki/Lance-Maintenance-Worker
|
||||
[S3TablesSecurity]: https://github.com/seaweedfs/seaweedfs/wiki/S3-Tables-Security
|
||||
|
||||
+1099
-1050
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 55 KiB |
@@ -16,7 +16,7 @@ use crate::pb::filer_pb;
|
||||
use crate::pb::master_pb;
|
||||
use crate::pb::volume_server_pb;
|
||||
use crate::pb::volume_server_pb::volume_server_server::VolumeServer;
|
||||
use crate::storage::erasure_coding::ec_shard::{DATA_SHARDS_COUNT, ShardId, shard_id_try_from};
|
||||
use crate::storage::erasure_coding::ec_shard::{ShardId, shard_id_try_from};
|
||||
use crate::storage::erasure_coding::ecj_merge::EcjIdDecoder;
|
||||
use crate::storage::needle::needle::{self, Needle};
|
||||
use crate::storage::types::*;
|
||||
@@ -53,6 +53,12 @@ fn needle_not_found(needle_id: NeedleId) -> Status {
|
||||
Status::not_found(format!("needle not found {}", needle_id.0))
|
||||
}
|
||||
|
||||
/// Mirrors Go's `isNotLeaderErr`: the master returns raft's NotLeaderError,
|
||||
/// which arrives as an Unknown-status message.
|
||||
fn is_not_leader_status(e: &Status) -> bool {
|
||||
e.message().contains("Not current leader")
|
||||
}
|
||||
|
||||
/// Deadline from the caller's `grpc-timeout` header (TimeoutValue +
|
||||
/// H|M|S|m|u|n unit, per the gRPC-over-HTTP2 spec). Tonic's GrpcTimeout layer
|
||||
/// drops an over-deadline handler future anyway; parsing it here lets a queued
|
||||
@@ -344,22 +350,46 @@ impl VolumeGrpcService {
|
||||
is_readonly: bool,
|
||||
) -> Result<(), Status> {
|
||||
// VolumeMarkReadonly mutates raft-replicated master topology, so it must
|
||||
// reach the leader. Prefer the live leader the heartbeat is talking to
|
||||
// (current_master_url), falling back to the static seed before the first
|
||||
// heartbeat — mirrors store_ec.rs and Go's vs.GetMaster(). Sending it to
|
||||
// the static seed fails "not current leader" after any master failover.
|
||||
let master_url = {
|
||||
let live = self.state.current_master_url.read().await.clone();
|
||||
if !live.is_empty() {
|
||||
live
|
||||
} else {
|
||||
self.state.master_url.clone()
|
||||
}
|
||||
};
|
||||
// reach the leader the heartbeat confirmed. On "Not current leader",
|
||||
// ask the seed masters who leads and retry there — mirrors Go's
|
||||
// notifyMasterVolumeReadonly.
|
||||
let master_url = self.state.current_master().await;
|
||||
if master_url.is_empty() {
|
||||
return Ok(());
|
||||
if !self.state.has_master {
|
||||
return Ok(());
|
||||
}
|
||||
return Err(Status::unavailable("no master leader known"));
|
||||
}
|
||||
let grpc_addr = parse_grpc_address(&master_url).map_err(|e| {
|
||||
match self
|
||||
.volume_mark_readonly_on_master(&master_url, info, is_readonly)
|
||||
.await
|
||||
{
|
||||
Err(e) if is_not_leader_status(&e) => {
|
||||
let leader = super::heartbeat::lookup_leader_from_peers(
|
||||
&self.state.master_urls,
|
||||
self.state.outgoing_grpc_tls.as_ref(),
|
||||
)
|
||||
.await
|
||||
.ok_or_else(|| {
|
||||
Status::unavailable(format!(
|
||||
"master {} rejected mark-readonly and no peer named a leader",
|
||||
master_url
|
||||
))
|
||||
})?;
|
||||
self.volume_mark_readonly_on_master(&leader, info, is_readonly)
|
||||
.await
|
||||
}
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
async fn volume_mark_readonly_on_master(
|
||||
&self,
|
||||
master_url: &str,
|
||||
info: &MasterVolumeInfo,
|
||||
is_readonly: bool,
|
||||
) -> Result<(), Status> {
|
||||
let grpc_addr = parse_grpc_address(master_url).map_err(|e| {
|
||||
Status::internal(format!("invalid master address {}: {}", master_url, e))
|
||||
})?;
|
||||
let channel = connect_channel(
|
||||
@@ -1353,6 +1383,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
// Go's CommitCompact waits out leased readers under
|
||||
// dataFileAccessLock — do it without holding the store
|
||||
// guard, so a slow download stalls only this vacuum.
|
||||
let _sync_guard = vol.data_file_sync_lock().lock().unwrap();
|
||||
let _lease = vol.instance().write_lock();
|
||||
let is_read_only = vol.is_read_only();
|
||||
vol.commit_compact_held()
|
||||
@@ -2317,9 +2348,9 @@ impl VolumeServer for VolumeGrpcService {
|
||||
// owns the .ecx on disk (volume not yet mounted — relevant
|
||||
// when shards stream in mid-rebuild before any
|
||||
// VolumeEcShardsMount has happened; see #9212), then any
|
||||
// HDD, then any disk. Pass the build's default data-shard
|
||||
// count for free-slot maths; the helper takes it as a
|
||||
// parameter so custom-ratio builds can swap it.
|
||||
// HDD, then any disk. The free-slot maths uses the
|
||||
// volume's own data-shard count from its .vif so a
|
||||
// custom-ratio volume is not scored as 10+4.
|
||||
let vid = VolumeId(info.volume_id);
|
||||
let dir = if info.disk_id > 0 {
|
||||
let count = store.locations.len();
|
||||
@@ -2334,11 +2365,13 @@ impl VolumeServer for VolumeGrpcService {
|
||||
} else {
|
||||
// The mounted-volume refusal above means no disk
|
||||
// holds an in-memory claim here.
|
||||
let data_shards =
|
||||
store.lookup_ec_data_shards(&info.collection, vid);
|
||||
store
|
||||
.find_ec_shard_target_location(
|
||||
&info.collection,
|
||||
vid,
|
||||
DATA_SHARDS_COUNT as u32,
|
||||
data_shards,
|
||||
&[],
|
||||
)
|
||||
.map(|i| store.locations[i].directory.clone())
|
||||
@@ -3288,9 +3321,9 @@ impl VolumeServer for VolumeGrpcService {
|
||||
// volume mounted, then a disk that owns the .ecx on disk (volume
|
||||
// not yet mounted — relevant for ec.rebuild, where only the
|
||||
// first shard carries .ecx and subsequent shards must land on
|
||||
// the same disk; see #9212), then any HDD, then any disk. Pass
|
||||
// the build's default data-shard count; the helper takes it as a
|
||||
// parameter so custom-ratio builds can swap it.
|
||||
// the same disk; see #9212), then any HDD, then any disk. The
|
||||
// free-slot maths uses the volume's own data-shard count from its
|
||||
// .vif so a custom-ratio volume is not scored as 10+4.
|
||||
let (dest_dir, dest_idx_dir) = {
|
||||
let store = self.state.store.read().unwrap();
|
||||
let count = store.locations.len();
|
||||
@@ -3322,10 +3355,11 @@ impl VolumeServer for VolumeGrpcService {
|
||||
req.volume_id, shard_ids, dirs
|
||||
)));
|
||||
}
|
||||
let data_shards = store.lookup_ec_data_shards(&req.collection, vid);
|
||||
match store.find_ec_shard_target_location(
|
||||
&req.collection,
|
||||
vid,
|
||||
DATA_SHARDS_COUNT as u32,
|
||||
data_shards,
|
||||
&shard_ids,
|
||||
) {
|
||||
Some(i) => {
|
||||
@@ -4723,6 +4757,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
// backend swap: between clearing the remote-only write
|
||||
// restriction and attaching the local .dat a write would
|
||||
// pass check_writable and then fail on a missing dat_file.
|
||||
let _sync_guard = vol.data_file_sync_lock().lock().unwrap();
|
||||
let _lease = vol.instance().write_lock();
|
||||
|
||||
// The store guard dropped before the lease was taken, so an
|
||||
@@ -5771,7 +5806,8 @@ impl VolumeCopyJob {
|
||||
(&self.dest.data_base_name, self.dest.has_remote_dat);
|
||||
let mut preallocate_size: i64 = 0;
|
||||
if !has_remote_dat {
|
||||
let grpc_addr = super::heartbeat::to_grpc_address(&state.master_url);
|
||||
let master = state.current_master().await;
|
||||
let grpc_addr = super::heartbeat::to_grpc_address(&master);
|
||||
// Race the master-configuration RPC against the caller's
|
||||
// response channel: a stalled master (or a slow leader
|
||||
// election) would otherwise hold the task and its .note
|
||||
@@ -5796,7 +5832,7 @@ impl VolumeCopyJob {
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("get master {} configuration: {}", state.master_url, e);
|
||||
tracing::warn!("get master {} configuration: {}", master, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -603,7 +603,7 @@ async fn batch_delete_file_ids(
|
||||
let locations = lookup_volume(
|
||||
&state.http_client,
|
||||
&state.outgoing_http_scheme,
|
||||
&state.master_url,
|
||||
&state.current_master().await,
|
||||
volume_id,
|
||||
)
|
||||
.await
|
||||
@@ -675,7 +675,7 @@ async fn do_replicated_request(
|
||||
let locations = lookup_volume(
|
||||
&state.http_client,
|
||||
&state.outgoing_http_scheme,
|
||||
&state.master_url,
|
||||
&state.current_master().await,
|
||||
vid,
|
||||
)
|
||||
.await
|
||||
@@ -832,7 +832,7 @@ async fn proxy_or_redirect_to_target(
|
||||
let locations = match lookup_volume(
|
||||
&state.http_client,
|
||||
&state.outgoing_http_scheme,
|
||||
&state.master_url,
|
||||
&state.current_master().await,
|
||||
vid.0,
|
||||
)
|
||||
.await
|
||||
@@ -1238,7 +1238,7 @@ async fn proxy_missing_volume(
|
||||
let query_string = uri.query().unwrap_or("").to_string();
|
||||
if is_proxied_query(&query_string)
|
||||
|| state.read_mode == ReadMode::Local
|
||||
|| state.master_url.is_empty()
|
||||
|| state.current_master().await.is_empty()
|
||||
{
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
@@ -1282,7 +1282,7 @@ async fn check_download_limit(
|
||||
// Go tries proxy to replica once before the wait loop
|
||||
// (checkDownloadLimit); it does not retry on each wakeup.
|
||||
let should_try_replica =
|
||||
!is_proxied_query(&query_string) && !state.master_url.is_empty() && {
|
||||
!is_proxied_query(&query_string) && !state.current_master().await.is_empty() && {
|
||||
let store = state.store.read().unwrap();
|
||||
store
|
||||
.find_volume(vid)
|
||||
@@ -2960,7 +2960,9 @@ pub async fn post_handler(
|
||||
|
||||
// Replicate to remote volume servers if this volume has replicas.
|
||||
// Matches Go's GetWritableRemoteReplications: skip if copy_count == 1.
|
||||
if !is_replicate && write_result.is_ok() && !state.master_url.is_empty() {
|
||||
// No leader-known gate: when the lookup cannot run, the write must fail
|
||||
// rather than be acknowledged on fewer copies than required.
|
||||
if !is_replicate && write_result.is_ok() {
|
||||
let needs_replication = {
|
||||
let store = state.store.read().unwrap();
|
||||
store
|
||||
@@ -3358,7 +3360,7 @@ pub async fn delete_handler(
|
||||
};
|
||||
|
||||
let is_replicate = del_query.split('&').any(|p| p == "type=replicate");
|
||||
if !is_replicate && delete_result.is_ok() && !state.master_url.is_empty() {
|
||||
if !is_replicate && delete_result.is_ok() {
|
||||
let needs_replication = {
|
||||
let store = state.store.read().unwrap();
|
||||
store
|
||||
@@ -4232,7 +4234,7 @@ async fn read_remote_chunk_needle(
|
||||
let locations = lookup_volume(
|
||||
&state.http_client,
|
||||
&state.outgoing_http_scheme,
|
||||
&state.master_url,
|
||||
&state.current_master().await,
|
||||
vid.0,
|
||||
)
|
||||
.await?;
|
||||
@@ -6671,7 +6673,8 @@ mod tests {
|
||||
let s = Arc::get_mut(&mut state).unwrap();
|
||||
// Empty self_url makes `url.contains(self_url)` true for every peer.
|
||||
s.self_url = "198.51.100.8:8080".to_string();
|
||||
s.master_url = master_url;
|
||||
s.master_url = master_url.clone();
|
||||
s.current_master_url = tokio::sync::RwLock::new(master_url);
|
||||
state
|
||||
}
|
||||
|
||||
|
||||
@@ -155,7 +155,11 @@ pub async fn run_heartbeat_with_state(
|
||||
}
|
||||
PostAction::SleepPulse => {
|
||||
new_leader = None;
|
||||
tokio::time::sleep(pulse).await;
|
||||
// The lookup spends part of the retry delay rather than
|
||||
// adding to it.
|
||||
let retry_at = tokio::time::Instant::now() + pulse;
|
||||
refresh_leader_from_peers(&config, &state, pulse).await;
|
||||
tokio::time::sleep_until(retry_at).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,10 +258,54 @@ pub async fn try_get_master_configuration(
|
||||
Ok(resp.into_inner())
|
||||
}
|
||||
|
||||
/// Publish the leader the configured masters report, so lookups stop going
|
||||
/// to the master the heartbeat just lost while the loop retries. Without an
|
||||
/// answer inside `timeout` the published master is cleared: the lost master
|
||||
/// is dead or no longer leader, and a follower answers lookups from its own
|
||||
/// cache rather than refusing them. Mirrors Go's refreshLeaderFromPeers.
|
||||
async fn refresh_leader_from_peers(
|
||||
config: &HeartbeatConfig,
|
||||
state: &Arc<VolumeServerState>,
|
||||
timeout: Duration,
|
||||
) {
|
||||
let lookup =
|
||||
lookup_leader_from_peers(&config.master_addresses, state.outgoing_grpc_tls.as_ref());
|
||||
match tokio::time::timeout(timeout, lookup).await {
|
||||
Ok(Some(leader)) => publish_current_master(state, &leader).await,
|
||||
_ => state.current_master_url.write().await.clear(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask each seed master for the raft leader and return the first answer, or
|
||||
/// None when none replies with one. Mirrors Go's
|
||||
/// `operation.LookupRaftLeaderMaster`.
|
||||
pub async fn lookup_leader_from_peers(
|
||||
master_addrs: &[String],
|
||||
tls: Option<&super::grpc_client::OutgoingGrpcTlsConfig>,
|
||||
) -> Option<String> {
|
||||
for master_addr in master_addrs {
|
||||
let grpc_addr = to_grpc_address(master_addr);
|
||||
if let Ok(resp) = try_get_master_configuration(&grpc_addr, tls).await
|
||||
&& !resp.leader.is_empty()
|
||||
{
|
||||
return Some(resp.leader);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn is_stopping(state: &VolumeServerState) -> bool {
|
||||
*state.is_stopping.read().unwrap()
|
||||
}
|
||||
|
||||
/// Store the master lookups should go to, in the address form it was
|
||||
/// announced in — `host:port` or `host:port.grpcPort` — so an explicit gRPC
|
||||
/// port survives to the gRPC callers, mirroring Go's setCurrentMaster.
|
||||
/// The heartbeat calls this only for a master known to lead.
|
||||
async fn publish_current_master(state: &Arc<VolumeServerState>, master: &str) {
|
||||
*state.current_master_url.write().await = master.to_string();
|
||||
}
|
||||
|
||||
fn duplicate_uuid_retry_delay(retry_count: u32) -> Duration {
|
||||
Duration::from_secs((1u64 << retry_count) * 2)
|
||||
}
|
||||
@@ -430,14 +478,6 @@ async fn do_heartbeat(
|
||||
let mut response_stream = client.send_heartbeat(stream).await?.into_inner();
|
||||
|
||||
info!("Heartbeat stream established with {}", grpc_addr);
|
||||
// Publish the master we're now talking to in canonical http host:port
|
||||
// form so Ping admission can recognise it once a leader change moves us
|
||||
// off the seed list. Mirrors Go's vs.setCurrentMaster(masterAddress).
|
||||
{
|
||||
let normalised = super::volume_server::to_http_address(current_master).into_owned();
|
||||
let mut guard = state.current_master_url.write().await;
|
||||
*guard = normalised;
|
||||
}
|
||||
if is_stopping(state) {
|
||||
state.is_heartbeating.store(false, Ordering::Relaxed);
|
||||
send_deregister_heartbeat(config, state, &tx).await;
|
||||
@@ -451,13 +491,31 @@ async fn do_heartbeat(
|
||||
volume_tick.tick().await;
|
||||
ec_tick.tick().await;
|
||||
|
||||
let mut confirmed_leader = false;
|
||||
loop {
|
||||
tokio::select! {
|
||||
resp = response_stream.message() => {
|
||||
match resp {
|
||||
Ok(Some(hb_resp)) => {
|
||||
// Match Go ordering: DuplicatedUuids first, then volume
|
||||
// options, then leader redirect.
|
||||
// A reply names the leader or comes from it, so it
|
||||
// settles where lookups go before anything else on the
|
||||
// reply is handled: a follower reply carries no other
|
||||
// fields, and a leader stays the lookup target even
|
||||
// when it rejects this registration. Mirrors Go.
|
||||
if !hb_resp.leader.is_empty() {
|
||||
if super::volume_server::to_http_address(current_master)
|
||||
!= super::volume_server::to_http_address(&hb_resp.leader)
|
||||
{
|
||||
publish_current_master(state, &hb_resp.leader).await;
|
||||
return Ok(Some(hb_resp.leader));
|
||||
}
|
||||
} else if !confirmed_leader {
|
||||
// The leader answers every new stream without
|
||||
// naming a leader, so this peer is the one lookups
|
||||
// go to.
|
||||
confirmed_leader = true;
|
||||
publish_current_master(state, current_master).await;
|
||||
}
|
||||
if !hb_resp.duplicated_uuids.is_empty() {
|
||||
let uuids = hb_resp.duplicated_uuids.clone();
|
||||
let duplicate_dirs = off_runtime(config, state, move |_, state| {
|
||||
@@ -502,11 +560,6 @@ async fn do_heartbeat(
|
||||
if metrics_changed {
|
||||
state.metrics_notify.notify_waiters();
|
||||
}
|
||||
// Match Go: only redirect if leader is non-empty AND
|
||||
// different from the current master we're connected to.
|
||||
if !hb_resp.leader.is_empty() && current_master != hb_resp.leader {
|
||||
return Ok(Some(hb_resp.leader));
|
||||
}
|
||||
}
|
||||
Ok(None) => return Ok(None),
|
||||
Err(e) => return Err(Box::new(e)),
|
||||
@@ -2977,4 +3030,385 @@ mod tests {
|
||||
assert_eq!(deleted_after_delete[0].ec_index_bits, 1);
|
||||
assert_eq!(deleted_after_delete[0].shard_sizes, vec![0]);
|
||||
}
|
||||
|
||||
/// A master gRPC stub for the leader-tracking tests: every RPC except the
|
||||
/// two the tests drive is unimplemented. `leader` is what
|
||||
/// GetMasterConfiguration names; `replies` are what the heartbeat stream
|
||||
/// sends before closing.
|
||||
struct FakeMaster {
|
||||
leader: String,
|
||||
replies: Vec<master_pb::HeartbeatResponse>,
|
||||
}
|
||||
|
||||
#[tonic::async_trait]
|
||||
impl master_pb::seaweed_server::Seaweed for FakeMaster {
|
||||
type SendHeartbeatStream = tokio_stream::Iter<
|
||||
std::vec::IntoIter<Result<master_pb::HeartbeatResponse, tonic::Status>>,
|
||||
>;
|
||||
type KeepConnectedStream = tokio_stream::Iter<
|
||||
std::vec::IntoIter<Result<master_pb::KeepConnectedResponse, tonic::Status>>,
|
||||
>;
|
||||
type StreamAssignStream = tokio_stream::Iter<
|
||||
std::vec::IntoIter<Result<master_pb::AssignResponse, tonic::Status>>,
|
||||
>;
|
||||
type VolumeListStreamStream = tokio_stream::Iter<
|
||||
std::vec::IntoIter<Result<master_pb::VolumeListStreamResponse, tonic::Status>>,
|
||||
>;
|
||||
|
||||
async fn send_heartbeat(
|
||||
&self,
|
||||
_request: tonic::Request<tonic::Streaming<master_pb::Heartbeat>>,
|
||||
) -> std::result::Result<tonic::Response<Self::SendHeartbeatStream>, tonic::Status>
|
||||
{
|
||||
Ok(tonic::Response::new(tokio_stream::iter(
|
||||
self.replies.iter().cloned().map(Ok).collect::<Vec<_>>(),
|
||||
)))
|
||||
}
|
||||
|
||||
async fn keep_connected(
|
||||
&self,
|
||||
_request: tonic::Request<tonic::Streaming<master_pb::KeepConnectedRequest>>,
|
||||
) -> std::result::Result<tonic::Response<Self::KeepConnectedStream>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("keep_connected"))
|
||||
}
|
||||
|
||||
async fn stream_assign(
|
||||
&self,
|
||||
_request: tonic::Request<tonic::Streaming<master_pb::AssignRequest>>,
|
||||
) -> std::result::Result<tonic::Response<Self::StreamAssignStream>, tonic::Status> {
|
||||
Err(tonic::Status::unimplemented("stream_assign"))
|
||||
}
|
||||
|
||||
async fn get_master_configuration(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::GetMasterConfigurationRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<master_pb::GetMasterConfigurationResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
Ok(tonic::Response::new(
|
||||
master_pb::GetMasterConfigurationResponse {
|
||||
leader: self.leader.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
async fn lookup_volume(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::LookupVolumeRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::LookupVolumeResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("lookup_volume"))
|
||||
}
|
||||
|
||||
async fn assign(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::AssignRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::AssignResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("assign"))
|
||||
}
|
||||
|
||||
async fn statistics(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::StatisticsRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::StatisticsResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("statistics"))
|
||||
}
|
||||
|
||||
async fn collection_list(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::CollectionListRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::CollectionListResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("collection_list"))
|
||||
}
|
||||
|
||||
async fn collection_delete(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::CollectionDeleteRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::CollectionDeleteResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("collection_delete"))
|
||||
}
|
||||
|
||||
async fn volume_list(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::VolumeListRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::VolumeListResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("volume_list"))
|
||||
}
|
||||
|
||||
async fn volume_list_stream(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::VolumeListRequest>,
|
||||
) -> std::result::Result<tonic::Response<Self::VolumeListStreamStream>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("volume_list_stream"))
|
||||
}
|
||||
|
||||
async fn lookup_ec_volume(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::LookupEcVolumeRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::LookupEcVolumeResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("lookup_ec_volume"))
|
||||
}
|
||||
|
||||
async fn vacuum_volume(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::VacuumVolumeRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::VacuumVolumeResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("vacuum_volume"))
|
||||
}
|
||||
|
||||
async fn disable_vacuum(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::DisableVacuumRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::DisableVacuumResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("disable_vacuum"))
|
||||
}
|
||||
|
||||
async fn enable_vacuum(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::EnableVacuumRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::EnableVacuumResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("enable_vacuum"))
|
||||
}
|
||||
|
||||
async fn volume_mark_readonly(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::VolumeMarkReadonlyRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<master_pb::VolumeMarkReadonlyResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
Err(tonic::Status::unimplemented("volume_mark_readonly"))
|
||||
}
|
||||
|
||||
async fn list_cluster_nodes(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::ListClusterNodesRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::ListClusterNodesResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("list_cluster_nodes"))
|
||||
}
|
||||
|
||||
async fn lease_admin_token(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::LeaseAdminTokenRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::LeaseAdminTokenResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("lease_admin_token"))
|
||||
}
|
||||
|
||||
async fn release_admin_token(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::ReleaseAdminTokenRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::ReleaseAdminTokenResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("release_admin_token"))
|
||||
}
|
||||
|
||||
async fn get_admin_lock_status(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::GetAdminLockStatusRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<master_pb::GetAdminLockStatusResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
Err(tonic::Status::unimplemented("get_admin_lock_status"))
|
||||
}
|
||||
|
||||
async fn ping(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::PingRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::PingResponse>, tonic::Status> {
|
||||
Err(tonic::Status::unimplemented("ping"))
|
||||
}
|
||||
|
||||
async fn raft_list_cluster_servers(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::RaftListClusterServersRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<master_pb::RaftListClusterServersResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
Err(tonic::Status::unimplemented("raft_list_cluster_servers"))
|
||||
}
|
||||
|
||||
async fn raft_add_server(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::RaftAddServerRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::RaftAddServerResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("raft_add_server"))
|
||||
}
|
||||
|
||||
async fn raft_remove_server(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::RaftRemoveServerRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::RaftRemoveServerResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("raft_remove_server"))
|
||||
}
|
||||
|
||||
async fn raft_leadership_transfer(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::RaftLeadershipTransferRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<master_pb::RaftLeadershipTransferResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
Err(tonic::Status::unimplemented("raft_leadership_transfer"))
|
||||
}
|
||||
|
||||
async fn resume_volume_growth(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::ResumeVolumeGrowthRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<master_pb::ResumeVolumeGrowthResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
Err(tonic::Status::unimplemented("resume_volume_growth"))
|
||||
}
|
||||
|
||||
async fn volume_grow(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::VolumeGrowRequest>,
|
||||
) -> std::result::Result<tonic::Response<master_pb::VolumeGrowResponse>, tonic::Status>
|
||||
{
|
||||
Err(tonic::Status::unimplemented("volume_grow"))
|
||||
}
|
||||
|
||||
async fn collection_statistics(
|
||||
&self,
|
||||
_request: tonic::Request<master_pb::CollectionStatisticsRequest>,
|
||||
) -> std::result::Result<
|
||||
tonic::Response<master_pb::CollectionStatisticsResponse>,
|
||||
tonic::Status,
|
||||
> {
|
||||
Err(tonic::Status::unimplemented("collection_statistics"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a FakeMaster on a loopback port, returning the `host:port` gRPC
|
||||
/// clients dial. The task stops with the test's runtime.
|
||||
async fn fake_master_addr(fake: FakeMaster) -> String {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
tokio::spawn(async move {
|
||||
let _ = tonic::transport::Server::builder()
|
||||
.add_service(master_pb::seaweed_server::SeaweedServer::new(fake))
|
||||
.serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))
|
||||
.await;
|
||||
});
|
||||
format!("127.0.0.1:{port}")
|
||||
}
|
||||
|
||||
// Go's TestHeartbeatToFollowerPublishesNamedLeaderOnly: a reply that
|
||||
// names a different leader publishes it right away and ends the session
|
||||
// with the redirect — lookups stop landing on the follower.
|
||||
#[tokio::test]
|
||||
async fn test_heartbeat_to_a_follower_publishes_the_named_leader() {
|
||||
let grpc_addr = fake_master_addr(FakeMaster {
|
||||
leader: String::new(),
|
||||
replies: vec![master_pb::HeartbeatResponse {
|
||||
leader: "leader.example.com:9333".to_string(),
|
||||
..Default::default()
|
||||
}],
|
||||
})
|
||||
.await;
|
||||
let state = test_state_with_store(Store::new(NeedleMapKind::InMemory));
|
||||
let config = test_config();
|
||||
let (_shutdown_tx, mut shutdown_rx) = broadcast::channel(1);
|
||||
|
||||
let redirected = do_heartbeat(
|
||||
&config,
|
||||
&state,
|
||||
&grpc_addr,
|
||||
"127.0.0.1:0",
|
||||
Duration::from_millis(50),
|
||||
&mut shutdown_rx,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(redirected.as_deref(), Some("leader.example.com:9333"));
|
||||
assert_eq!(
|
||||
*state.current_master_url.read().await,
|
||||
"leader.example.com:9333"
|
||||
);
|
||||
}
|
||||
|
||||
// Go's TestHeartbeatToLeaderPublishesItAndResendsFromSendLoop, first
|
||||
// half: the first reply without a leader field is the leader's own, so
|
||||
// the connected peer becomes the lookup target.
|
||||
#[tokio::test]
|
||||
async fn test_heartbeat_to_the_leader_publishes_the_connected_peer() {
|
||||
let grpc_addr = fake_master_addr(FakeMaster {
|
||||
leader: String::new(),
|
||||
replies: vec![master_pb::HeartbeatResponse::default()],
|
||||
})
|
||||
.await;
|
||||
let state = test_state_with_store(Store::new(NeedleMapKind::InMemory));
|
||||
let config = test_config();
|
||||
let (_shutdown_tx, mut shutdown_rx) = broadcast::channel(1);
|
||||
|
||||
let redirected = do_heartbeat(
|
||||
&config,
|
||||
&state,
|
||||
&grpc_addr,
|
||||
"127.0.0.1:1",
|
||||
Duration::from_millis(50),
|
||||
&mut shutdown_rx,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(redirected.is_none());
|
||||
assert_eq!(*state.current_master_url.read().await, "127.0.0.1:1");
|
||||
}
|
||||
|
||||
// Go's TestRefreshLeaderFromPeersPublishesReportedLeader: after losing
|
||||
// the stream, the loop asks the configured masters who leads and
|
||||
// publishes the answer.
|
||||
#[tokio::test]
|
||||
async fn test_refresh_leader_from_peers_publishes_the_reported_leader() {
|
||||
let grpc_addr = fake_master_addr(FakeMaster {
|
||||
leader: "10.9.9.9:9333".to_string(),
|
||||
replies: vec![],
|
||||
})
|
||||
.await;
|
||||
let port = grpc_addr.rsplit(':').next().unwrap();
|
||||
let mut config = test_config();
|
||||
config.master_addresses = vec![format!("127.0.0.1:0.{port}")];
|
||||
let state = test_state_with_store(Store::new(NeedleMapKind::InMemory));
|
||||
|
||||
refresh_leader_from_peers(&config, &state, Duration::from_secs(5)).await;
|
||||
|
||||
assert_eq!(*state.current_master_url.read().await, "10.9.9.9:9333");
|
||||
}
|
||||
|
||||
// Go's TestRefreshLeaderFromPeersClearsLeaderWithoutAnswer: no peer
|
||||
// answering clears the published master — the lost one is dead or a
|
||||
// follower answering lookups from its own cache.
|
||||
#[tokio::test]
|
||||
async fn test_refresh_leader_from_peers_clears_without_an_answer() {
|
||||
let mut config = test_config();
|
||||
config.master_addresses = vec!["127.0.0.1:0.1".to_string()];
|
||||
let state = test_state_with_store(Store::new(NeedleMapKind::InMemory));
|
||||
*state.current_master_url.write().await = "dead.example.com:9333".to_string();
|
||||
|
||||
refresh_leader_from_peers(&config, &state, Duration::from_secs(2)).await;
|
||||
|
||||
assert!(state.current_master_url.read().await.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1139,16 +1139,9 @@ async fn cached_lookup_ec_shard_locations(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
) -> io::Result<HashMap<ShardId, Vec<String>>> {
|
||||
let master = {
|
||||
let live = state.current_master_url.read().await.clone();
|
||||
if !live.is_empty() {
|
||||
live
|
||||
} else {
|
||||
state.master_url.clone()
|
||||
}
|
||||
};
|
||||
let master = state.current_master().await;
|
||||
if master.is_empty() {
|
||||
return Err(io::Error::other("no master configured for ec shard lookup"));
|
||||
return Err(io::Error::other("no master leader known for ec shard lookup"));
|
||||
}
|
||||
|
||||
let grpc_addr =
|
||||
|
||||
@@ -86,7 +86,8 @@ pub struct VolumeServerState {
|
||||
/// If true, FetchAndWriteNeedle skips remote S3 endpoint validation,
|
||||
/// allowing arbitrary (incl. loopback / link-local / metadata) hosts.
|
||||
pub allow_untrusted_remote_endpoints: bool,
|
||||
/// First master address for volume lookups (e.g., "localhost:9333").
|
||||
/// First configured master address (e.g., "localhost:9333"). A seed, not a
|
||||
/// lookup target: lookups go to `current_master_url`.
|
||||
pub master_url: String,
|
||||
/// Seed master addresses for UI rendering.
|
||||
pub master_urls: Vec<String>,
|
||||
@@ -94,10 +95,12 @@ pub struct VolumeServerState {
|
||||
/// Built once at construction so Ping admission stays O(1). Mirrors
|
||||
/// Go's `seedMasterSet` on `VolumeServer`.
|
||||
pub seed_master_set: std::collections::HashSet<String>,
|
||||
/// Current master this server is heartbeating with, in canonical http
|
||||
/// `host:port` form. Empty when no heartbeat connection is active. The
|
||||
/// heartbeat goroutine writes; admission reads — the lock keeps them
|
||||
/// from racing on a leader change. Mirrors Go's `currentMaster` plus
|
||||
/// Master this server takes as leader, in its announced
|
||||
/// `host:port[.grpcPort]` form — callers pick http or gRPC form per use.
|
||||
/// Empty until the heartbeat confirms one — a peer that answered a
|
||||
/// stream without naming a leader, or the leader a follower named — and
|
||||
/// cleared again when no master reports one. The heartbeat writes;
|
||||
/// admission and lookups read. Mirrors Go's `currentMaster` plus
|
||||
/// `currentMasterLock`.
|
||||
pub current_master_url: tokio::sync::RwLock<String>,
|
||||
/// This server's own address (ip:port) for filtering self from lookup results.
|
||||
@@ -140,6 +143,13 @@ pub struct VolumeServerState {
|
||||
}
|
||||
|
||||
impl VolumeServerState {
|
||||
/// The master lookups should go to: the leader the heartbeat confirmed,
|
||||
/// or empty while none is known, in its announced `host:port[.grpcPort]`
|
||||
/// form. Mirrors Go's `vs.getCurrentMaster()`.
|
||||
pub async fn current_master(&self) -> String {
|
||||
self.current_master_url.read().await.clone()
|
||||
}
|
||||
|
||||
/// Check if the server is in maintenance mode; return gRPC error if so.
|
||||
pub fn check_maintenance(&self) -> Result<(), tonic::Status> {
|
||||
if self.maintenance.load(Ordering::Relaxed) {
|
||||
@@ -209,7 +219,7 @@ impl VolumeServerState {
|
||||
return false;
|
||||
}
|
||||
let current = self.current_master_url.read().await.clone();
|
||||
if !current.is_empty() && current == key {
|
||||
if !current.is_empty() && to_http_address(¤t) == key {
|
||||
return true;
|
||||
}
|
||||
self.seed_master_set.contains(&key)
|
||||
|
||||
@@ -18,3 +18,4 @@ pub mod volume_idx_repair;
|
||||
pub mod volume_open;
|
||||
pub mod volume_report;
|
||||
pub mod volume_report_hash;
|
||||
pub mod volume_tail_repair;
|
||||
@@ -14,7 +14,7 @@ use crate::pb::master_pb;
|
||||
use crate::storage::disk_location::DiskLocation;
|
||||
use crate::storage::erasure_coding::ec_shard::{EcVolumeShard, MAX_SHARD_COUNT, ShardId};
|
||||
use crate::storage::erasure_coding::ec_volume::{
|
||||
ECJ_COMPACT_TMP_EXT, EcVolume, is_usable_ecx_file,
|
||||
ECJ_COMPACT_TMP_EXT, EcVolume, is_usable_ecx_file, read_ec_shard_config_across_dirs,
|
||||
};
|
||||
use crate::storage::needle::needle::{Needle, get_actual_size};
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
@@ -416,6 +416,39 @@ impl Store {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Look up the per-volume EC data-shard count, preferring a mounted EC
|
||||
/// volume's own config and then the `.vif` on whichever disk holds it.
|
||||
/// Falls back to the default when neither exists yet (e.g. before the
|
||||
/// first shard streams in during ec.rebuild), so
|
||||
/// `find_ec_shard_target_location`'s free-slot maths scores custom-ratio
|
||||
/// volumes against their real width instead of the build default.
|
||||
pub fn lookup_ec_data_shards(&self, collection: &str, vid: VolumeId) -> u32 {
|
||||
use crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
|
||||
|
||||
for loc in &self.locations {
|
||||
if let Some(ec_vol) = loc.find_ec_volume(vid) {
|
||||
return ec_vol.data_shards;
|
||||
}
|
||||
}
|
||||
let Some(first) = self.locations.first() else {
|
||||
return DATA_SHARDS_COUNT as u32;
|
||||
};
|
||||
let other_dirs: Vec<String> = self.locations[1..]
|
||||
.iter()
|
||||
.flat_map(|loc| [loc.directory.clone(), loc.idx_directory.clone()])
|
||||
.filter(|d| !d.is_empty())
|
||||
.collect();
|
||||
read_ec_shard_config_across_dirs(
|
||||
&first.directory,
|
||||
&first.idx_directory,
|
||||
&other_dirs,
|
||||
collection,
|
||||
vid,
|
||||
)
|
||||
.map(|(data_shards, _, _)| data_shards)
|
||||
.unwrap_or(DATA_SHARDS_COUNT as u32)
|
||||
}
|
||||
|
||||
/// Create a new volume, placing it on the location with the most free space.
|
||||
pub fn add_volume(
|
||||
&mut self,
|
||||
@@ -2980,6 +3013,35 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A volume whose `.vif` declares a custom EC ratio must feed its own
|
||||
/// data-shard count into the free-slot maths — not the build default —
|
||||
/// wherever the `.vif` happens to sit. With no `.vif` anywhere (a
|
||||
/// brand-new volume mid-ec.rebuild) the answer is the default.
|
||||
#[test]
|
||||
fn test_lookup_ec_data_shards_reads_vif_on_any_disk() {
|
||||
use crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
|
||||
|
||||
let (store, _tmp) = make_ec_target_test_store(3);
|
||||
let collection = "custom-ratio";
|
||||
let vid = VolumeId(4242);
|
||||
|
||||
assert_eq!(
|
||||
store.lookup_ec_data_shards(collection, vid),
|
||||
DATA_SHARDS_COUNT as u32,
|
||||
"no .vif anywhere must answer the default"
|
||||
);
|
||||
|
||||
// A 6+2 .vif lands on disk 2 only — the rebuild staging disk.
|
||||
let base = volume_file_name(&store.locations[2].directory, collection, vid);
|
||||
std::fs::write(
|
||||
format!("{}.vif", base),
|
||||
br#"{"ecShardConfig":{"dataShards":6,"parityShards":2}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(store.lookup_ec_data_shards(collection, vid), 6);
|
||||
}
|
||||
|
||||
/// Deleting a disk's last shard removes that disk's now-orphaned `.ecsum`;
|
||||
/// a disk this delete never changed keeps its sidecar. Disk 0 models
|
||||
/// ec.rebuild's index-prep state (`.ecsum` landed, no shards yet) — an
|
||||
|
||||
@@ -29,6 +29,7 @@ use crate::storage::needle_map::{CompactNeedleMap, NeedleMap, NeedleMapKind, Red
|
||||
use crate::storage::super_block::{ReplicaPlacement, SUPER_BLOCK_SIZE, SuperBlock};
|
||||
use crate::storage::types::*;
|
||||
use crate::storage::volume_open::open_volume_file;
|
||||
use crate::storage::volume_tail_repair::TailRepairError;
|
||||
|
||||
// ============================================================================
|
||||
// Errors
|
||||
@@ -1247,6 +1248,12 @@ pub struct Volume {
|
||||
idx_syncs_for_test: std::sync::atomic::AtomicUsize,
|
||||
needle_map_kind: NeedleMapKind,
|
||||
data_file_access_control: Arc<DataFileAccessControl>,
|
||||
/// Serializes a data-file mutation with the sync that makes it durable:
|
||||
/// write, delete and lifecycle paths hold it for their whole critical
|
||||
/// section, while the fsync itself runs with only the `io` read guard so
|
||||
/// readers of this volume do not wait on it. Lock order is
|
||||
/// `data_file_sync_lock` -> `data_file_access_control` -> `io`.
|
||||
data_file_sync_lock: std::sync::Mutex<()>,
|
||||
|
||||
/// Go's superBlockAccessLock.
|
||||
super_block: RwLock<SuperBlock>,
|
||||
@@ -1370,6 +1377,7 @@ impl Volume {
|
||||
idx_syncs_for_test: Default::default(),
|
||||
needle_map_kind,
|
||||
data_file_access_control: Arc::new(DataFileAccessControl::default()),
|
||||
data_file_sync_lock: std::sync::Mutex::new(()),
|
||||
super_block: RwLock::new(SuperBlock {
|
||||
replica_placement: replica_placement.unwrap_or_default(),
|
||||
ttl: ttl.unwrap_or(crate::storage::needle::ttl::TTL::EMPTY),
|
||||
@@ -1426,6 +1434,7 @@ impl Volume {
|
||||
idx_syncs_for_test: Default::default(),
|
||||
needle_map_kind: NeedleMapKind::InMemory,
|
||||
data_file_access_control: Arc::new(DataFileAccessControl::default()),
|
||||
data_file_sync_lock: std::sync::Mutex::new(()),
|
||||
super_block: RwLock::new(SuperBlock::default()),
|
||||
no_write: AtomicU8::new(0),
|
||||
io_unavailable: Arc::default(),
|
||||
@@ -1446,6 +1455,13 @@ impl Volume {
|
||||
self.data_file_access_control.clone()
|
||||
}
|
||||
|
||||
/// The mutation/sync serializer, for callers that manage the access
|
||||
/// lease themselves (the `_held` lifecycle paths). Same lock order as
|
||||
/// everywhere else: sync lock first, then the write lease, then `io`.
|
||||
pub(crate) fn data_file_sync_lock(&self) -> &std::sync::Mutex<()> {
|
||||
&self.data_file_sync_lock
|
||||
}
|
||||
|
||||
pub(crate) fn is_instance(&self, instance: &Arc<DataFileAccessControl>) -> bool {
|
||||
Arc::ptr_eq(instance, &self.data_file_access_control)
|
||||
}
|
||||
@@ -1709,6 +1725,48 @@ impl Volume {
|
||||
),
|
||||
}
|
||||
|
||||
// A crash between the .dat append and the .idx append leaves a
|
||||
// .dat tail no index entry covers. Re-index complete needles and
|
||||
// cut an incomplete remainder before the index loads, so the
|
||||
// recovered rows land in the needle map and inside its append
|
||||
// offset. Mirrors Go running repairUnindexedDatTail inside
|
||||
// CheckVolumeDataIntegrity ahead of the needle map load. Only a
|
||||
// volume about to load writable is repaired.
|
||||
// A no_write_can_delete volume still appends tombstone records on
|
||||
// delete, so it tears tails the same way and gets the same repair.
|
||||
if !self.has_remote_file() && !self.no_write_flags().0 {
|
||||
// An empty .idx gets the same repair: every check below
|
||||
// skips an empty index on its own, so a tail the repair
|
||||
// cannot explain there fails the load like in Go rather
|
||||
// than warn and load writable.
|
||||
let idx_empty = fs::metadata(self.file_name(".idx"))
|
||||
.map(|m| m.len() == 0)
|
||||
.unwrap_or(false);
|
||||
match self.repair_unindexed_dat_tail(io) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.is_not_torn() && !idx_empty => warn!(
|
||||
volume_id = self.id.0,
|
||||
error = %e,
|
||||
"unindexed .dat tail not repaired"
|
||||
),
|
||||
// The index refusing a read-write open is the same failure
|
||||
// Go reports opening it ahead of the check: it fails the
|
||||
// load rather than only the repair.
|
||||
Err(TailRepairError::OpenIndex(e)) => return Err(e),
|
||||
Err(e) => {
|
||||
// A repair that could not complete must not load the
|
||||
// volume writable on files it half-fixed: the check
|
||||
// fails as in Go, so the volume loads read-only.
|
||||
self.set_no_write_flag(NO_WRITE_OR_DELETE, true);
|
||||
warn!(
|
||||
volume_id = self.id.0,
|
||||
error = %e,
|
||||
"repair unindexed .dat tail"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.load_index(io)?;
|
||||
|
||||
// Match Go: CheckVolumeDataIntegrity after loading index (volume_loading.go L154-159)
|
||||
@@ -1980,6 +2038,7 @@ impl Volume {
|
||||
}
|
||||
|
||||
pub(crate) fn load_remote_dat_file(&self) -> Result<(), VolumeError> {
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let mut io = self.io.write().unwrap();
|
||||
self.load_remote_dat_file_io(&mut io)
|
||||
@@ -2066,7 +2125,7 @@ impl Volume {
|
||||
self.current_dat_file_size_io(&io)
|
||||
}
|
||||
|
||||
fn current_dat_file_size_io(&self, io: &VolumeIo) -> io::Result<u64> {
|
||||
pub(crate) fn current_dat_file_size_io(&self, io: &VolumeIo) -> io::Result<u64> {
|
||||
if let Some(ref f) = io.dat_file {
|
||||
Ok(f.metadata()?.len())
|
||||
} else if let Some(ref remote_dat_file) = io.remote_dat_file {
|
||||
@@ -2290,7 +2349,7 @@ impl Volume {
|
||||
self.read_needle_blob_unlocked(&io, offset, size)
|
||||
}
|
||||
|
||||
fn read_needle_blob_unlocked(
|
||||
pub(crate) fn read_needle_blob_unlocked(
|
||||
&self,
|
||||
io: &VolumeIo,
|
||||
offset: i64,
|
||||
@@ -2509,10 +2568,14 @@ impl Volume {
|
||||
check_cookie: bool,
|
||||
fsync: bool,
|
||||
) -> Result<(u64, Size, bool), VolumeError> {
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let mut io = self.io.write().unwrap();
|
||||
self.check_writable()?;
|
||||
self.do_write_request(&mut io, n, check_cookie, fsync)
|
||||
// A single write is a one-entry run of the grouped path: identical
|
||||
// outcome, and the fsync handling lives in one place.
|
||||
debug_assert!(check_cookie, "every write_needle caller checks the cookie");
|
||||
let _ = check_cookie;
|
||||
let mut writes = [(std::mem::take(n), fsync)];
|
||||
let mut results = self.write_needles_grouped(&mut writes);
|
||||
*n = std::mem::replace(&mut writes[0].0, Needle::default());
|
||||
results.pop().unwrap_or(Err(VolumeError::NotFound))
|
||||
}
|
||||
|
||||
/// Write a batch of needles the way Go's processBatch does: one .dat
|
||||
@@ -2527,8 +2590,13 @@ impl Volume {
|
||||
&self,
|
||||
writes: &mut [(Needle, bool)],
|
||||
) -> Vec<Result<(u64, Size, bool), VolumeError>> {
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let mut io = self.io.write().unwrap();
|
||||
// The sync lock serializes a .dat mutation with the flush that makes
|
||||
// it durable: a failed sync's rollback can never clobber an append
|
||||
// that slipped in behind it, and a compaction swap or unlink cannot
|
||||
// land between the append and its sync. Readers never take it, and
|
||||
// the write-side guards are dropped for the sync itself, so reads of
|
||||
// this volume do not wait on fsync.
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let mut results = Vec::with_capacity(writes.len());
|
||||
let mut rest = writes;
|
||||
while !rest.is_empty() {
|
||||
@@ -2536,8 +2604,10 @@ impl Volume {
|
||||
let len = rest.iter().take_while(|(n, _)| ids.insert(n.id)).count();
|
||||
let (run, tail) = std::mem::take(&mut rest).split_at_mut(len);
|
||||
if run.iter().any(|(_, fsync)| *fsync) {
|
||||
results.extend(self.write_synced_run(&mut io, run));
|
||||
results.extend(self.write_synced_run(run));
|
||||
} else {
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let mut io = self.io.write().unwrap();
|
||||
for (n, _) in run.iter_mut() {
|
||||
results.push(
|
||||
self.check_writable()
|
||||
@@ -2552,7 +2622,6 @@ impl Volume {
|
||||
|
||||
fn write_synced_run(
|
||||
&self,
|
||||
io: &mut VolumeIo,
|
||||
run: &mut [(Needle, bool)],
|
||||
) -> Vec<Result<(u64, Size, bool), VolumeError>> {
|
||||
// Per entry: Some(offset) once appended, None when it dedups.
|
||||
@@ -2560,63 +2629,82 @@ impl Volume {
|
||||
// Per entry: the I/O error streak once it is staged, where a write
|
||||
// sent on its own would have recorded its success.
|
||||
let mut marks = Vec::with_capacity(run.len());
|
||||
let mut last_append_at_ns = io.last_append_at_ns;
|
||||
let mut last_append_at_ns;
|
||||
let mut run_start = None;
|
||||
let mut sync = false;
|
||||
for (n, fsync) in run.iter_mut() {
|
||||
let r = self.append_unpublished(io, n, &mut last_append_at_ns);
|
||||
marks.push(self.io_errors.mark());
|
||||
if let Ok(Some(offset)) = r {
|
||||
run_start.get_or_insert(offset);
|
||||
}
|
||||
// Only a durable entry that got this far needs the sync.
|
||||
sync |= *fsync && r.is_ok();
|
||||
staged.push(r);
|
||||
}
|
||||
|
||||
if sync && let Err(e) = self.flush_dat(io) {
|
||||
self.check_read_write_error(Some(&e));
|
||||
if let Some(start) = run_start {
|
||||
self.undo_unsynced_append(io, start);
|
||||
}
|
||||
let e = VolumeError::Io(e);
|
||||
return staged
|
||||
.into_iter()
|
||||
.map(|r| r.and_then(|_| Err(run_error(&e))))
|
||||
.collect();
|
||||
}
|
||||
io.last_append_at_ns = last_append_at_ns;
|
||||
for ((n, _), r) in run.iter().zip(&staged) {
|
||||
if matches!(r, Ok(Some(_))) && n.append_at_ns > io.last_write_append_at_ns {
|
||||
io.last_write_append_at_ns = n.append_at_ns;
|
||||
io.last_write_needle_key = n.id;
|
||||
io.last_write_deleted = false;
|
||||
{
|
||||
// Append under the write guards, then drop them for the flush:
|
||||
// readers need only `io`'s read side, while mutators and a
|
||||
// compaction swap stay excluded by the caller's sync lock.
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let mut io = self.io.write().unwrap();
|
||||
last_append_at_ns = io.last_append_at_ns;
|
||||
for (n, fsync) in run.iter_mut() {
|
||||
let r = self.append_unpublished(&mut io, n, &mut last_append_at_ns);
|
||||
marks.push(self.io_errors.mark());
|
||||
if let Ok(Some(offset)) = r {
|
||||
run_start.get_or_insert(offset);
|
||||
}
|
||||
// Only a durable entry that got this far needs the sync.
|
||||
sync |= *fsync && r.is_ok();
|
||||
staged.push(r);
|
||||
}
|
||||
}
|
||||
|
||||
// A durable entry that fails to publish stops the volume taking
|
||||
// writes, so the entries after it are refused the way a lone
|
||||
// write would be.
|
||||
let mut refused = false;
|
||||
for ((n, fsync), r) in run.iter().zip(staged.iter_mut()) {
|
||||
if refused {
|
||||
*r = Err(self
|
||||
.check_writable()
|
||||
.err()
|
||||
.unwrap_or(VolumeError::ReadOnly(self.id)));
|
||||
} else if let Ok(Some(offset)) = *r
|
||||
&& let Err(e) = self.publish_write(io, n, offset, *fsync)
|
||||
{
|
||||
*r = Err(e);
|
||||
refused = *fsync;
|
||||
if sync {
|
||||
let io = self.io.read().unwrap();
|
||||
if let Err(e) = self.flush_dat(&io) {
|
||||
self.check_read_write_error(Some(&e));
|
||||
if let Some(start) = run_start {
|
||||
self.undo_unsynced_append(&io, start);
|
||||
}
|
||||
let e = VolumeError::Io(e);
|
||||
return staged
|
||||
.into_iter()
|
||||
.map(|r| r.and_then(|_| Err(run_error(&e))))
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
|
||||
if sync && let Err(e) = self.flush_idx(io) {
|
||||
return staged
|
||||
.into_iter()
|
||||
.map(|r| r.and_then(|_| Err(run_error(&e))))
|
||||
.collect();
|
||||
{
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let mut io = self.io.write().unwrap();
|
||||
io.last_append_at_ns = last_append_at_ns;
|
||||
for ((n, _), r) in run.iter().zip(&staged) {
|
||||
if matches!(r, Ok(Some(_))) && n.append_at_ns > io.last_write_append_at_ns {
|
||||
io.last_write_append_at_ns = n.append_at_ns;
|
||||
io.last_write_needle_key = n.id;
|
||||
io.last_write_deleted = false;
|
||||
}
|
||||
}
|
||||
|
||||
// A durable entry that fails to publish stops the volume taking
|
||||
// writes, so the entries after it are refused the way a lone
|
||||
// write would be.
|
||||
let mut refused = false;
|
||||
for ((n, fsync), r) in run.iter().zip(staged.iter_mut()) {
|
||||
if refused {
|
||||
*r = Err(self
|
||||
.check_writable()
|
||||
.err()
|
||||
.unwrap_or(VolumeError::ReadOnly(self.id)));
|
||||
} else if let Ok(Some(offset)) = *r
|
||||
&& let Err(e) = self.publish_write(&mut io, n, offset, *fsync)
|
||||
{
|
||||
*r = Err(e);
|
||||
refused = *fsync;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if sync {
|
||||
let io = self.io.read().unwrap();
|
||||
if let Err(e) = self.flush_idx(&io) {
|
||||
return staged
|
||||
.into_iter()
|
||||
.map(|r| r.and_then(|_| Err(run_error(&e))))
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
|
||||
let written = run
|
||||
@@ -2630,7 +2718,9 @@ impl Volume {
|
||||
// Sent one at a time, the last write to land would have cleared
|
||||
// the streak of the appends before it, and the ones after it
|
||||
// would have failed on top of that.
|
||||
self.finish_write(io, last_modified, sync, marks[last]);
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let mut io = self.io.write().unwrap();
|
||||
self.finish_write(&mut io, last_modified, sync, marks[last]);
|
||||
}
|
||||
|
||||
run.iter()
|
||||
@@ -2679,7 +2769,7 @@ impl Volume {
|
||||
/// Flush the .dat, the first half of a durable write. The .idx is flushed
|
||||
/// separately by flush_idx once the row is published; the two are split so
|
||||
/// nothing is indexed before the bytes it points at are down.
|
||||
fn flush_dat(&self, io: &VolumeIo) -> io::Result<()> {
|
||||
pub(crate) fn flush_dat(&self, io: &VolumeIo) -> io::Result<()> {
|
||||
#[cfg(test)]
|
||||
self.dat_syncs_for_test.fetch_add(1, Ordering::Relaxed);
|
||||
#[cfg(test)]
|
||||
@@ -2731,7 +2821,7 @@ impl Volume {
|
||||
}
|
||||
|
||||
/// Take an unflushed append back off the .dat after its sync failed.
|
||||
fn truncate_dat(&self, io: &VolumeIo, len: u64) -> io::Result<()> {
|
||||
pub(crate) fn truncate_dat(&self, io: &VolumeIo, len: u64) -> io::Result<()> {
|
||||
#[cfg(test)]
|
||||
if io.fail_truncate_for_test {
|
||||
return Err(io::Error::other("injected truncate failure"));
|
||||
@@ -3082,6 +3172,7 @@ impl Volume {
|
||||
|
||||
/// Delete a needle from the volume.
|
||||
pub fn delete_needle(&self, n: &mut Needle) -> Result<Size, VolumeError> {
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let mut io = self.io.write().unwrap();
|
||||
if self.is_closed() {
|
||||
@@ -3464,7 +3555,7 @@ impl Volume {
|
||||
/// key-sorted .idx (e.g. legacy weed fix output) falls back to a single
|
||||
/// linear scan for the maximum offset. Returns -1 when no entry has a
|
||||
/// non-zero offset (a pre-allocated / all-zero index).
|
||||
fn find_dat_tail_entry_offset(
|
||||
pub(crate) fn find_dat_tail_entry_offset(
|
||||
&self,
|
||||
io: &VolumeIo,
|
||||
idx_file: &mut File,
|
||||
@@ -3981,6 +4072,7 @@ impl Volume {
|
||||
offset: Offset,
|
||||
size: Size,
|
||||
) -> Result<(), VolumeError> {
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let mut io = self.io.write().unwrap();
|
||||
if let Some(ref mut nm) = io.nm {
|
||||
@@ -4005,6 +4097,7 @@ impl Volume {
|
||||
// The flag flip and the .vif save are one critical section with the idx
|
||||
// attach: Go's markVolumeReadonly runs under dataFileAccessLock, so a
|
||||
// racing mark-writable cannot interleave a save of half-applied state.
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
self.set_read_only_persist_held(can_delete, persist)
|
||||
}
|
||||
@@ -4089,6 +4182,7 @@ impl Volume {
|
||||
if let Some(e) = self.unavailable_error() {
|
||||
return Err(e);
|
||||
}
|
||||
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.
|
||||
@@ -4187,6 +4281,7 @@ impl Volume {
|
||||
&self,
|
||||
f: impl FnOnce(&mut Vec<PbRemoteFile>),
|
||||
) -> Result<(), VolumeError> {
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
self.update_remote_files_held(f)
|
||||
}
|
||||
@@ -4451,6 +4546,7 @@ impl Volume {
|
||||
|
||||
/// Change the replication placement and rewrite the super block.
|
||||
pub fn set_replica_placement(&self, rp: ReplicaPlacement) -> Result<(), VolumeError> {
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let bytes = {
|
||||
let mut sb = self.super_block.write().unwrap();
|
||||
@@ -4621,6 +4717,7 @@ impl Volume {
|
||||
|
||||
/// Write a raw needle blob at a specific offset in the .dat file.
|
||||
pub fn write_needle_blob(&self, offset: i64, needle_blob: &[u8]) -> Result<(), VolumeError> {
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
if self.is_read_only() {
|
||||
return Err(VolumeError::ReadOnly(self.id));
|
||||
@@ -4652,6 +4749,7 @@ impl Volume {
|
||||
needle_blob: &[u8],
|
||||
size: Size,
|
||||
) -> Result<(), VolumeError> {
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
// nm.put on a read-only volume fails only after the blob is appended to .dat.
|
||||
if self.is_read_only() {
|
||||
@@ -4956,6 +5054,16 @@ impl Volume {
|
||||
// would stall every volume behind one slow client. The vacuum-commit
|
||||
// RPC uses the lease-holding path instead — it waits with no store
|
||||
// guard held, matching Go's blocking commit.
|
||||
// The sync lock must come before the lease and be non-blocking like
|
||||
// it: a durable write holds it across its fsync, and the commit must
|
||||
// not swap files over an unpublished write — nor stall the store
|
||||
// behind one.
|
||||
let Ok(_sync_guard) = self.data_file_sync_lock.try_lock() else {
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::WouldBlock,
|
||||
COMMIT_WAITS_FOR_READS,
|
||||
)));
|
||||
};
|
||||
let Some(_lease) = self.data_file_access_control.try_write_lock() else {
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::WouldBlock,
|
||||
@@ -4965,7 +5073,9 @@ impl Volume {
|
||||
self.commit_compact_held()
|
||||
}
|
||||
|
||||
/// `commit_compact` for callers already holding the write lease.
|
||||
/// `commit_compact` for callers already holding `data_file_sync_lock`
|
||||
/// and the write lease — the swap must not land between a durable
|
||||
/// write's append and its publish.
|
||||
pub(crate) fn commit_compact_held(&self) -> Result<(), VolumeError> {
|
||||
// A handle detached between lookup and lease must not swap compacted
|
||||
// files over the ones its remounted replacement now owns.
|
||||
@@ -5356,6 +5466,7 @@ impl Volume {
|
||||
/// Go's `Volume.Close`: the write lease excludes in-flight I/O — with a
|
||||
/// shared handle, `&mut self` no longer provides that exclusion.
|
||||
pub fn close(&self) {
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
self.closed.store(true, Ordering::Release);
|
||||
self.close_locked();
|
||||
@@ -5401,6 +5512,7 @@ impl Volume {
|
||||
if self.is_compacting() {
|
||||
return Err(self.compacting_error());
|
||||
}
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
|
||||
if self.dir_idx() == new_idx_dir {
|
||||
@@ -5463,6 +5575,7 @@ impl Volume {
|
||||
) -> Result<(), VolumeError> {
|
||||
// Go's Destroy holds dataFileAccessLock: file unlinking must exclude
|
||||
// in-flight I/O from a shared handle, not just borrow exclusivity.
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
// Either enabled check may pass: a volume with no live data qualifies
|
||||
// whether it reads empty or as all garbage. Byte counters, not counts:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -24,7 +24,7 @@ require (
|
||||
github.com/jcmturner/gofork v1.7.6 // indirect
|
||||
github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
|
||||
github.com/jcmturner/rpc/v2 v2.0.3 // indirect
|
||||
github.com/klauspost/compress v1.18.0 // indirect
|
||||
github.com/klauspost/compress v1.18.7 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.22 // indirect
|
||||
|
||||
@@ -38,8 +38,8 @@ github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh6
|
||||
github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs=
|
||||
github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY=
|
||||
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
|
||||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
||||
github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw=
|
||||
github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
|
||||
@@ -5,6 +5,6 @@ go 1.24.7
|
||||
require github.com/segmentio/kafka-go v0.4.49
|
||||
|
||||
require (
|
||||
github.com/klauspost/compress v1.15.9 // indirect
|
||||
github.com/klauspost/compress v1.18.7 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.15 // indirect
|
||||
)
|
||||
@@ -1,7 +1,7 @@
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/klauspost/compress v1.15.9 h1:wKRjX6JRtDdrE9qwa4b/Cip7ACOshUI4smpCQanqjSY=
|
||||
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
|
||||
github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw=
|
||||
github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/pierrec/lz4/v4 v4.1.15 h1:MO0/ucJhngq7299dKLwIMtgTfbkoSPF6AoMYDd8Q4q0=
|
||||
github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
module simple-consumer
|
||||
|
||||
go 1.21
|
||||
go 1.24
|
||||
|
||||
require github.com/segmentio/kafka-go v0.4.47
|
||||
|
||||
require (
|
||||
github.com/klauspost/compress v1.17.0 // indirect
|
||||
github.com/klauspost/compress v1.18.7 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.15 // indirect
|
||||
)
|
||||
@@ -2,8 +2,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
|
||||
github.com/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM=
|
||||
github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
|
||||
github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw=
|
||||
github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/pierrec/lz4/v4 v4.1.15 h1:MO0/ucJhngq7299dKLwIMtgTfbkoSPF6AoMYDd8Q4q0=
|
||||
github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
|
||||
@@ -120,13 +120,20 @@ func (store *IamGrpcStore) CreateAccessKey(ctx context.Context, username string,
|
||||
}
|
||||
|
||||
func (store *IamGrpcStore) DeleteAccessKey(ctx context.Context, username string, accessKey string) error {
|
||||
return store.withIamClient(ctx, func(ctx context.Context, client iam_pb.SeaweedIdentityAccessManagementClient) error {
|
||||
err := store.withIamClient(ctx, func(ctx context.Context, client iam_pb.SeaweedIdentityAccessManagementClient) error {
|
||||
_, err := client.DeleteAccessKey(ctx, &iam_pb.DeleteAccessKeyRequest{
|
||||
Username: username,
|
||||
AccessKey: accessKey,
|
||||
})
|
||||
return err
|
||||
})
|
||||
// The filer-side handler returns gRPC NotFound when the user or the key is
|
||||
// absent; translate back to the sentinel so callers can use
|
||||
// errors.Is(err, credential.ErrAccessKeyNotFound) uniformly across stores.
|
||||
if err != nil && status.Code(err) == codes.NotFound {
|
||||
return credential.ErrAccessKeyNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// AttachUserPolicy attaches a managed policy to a user by policy name
|
||||
|
||||
@@ -2,6 +2,7 @@ package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
@@ -106,3 +107,50 @@ func TestIamGrpcStore_AdminBearerToken(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestIamGrpcStore_DeleteAccessKeyNotFound pins the not-found translation:
|
||||
// the filer reports a missing user or key as gRPC NotFound, and the store must
|
||||
// surface it as credential.ErrAccessKeyNotFound so repeat deletes stay a no-op
|
||||
// for IAM dispatchers that tolerate the sentinel.
|
||||
func TestIamGrpcStore_DeleteAccessKeyNotFound(t *testing.T) {
|
||||
const goodKey = "iam-admin-itest-key"
|
||||
|
||||
cm, err := credential.NewCredentialManager(credential.StoreTypeMemory, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("NewCredentialManager: %v", err)
|
||||
}
|
||||
defer cm.Shutdown()
|
||||
|
||||
iamSrv := weed_server.NewIamGrpcServer(cm, security.SigningKey(goodKey))
|
||||
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
grpcSrv := grpc.NewServer()
|
||||
iam_pb.RegisterSeaweedIdentityAccessManagementServer(grpcSrv, iamSrv)
|
||||
go func() { _ = grpcSrv.Serve(lis) }()
|
||||
t.Cleanup(grpcSrv.Stop)
|
||||
|
||||
_, portStr, err := net.SplitHostPort(lis.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split listener addr: %v", err)
|
||||
}
|
||||
serverAddr := pb.ServerAddress(fmt.Sprintf("127.0.0.1:0.%s", portStr))
|
||||
|
||||
store := &IamGrpcStore{}
|
||||
store.SetFilerAddressFunc(func() pb.ServerAddress { return serverAddr }, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
store.SetAdminSigning(security.SigningKey(goodKey), 0)
|
||||
|
||||
ctx := context.Background()
|
||||
if err := store.CreateUser(ctx, &iam_pb.Identity{Name: "alice"}); err != nil {
|
||||
t.Fatalf("CreateUser: %v", err)
|
||||
}
|
||||
|
||||
if err := store.DeleteAccessKey(ctx, "alice", "AKIAMISSING0000000001"); !errors.Is(err, credential.ErrAccessKeyNotFound) {
|
||||
t.Fatalf("DeleteAccessKey with missing key: got %v, want ErrAccessKeyNotFound", err)
|
||||
}
|
||||
if err := store.DeleteAccessKey(ctx, "ghost", "AKIAMISSING0000000001"); !errors.Is(err, credential.ErrAccessKeyNotFound) {
|
||||
t.Fatalf("DeleteAccessKey with missing user: got %v, want ErrAccessKeyNotFound", err)
|
||||
}
|
||||
}
|
||||
@@ -142,6 +142,14 @@ func (store *MemoryStore) UpdateUser(ctx context.Context, username string, ident
|
||||
return credential.ErrUserNotFound
|
||||
}
|
||||
|
||||
if identity.Name != username {
|
||||
// Rename: the destination name must not already be taken, matching
|
||||
// RenameUser's collision check.
|
||||
if _, clash := store.users[identity.Name]; clash {
|
||||
return credential.ErrUserAlreadyExists
|
||||
}
|
||||
}
|
||||
|
||||
// Remove old access keys from index
|
||||
for _, cred := range existingUser.Credentials {
|
||||
delete(store.accessKeys, cred.AccessKey)
|
||||
@@ -156,11 +164,15 @@ func (store *MemoryStore) UpdateUser(ctx context.Context, username string, ident
|
||||
|
||||
// Deep copy to avoid mutation issues
|
||||
identityCopy := store.deepCopyIdentity(identity)
|
||||
store.users[username] = identityCopy
|
||||
if identityCopy.Name != username {
|
||||
// Rename: re-key the record, the way filer_etc does (delete old, save new).
|
||||
delete(store.users, username)
|
||||
}
|
||||
store.users[identityCopy.Name] = identityCopy
|
||||
|
||||
// Re-index access keys
|
||||
for _, cred := range identity.Credentials {
|
||||
store.accessKeys[cred.AccessKey] = username
|
||||
store.accessKeys[cred.AccessKey] = identityCopy.Name
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -378,3 +378,82 @@ func TestMemoryStoreServiceAccountByAccessKey(t *testing.T) {
|
||||
t.Errorf("Expected ErrAccessKeyNotFound after delete, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMemoryStoreUpdateUserRename: UpdateUser with an identity whose Name
|
||||
// differs from the key must re-key the record, the way filer_etc does
|
||||
// (delete old, save new). The IAM rename path relies on this.
|
||||
func TestMemoryStoreUpdateUserRename(t *testing.T) {
|
||||
store := &MemoryStore{}
|
||||
if err := store.Initialize(util.GetViper(), "credential."); err != nil {
|
||||
t.Fatalf("Failed to initialize store: %v", err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
err := store.CreateUser(ctx, &iam_pb.Identity{
|
||||
Name: "oldname",
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: "access123", SecretKey: "secret123"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create user: %v", err)
|
||||
}
|
||||
|
||||
err = store.UpdateUser(ctx, "oldname", &iam_pb.Identity{
|
||||
Name: "newname",
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: "access123", SecretKey: "secret123"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to rename user via UpdateUser: %v", err)
|
||||
}
|
||||
|
||||
if _, err := store.GetUser(ctx, "oldname"); err != credential.ErrUserNotFound {
|
||||
t.Fatalf("Expected ErrUserNotFound for old name, got %v", err)
|
||||
}
|
||||
renamed, err := store.GetUser(ctx, "newname")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get renamed user: %v", err)
|
||||
}
|
||||
if renamed.Name != "newname" {
|
||||
t.Errorf("Expected 'newname', got '%s'", renamed.Name)
|
||||
}
|
||||
byKey, err := store.GetUserByAccessKey(ctx, "access123")
|
||||
if err != nil {
|
||||
t.Fatalf("Access key must resolve to the renamed user: %v", err)
|
||||
}
|
||||
if byKey.Name != "newname" {
|
||||
t.Errorf("Expected access key owner 'newname', got '%s'", byKey.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMemoryStoreUpdateUserRenameCollision: a rename whose destination name is
|
||||
// taken must fail rather than overwrite the existing user.
|
||||
func TestMemoryStoreUpdateUserRenameCollision(t *testing.T) {
|
||||
store := &MemoryStore{}
|
||||
if err := store.Initialize(util.GetViper(), "credential."); err != nil {
|
||||
t.Fatalf("Failed to initialize store: %v", err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
if err := store.CreateUser(ctx, &iam_pb.Identity{Name: "alice"}); err != nil {
|
||||
t.Fatalf("Failed to create alice: %v", err)
|
||||
}
|
||||
if err := store.CreateUser(ctx, &iam_pb.Identity{
|
||||
Name: "bob",
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: "bobkey123", SecretKey: "secret123"}},
|
||||
}); err != nil {
|
||||
t.Fatalf("Failed to create bob: %v", err)
|
||||
}
|
||||
|
||||
err := store.UpdateUser(ctx, "alice", &iam_pb.Identity{Name: "bob"})
|
||||
if err != credential.ErrUserAlreadyExists {
|
||||
t.Fatalf("Expected ErrUserAlreadyExists, got %v", err)
|
||||
}
|
||||
|
||||
// Both users must be intact.
|
||||
if _, err := store.GetUser(ctx, "alice"); err != nil {
|
||||
t.Fatalf("alice must still exist: %v", err)
|
||||
}
|
||||
bob, err := store.GetUserByAccessKey(ctx, "bobkey123")
|
||||
if err != nil || bob.Name != "bob" {
|
||||
t.Fatalf("bob's access key must still resolve to bob: %v", err)
|
||||
}
|
||||
}
|
||||
+9
-7
@@ -104,13 +104,15 @@ var baseS3ActionMap = map[string]string{
|
||||
"DeleteObjectVersion": s3_constants.ACTION_WRITE,
|
||||
"GetObjectVersion": s3_constants.ACTION_READ,
|
||||
// Tagging operations
|
||||
"GetObjectTagging": s3_constants.ACTION_TAGGING,
|
||||
"GetObjectVersionTagging": s3_constants.ACTION_TAGGING,
|
||||
"PutObjectTagging": s3_constants.ACTION_TAGGING,
|
||||
"DeleteObjectTagging": s3_constants.ACTION_TAGGING,
|
||||
"GetBucketTagging": s3_constants.ACTION_TAGGING,
|
||||
"PutBucketTagging": s3_constants.ACTION_TAGGING,
|
||||
"DeleteBucketTagging": s3_constants.ACTION_TAGGING,
|
||||
"GetObjectTagging": s3_constants.ACTION_TAGGING,
|
||||
"GetObjectVersionTagging": s3_constants.ACTION_TAGGING,
|
||||
"PutObjectTagging": s3_constants.ACTION_TAGGING,
|
||||
"PutObjectVersionTagging": s3_constants.ACTION_TAGGING,
|
||||
"DeleteObjectTagging": s3_constants.ACTION_TAGGING,
|
||||
"DeleteObjectVersionTagging": s3_constants.ACTION_TAGGING,
|
||||
"GetBucketTagging": s3_constants.ACTION_TAGGING,
|
||||
"PutBucketTagging": s3_constants.ACTION_TAGGING,
|
||||
"DeleteBucketTagging": s3_constants.ACTION_TAGGING,
|
||||
// ACL operations
|
||||
"PutObjectAcl": s3_constants.ACTION_WRITE_ACP,
|
||||
"GetObjectAcl": s3_constants.ACTION_READ_ACP,
|
||||
|
||||
@@ -4,6 +4,7 @@ package iamapi
|
||||
// Common IAM types and helpers are imported from the shared weed/iam package.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
"sync"
|
||||
|
||||
"github.com/aws/aws-sdk-go/service/iam"
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
iamlib "github.com/seaweedfs/seaweedfs/weed/iam"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -1312,6 +1314,115 @@ func (iama *IamApiServer) handleImplicitUsername(r *http.Request, values url.Val
|
||||
values.Set("UserName", identity.Name)
|
||||
}
|
||||
|
||||
// targetedCredentialManager returns the credential manager through which a change to the named
|
||||
// identity is written on its own instead of via SaveConfiguration, or nil when this server has
|
||||
// none, or the identity is static: static identities live outside the store and keep the
|
||||
// full-save path.
|
||||
func (iama *IamApiServer) targetedCredentialManager(userName string) *credential.CredentialManager {
|
||||
if iama.iam == nil {
|
||||
return nil
|
||||
}
|
||||
cm := iama.iam.GetCredentialManager()
|
||||
if cm == nil || cm.IsStaticIdentity(userName) {
|
||||
return nil
|
||||
}
|
||||
return cm
|
||||
}
|
||||
|
||||
// findIdentityByName returns the identity named userName in s3cfg, or nil.
|
||||
func findIdentityByName(s3cfg *iam_pb.S3ApiConfiguration, userName string) *iam_pb.Identity {
|
||||
for _, ident := range s3cfg.Identities {
|
||||
if ident.Name == userName {
|
||||
return ident
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// groupsWithMember returns the groups in s3cfg that list userName as a member. Taken before a
|
||||
// handler renames or removes the user, it names the group records that handler will change.
|
||||
func groupsWithMember(s3cfg *iam_pb.S3ApiConfiguration, userName string) []*iam_pb.Group {
|
||||
var groups []*iam_pb.Group
|
||||
for _, g := range s3cfg.Groups {
|
||||
for _, m := range g.Members {
|
||||
if m == userName {
|
||||
groups = append(groups, g)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
// serviceAccountsOf returns the service accounts in s3cfg whose parent is userName.
|
||||
func serviceAccountsOf(s3cfg *iam_pb.S3ApiConfiguration, userName string) []*iam_pb.ServiceAccount {
|
||||
var accounts []*iam_pb.ServiceAccount
|
||||
for _, sa := range s3cfg.ServiceAccounts {
|
||||
if sa.ParentUser == userName {
|
||||
accounts = append(accounts, sa)
|
||||
}
|
||||
}
|
||||
return accounts
|
||||
}
|
||||
|
||||
// persistIdentity writes the one identity a handler changed in s3cfg through the credential
|
||||
// manager. The store writes that identity's record and propagates it alone; the other
|
||||
// identities are not rewritten.
|
||||
func persistIdentity(ctx context.Context, cm *credential.CredentialManager, s3cfg *iam_pb.S3ApiConfiguration, userName string) error {
|
||||
ident := findIdentityByName(s3cfg, userName)
|
||||
if ident == nil {
|
||||
return credential.ErrUserNotFound
|
||||
}
|
||||
return cm.UpdateUser(ctx, userName, ident)
|
||||
}
|
||||
|
||||
// persistRenamedIdentity writes a user renamed from oldName to newName by UpdateUser through the
|
||||
// credential manager: the identity, the groups that listed the old name and the service accounts
|
||||
// it parented. UpdateUser under the old name moves the record in stores that treat a changed Name
|
||||
// as a rename (filer_etc, memory), and the propagating store propagates the new identity and the
|
||||
// old name's removal; UpdateUser already moved the inline policies through PutPolicies. A store
|
||||
// that did not move the record still holds the user under the old name; the caller is told so
|
||||
// (false) and keeps the full save, which is what renames such a store today.
|
||||
func persistRenamedIdentity(ctx context.Context, cm *credential.CredentialManager, s3cfg *iam_pb.S3ApiConfiguration, oldName, newName string, groups []*iam_pb.Group, accounts []*iam_pb.ServiceAccount) (bool, error) {
|
||||
ident := findIdentityByName(s3cfg, newName)
|
||||
if ident == nil {
|
||||
return false, credential.ErrUserNotFound
|
||||
}
|
||||
if err := cm.UpdateUser(ctx, oldName, ident); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err := cm.GetUser(ctx, newName); err != nil {
|
||||
return false, nil
|
||||
}
|
||||
for _, g := range groups {
|
||||
if err := cm.UpdateGroup(ctx, g); err != nil {
|
||||
return false, fmt.Errorf("update group %s: %w", g.Name, err)
|
||||
}
|
||||
}
|
||||
for _, sa := range accounts {
|
||||
if err := cm.UpdateServiceAccount(ctx, sa.Id, sa); err != nil {
|
||||
return false, fmt.Errorf("update service account %s: %w", sa.Id, err)
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// deleteIdentity removes a user deleted by DeleteUser through the credential manager: its record
|
||||
// (the store propagates the one removal) and the groups that listed it, whose membership
|
||||
// DeleteUser already changed in s3cfg. DeleteUser already removed the inline policies through
|
||||
// PutPolicies.
|
||||
func deleteIdentity(ctx context.Context, cm *credential.CredentialManager, userName string, groups []*iam_pb.Group) error {
|
||||
if err := cm.DeleteUser(ctx, userName); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, g := range groups {
|
||||
if err := cm.UpdateGroup(ctx, g); err != nil {
|
||||
return fmt.Errorf("update group %s: %w", g.Name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
|
||||
// Lock to prevent concurrent read-modify-write race conditions
|
||||
policyLock.Lock()
|
||||
@@ -1333,6 +1444,9 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
|
||||
glog.V(4).Infof("DoActions: %+v", iamlib.RedactSensitiveFormValues(values))
|
||||
var response iamlib.RequestIDSetter
|
||||
changed := true
|
||||
// persisted is set by the actions that wrote one identity through the credential manager
|
||||
// instead of SaveConfiguration; the in-memory identity maps are reloaded after them too.
|
||||
persisted := false
|
||||
switch r.Form.Get("Action") {
|
||||
case "ListUsers":
|
||||
response = iama.ListUsers(s3cfg, values)
|
||||
@@ -1365,40 +1479,107 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
changed = false
|
||||
case "UpdateUser":
|
||||
userName, newUserName := values.Get("UserName"), values.Get("NewUserName")
|
||||
// Taken before the rename: the records the handler changes besides the identity.
|
||||
groups := groupsWithMember(s3cfg, userName)
|
||||
accounts := serviceAccountsOf(s3cfg, userName)
|
||||
var err *IamError
|
||||
response, err = iama.UpdateUser(s3cfg, values)
|
||||
if err != nil {
|
||||
writeIamErrorResponse(w, r, reqID, err)
|
||||
return
|
||||
}
|
||||
// Write the renamed identity, its groups and service accounts through the credential
|
||||
// manager instead of rewriting every identity via SaveConfiguration. A request that
|
||||
// renames nothing changed nothing, so there is nothing to write either way.
|
||||
if cm := iama.targetedCredentialManager(userName); cm != nil {
|
||||
renamed := true
|
||||
if newUserName != "" && newUserName != userName {
|
||||
var err error
|
||||
renamed, err = persistRenamedIdentity(r.Context(), cm, s3cfg, userName, newUserName, groups, accounts)
|
||||
if err != nil {
|
||||
writeIamErrorResponse(w, r, reqID, &IamError{Code: s3api.CredentialErrToIamErrCode(err), Error: err})
|
||||
return
|
||||
}
|
||||
}
|
||||
changed, persisted = !renamed, renamed
|
||||
}
|
||||
case "DeleteUser":
|
||||
userName := values.Get("UserName")
|
||||
groups := groupsWithMember(s3cfg, userName)
|
||||
var err *IamError
|
||||
response, err = iama.DeleteUser(s3cfg, userName)
|
||||
if err != nil {
|
||||
writeIamErrorResponse(w, r, reqID, err)
|
||||
return
|
||||
}
|
||||
// Targeted delete: one record removed and one removal propagated, plus the groups whose
|
||||
// membership changed, instead of rewriting every remaining identity.
|
||||
if cm := iama.targetedCredentialManager(userName); cm != nil {
|
||||
if err := deleteIdentity(r.Context(), cm, userName, groups); err != nil {
|
||||
writeIamErrorResponse(w, r, reqID, &IamError{Code: s3api.CredentialErrToIamErrCode(err), Error: err})
|
||||
return
|
||||
}
|
||||
changed, persisted = false, true
|
||||
}
|
||||
case "CreateAccessKey":
|
||||
iama.handleImplicitUsername(r, values)
|
||||
var err *IamError
|
||||
response, err = iama.CreateAccessKey(s3cfg, values)
|
||||
userName := values.Get("UserName")
|
||||
resp, err := iama.CreateAccessKey(s3cfg, values)
|
||||
if err != nil {
|
||||
glog.Errorf("CreateAccessKey: %+v", err.Error)
|
||||
writeIamErrorResponse(w, r, reqID, err)
|
||||
return
|
||||
}
|
||||
response = resp
|
||||
// Targeted write: credentialManager.CreateAccessKey adds the key to the one identity and
|
||||
// propagates that identity alone. The handler creates the identity for a user it does
|
||||
// not know; that case still needs the full save.
|
||||
if cm := iama.targetedCredentialManager(userName); cm != nil {
|
||||
if _, known := cm.GetUser(r.Context(), userName); known == nil {
|
||||
cred := &iam_pb.Credential{
|
||||
AccessKey: *resp.CreateAccessKeyResult.AccessKey.AccessKeyId,
|
||||
SecretKey: *resp.CreateAccessKeyResult.AccessKey.SecretAccessKey,
|
||||
Status: accessKeyStatusActive,
|
||||
}
|
||||
if err := cm.CreateAccessKey(r.Context(), userName, cred); err != nil {
|
||||
writeIamErrorResponse(w, r, reqID, &IamError{Code: s3api.CredentialErrToIamErrCode(err), Error: err})
|
||||
return
|
||||
}
|
||||
changed, persisted = false, true
|
||||
}
|
||||
}
|
||||
case "DeleteAccessKey":
|
||||
iama.handleImplicitUsername(r, values)
|
||||
userName, accessKeyId := values.Get("UserName"), values.Get("AccessKeyId")
|
||||
response = iama.DeleteAccessKey(s3cfg, values)
|
||||
// Targeted write: credentialManager.DeleteAccessKey removes the key from the one identity
|
||||
// and propagates that identity alone. The handler answers 200 for a key or user it does
|
||||
// not know, so a not-found from the store is the same no-op it always was.
|
||||
if cm := iama.targetedCredentialManager(userName); cm != nil {
|
||||
err := cm.DeleteAccessKey(r.Context(), userName, accessKeyId)
|
||||
if err != nil && !errors.Is(err, credential.ErrAccessKeyNotFound) && !errors.Is(err, credential.ErrUserNotFound) {
|
||||
writeIamErrorResponse(w, r, reqID, &IamError{Code: s3api.CredentialErrToIamErrCode(err), Error: err})
|
||||
return
|
||||
}
|
||||
changed, persisted = false, true
|
||||
}
|
||||
case "UpdateAccessKey":
|
||||
iama.handleImplicitUsername(r, values)
|
||||
userName := values.Get("UserName")
|
||||
var err *IamError
|
||||
response, err = iama.UpdateAccessKey(s3cfg, values)
|
||||
if err != nil {
|
||||
writeIamErrorResponse(w, r, reqID, err)
|
||||
return
|
||||
}
|
||||
if cm := iama.targetedCredentialManager(userName); cm != nil {
|
||||
if err := persistIdentity(r.Context(), cm, s3cfg, userName); err != nil {
|
||||
writeIamErrorResponse(w, r, reqID, &IamError{Code: s3api.CredentialErrToIamErrCode(err), Error: err})
|
||||
return
|
||||
}
|
||||
changed, persisted = false, true
|
||||
}
|
||||
case "CreatePolicy":
|
||||
var err *IamError
|
||||
response, err = iama.CreatePolicy(s3cfg, values)
|
||||
@@ -1410,6 +1591,7 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
|
||||
// The `changed` flag is false because this does not modify the main s3cfg.Identities configuration.
|
||||
changed = false
|
||||
case "PutUserPolicy":
|
||||
userName := values.Get("UserName")
|
||||
var err *IamError
|
||||
response, err = iama.PutUserPolicy(s3cfg, values)
|
||||
if err != nil {
|
||||
@@ -1417,6 +1599,15 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
|
||||
writeIamErrorResponse(w, r, reqID, err)
|
||||
return
|
||||
}
|
||||
// The policy document is already stored through PutPolicies; what remains is the
|
||||
// identity's recomputed Actions, written and propagated for that identity alone.
|
||||
if cm := iama.targetedCredentialManager(userName); cm != nil {
|
||||
if err := persistIdentity(r.Context(), cm, s3cfg, userName); err != nil {
|
||||
writeIamErrorResponse(w, r, reqID, &IamError{Code: s3api.CredentialErrToIamErrCode(err), Error: err})
|
||||
return
|
||||
}
|
||||
changed, persisted = false, true
|
||||
}
|
||||
case "GetUserPolicy":
|
||||
var err *IamError
|
||||
response, err = iama.GetUserPolicy(s3cfg, values)
|
||||
@@ -1426,12 +1617,20 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
changed = false
|
||||
case "DeleteUserPolicy":
|
||||
userName := values.Get("UserName")
|
||||
var err *IamError
|
||||
response, err = iama.DeleteUserPolicy(s3cfg, values)
|
||||
if err != nil {
|
||||
writeIamErrorResponse(w, r, reqID, err)
|
||||
return
|
||||
}
|
||||
if cm := iama.targetedCredentialManager(userName); cm != nil {
|
||||
if err := persistIdentity(r.Context(), cm, s3cfg, userName); err != nil {
|
||||
writeIamErrorResponse(w, r, reqID, &IamError{Code: s3api.CredentialErrToIamErrCode(err), Error: err})
|
||||
return
|
||||
}
|
||||
changed, persisted = false, true
|
||||
}
|
||||
case "ListUserPolicies":
|
||||
iama.handleImplicitUsername(r, values)
|
||||
var err *IamError
|
||||
@@ -1642,6 +1841,8 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
|
||||
writeIamErrorResponse(w, r, reqID, &iamError)
|
||||
return
|
||||
}
|
||||
}
|
||||
if changed || persisted {
|
||||
// Reload in-memory identity maps so subsequent LookupByAccessKey calls
|
||||
// can see newly created or deleted keys immediately
|
||||
if iama.iam != nil {
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
package iamapi
|
||||
|
||||
// Targeted-write regression tests: single-identity IAM actions must write only
|
||||
// the identity they changed through the credential manager, not every identity
|
||||
// via PutS3ApiConfiguration/SaveConfiguration.
|
||||
// See https://github.com/seaweedfs/seaweedfs/issues/11865.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/iam"
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential/memory"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// targetedRecordingStore wraps a memory store and counts the write methods
|
||||
// the dispatcher used, so a test can assert the single-identity path was
|
||||
// taken. It embeds the concrete store (rather than the CredentialStore
|
||||
// interface) so optional interfaces like InlinePolicyStore stay visible
|
||||
// through the wrapper.
|
||||
type targetedRecordingStore struct {
|
||||
*memory.MemoryStore
|
||||
saves int
|
||||
createAccessKeys int
|
||||
deleteAccessKeys int
|
||||
updateUsers int
|
||||
deleteUsers int
|
||||
updateGroups int
|
||||
}
|
||||
|
||||
func (r *targetedRecordingStore) SaveConfiguration(ctx context.Context, config *iam_pb.S3ApiConfiguration) error {
|
||||
r.saves++
|
||||
return r.MemoryStore.SaveConfiguration(ctx, config)
|
||||
}
|
||||
|
||||
func (r *targetedRecordingStore) CreateAccessKey(ctx context.Context, username string, cred *iam_pb.Credential) error {
|
||||
r.createAccessKeys++
|
||||
return r.MemoryStore.CreateAccessKey(ctx, username, cred)
|
||||
}
|
||||
|
||||
func (r *targetedRecordingStore) DeleteAccessKey(ctx context.Context, username string, accessKey string) error {
|
||||
r.deleteAccessKeys++
|
||||
return r.MemoryStore.DeleteAccessKey(ctx, username, accessKey)
|
||||
}
|
||||
|
||||
func (r *targetedRecordingStore) UpdateUser(ctx context.Context, username string, identity *iam_pb.Identity) error {
|
||||
r.updateUsers++
|
||||
return r.MemoryStore.UpdateUser(ctx, username, identity)
|
||||
}
|
||||
|
||||
func (r *targetedRecordingStore) DeleteUser(ctx context.Context, username string) error {
|
||||
r.deleteUsers++
|
||||
return r.MemoryStore.DeleteUser(ctx, username)
|
||||
}
|
||||
|
||||
func (r *targetedRecordingStore) UpdateGroup(ctx context.Context, group *iam_pb.Group) error {
|
||||
r.updateGroups++
|
||||
return r.MemoryStore.UpdateGroup(ctx, group)
|
||||
}
|
||||
|
||||
func targetedIamApiServer() (*IamApiServer, *credential.CredentialManager, *countingConfigSaver, *targetedRecordingStore) {
|
||||
srv, cm, counter := iamApiServerWithCredentialManager()
|
||||
rec := &targetedRecordingStore{MemoryStore: cm.Store.(*memory.MemoryStore)}
|
||||
cm.Store = rec
|
||||
return srv, cm, counter, rec
|
||||
}
|
||||
|
||||
const targetedTestPolicy = `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::bench/*"]}]
|
||||
}`
|
||||
|
||||
func TestIamApiCreateAccessKeyTargeted(t *testing.T) {
|
||||
srv, cm, counter, rec := targetedIamApiServer()
|
||||
ctx := context.Background()
|
||||
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "alice"}))
|
||||
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "bob"}))
|
||||
|
||||
req, _ := iam.New(session.New()).CreateAccessKeyRequest(&iam.CreateAccessKeyInput{UserName: aws.String("alice")})
|
||||
_ = req.Build()
|
||||
out := CreateAccessKeyResponse{}
|
||||
resp, err := executeRequestWith(srv, req.HTTPRequest, &out)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, resp.Code)
|
||||
|
||||
assert.Equal(t, 0, counter.putCalled, "CreateAccessKey must not PutS3ApiConfiguration")
|
||||
assert.Equal(t, 0, rec.saves)
|
||||
assert.Equal(t, 1, rec.createAccessKeys)
|
||||
|
||||
ident, err := cm.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, ident.Credentials, 1)
|
||||
assert.Equal(t, *out.CreateAccessKeyResult.AccessKey.AccessKeyId, ident.Credentials[0].AccessKey)
|
||||
}
|
||||
|
||||
// CreateAccessKey for a user the store does not know still needs the full save:
|
||||
// the handler creates the identity in the config, so there is no existing
|
||||
// record to write a key into.
|
||||
func TestIamApiCreateAccessKeyUnknownUserFallsBack(t *testing.T) {
|
||||
srv, cm, counter, _ := targetedIamApiServer()
|
||||
ctx := context.Background()
|
||||
|
||||
req, _ := iam.New(session.New()).CreateAccessKeyRequest(&iam.CreateAccessKeyInput{UserName: aws.String("ghost")})
|
||||
_ = req.Build()
|
||||
out := CreateAccessKeyResponse{}
|
||||
resp, err := executeRequestWith(srv, req.HTTPRequest, &out)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, resp.Code)
|
||||
|
||||
assert.Equal(t, 1, counter.putCalled)
|
||||
ident, err := cm.GetUser(ctx, "ghost")
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ident.Credentials, 1)
|
||||
}
|
||||
|
||||
func TestIamApiDeleteAccessKeyTargeted(t *testing.T) {
|
||||
srv, cm, counter, rec := targetedIamApiServer()
|
||||
ctx := context.Background()
|
||||
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{
|
||||
Name: "alice",
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: "AKIATESTFAKEKEY00001", SecretKey: "testsecretfake"}},
|
||||
}))
|
||||
|
||||
req, _ := iam.New(session.New()).DeleteAccessKeyRequest(&iam.DeleteAccessKeyInput{
|
||||
UserName: aws.String("alice"),
|
||||
AccessKeyId: aws.String("AKIATESTFAKEKEY00001"),
|
||||
})
|
||||
_ = req.Build()
|
||||
out := DeleteAccessKeyResponse{}
|
||||
resp, err := executeRequestWith(srv, req.HTTPRequest, &out)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, resp.Code)
|
||||
|
||||
assert.Equal(t, 0, counter.putCalled, "DeleteAccessKey must not PutS3ApiConfiguration")
|
||||
assert.Equal(t, 1, rec.deleteAccessKeys)
|
||||
|
||||
ident, err := cm.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, ident.Credentials)
|
||||
|
||||
// Deleting a key that does not exist still answers 200 and stays targeted.
|
||||
req, _ = iam.New(session.New()).DeleteAccessKeyRequest(&iam.DeleteAccessKeyInput{
|
||||
UserName: aws.String("alice"),
|
||||
AccessKeyId: aws.String("AKIATESTFAKEKEY99999"),
|
||||
})
|
||||
_ = req.Build()
|
||||
resp, err = executeRequestWith(srv, req.HTTPRequest, &out)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, resp.Code)
|
||||
assert.Equal(t, 0, counter.putCalled)
|
||||
}
|
||||
|
||||
func TestIamApiUpdateAccessKeyTargeted(t *testing.T) {
|
||||
srv, cm, counter, rec := targetedIamApiServer()
|
||||
ctx := context.Background()
|
||||
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{
|
||||
Name: "alice",
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: "AKIATESTFAKEKEY00001", SecretKey: "testsecretfake", Status: "Active"}},
|
||||
}))
|
||||
|
||||
req, _ := iam.New(session.New()).UpdateAccessKeyRequest(&iam.UpdateAccessKeyInput{
|
||||
UserName: aws.String("alice"),
|
||||
AccessKeyId: aws.String("AKIATESTFAKEKEY00001"),
|
||||
Status: aws.String(iam.StatusTypeInactive),
|
||||
})
|
||||
_ = req.Build()
|
||||
out := UpdateAccessKeyResponse{}
|
||||
resp, err := executeRequestWith(srv, req.HTTPRequest, &out)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, resp.Code)
|
||||
|
||||
assert.Equal(t, 0, counter.putCalled, "UpdateAccessKey must not PutS3ApiConfiguration")
|
||||
assert.Equal(t, 1, rec.updateUsers)
|
||||
|
||||
ident, err := cm.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, ident.Credentials, 1)
|
||||
assert.Equal(t, iam.StatusTypeInactive, ident.Credentials[0].Status)
|
||||
}
|
||||
|
||||
func TestIamApiPutUserPolicyTargeted(t *testing.T) {
|
||||
srv, cm, counter, rec := targetedIamApiServer()
|
||||
ctx := context.Background()
|
||||
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "alice"}))
|
||||
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "bob"}))
|
||||
|
||||
req, _ := iam.New(session.New()).PutUserPolicyRequest(&iam.PutUserPolicyInput{
|
||||
UserName: aws.String("alice"),
|
||||
PolicyName: aws.String("read-bench"),
|
||||
PolicyDocument: aws.String(targetedTestPolicy),
|
||||
})
|
||||
_ = req.Build()
|
||||
out := PutUserPolicyResponse{}
|
||||
resp, err := executeRequestWith(srv, req.HTTPRequest, &out)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, resp.Code)
|
||||
|
||||
assert.Equal(t, 0, counter.putCalled, "PutUserPolicy must not PutS3ApiConfiguration")
|
||||
assert.Equal(t, 0, rec.saves)
|
||||
assert.Equal(t, 1, rec.updateUsers)
|
||||
|
||||
ident, err := cm.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.NotEmpty(t, ident.Actions, "recomputed Actions must be persisted for the one identity")
|
||||
}
|
||||
|
||||
func TestIamApiDeleteUserPolicyTargeted(t *testing.T) {
|
||||
srv, cm, counter, rec := targetedIamApiServer()
|
||||
ctx := context.Background()
|
||||
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "alice"}))
|
||||
|
||||
putReq, _ := iam.New(session.New()).PutUserPolicyRequest(&iam.PutUserPolicyInput{
|
||||
UserName: aws.String("alice"),
|
||||
PolicyName: aws.String("read-bench"),
|
||||
PolicyDocument: aws.String(targetedTestPolicy),
|
||||
})
|
||||
_ = putReq.Build()
|
||||
putOut := PutUserPolicyResponse{}
|
||||
resp, err := executeRequestWith(srv, putReq.HTTPRequest, &putOut)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, resp.Code)
|
||||
|
||||
delReq, _ := iam.New(session.New()).DeleteUserPolicyRequest(&iam.DeleteUserPolicyInput{
|
||||
UserName: aws.String("alice"),
|
||||
PolicyName: aws.String("read-bench"),
|
||||
})
|
||||
_ = delReq.Build()
|
||||
delOut := DeleteUserPolicyResponse{}
|
||||
resp, err = executeRequestWith(srv, delReq.HTTPRequest, &delOut)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, resp.Code)
|
||||
|
||||
assert.Equal(t, 0, counter.putCalled, "DeleteUserPolicy must not PutS3ApiConfiguration")
|
||||
assert.Equal(t, 2, rec.updateUsers)
|
||||
|
||||
policies := Policies{}
|
||||
require.NoError(t, srv.s3ApiConfig.GetPolicies(&policies))
|
||||
assert.Empty(t, policies.InlinePolicies["alice"])
|
||||
}
|
||||
|
||||
func TestIamApiUpdateUserRenameTargeted(t *testing.T) {
|
||||
srv, cm, counter, _ := targetedIamApiServer()
|
||||
ctx := context.Background()
|
||||
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "alice"}))
|
||||
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "bob"}))
|
||||
require.NoError(t, cm.CreateGroup(ctx, &iam_pb.Group{Name: "devs", Members: []string{"alice", "bob"}}))
|
||||
|
||||
req, _ := iam.New(session.New()).UpdateUserRequest(&iam.UpdateUserInput{
|
||||
UserName: aws.String("alice"),
|
||||
NewUserName: aws.String("alice-renamed"),
|
||||
})
|
||||
_ = req.Build()
|
||||
out := UpdateUserResponse{}
|
||||
resp, err := executeRequestWith(srv, req.HTTPRequest, &out)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, resp.Code)
|
||||
|
||||
assert.Equal(t, 0, counter.putCalled, "UpdateUser rename must not PutS3ApiConfiguration")
|
||||
|
||||
_, err = cm.GetUser(ctx, "alice")
|
||||
require.ErrorIs(t, err, credential.ErrUserNotFound)
|
||||
_, err = cm.GetUser(ctx, "alice-renamed")
|
||||
require.NoError(t, err)
|
||||
|
||||
g, err := cm.GetGroup(ctx, "devs")
|
||||
require.NoError(t, err)
|
||||
assert.ElementsMatch(t, []string{"alice-renamed", "bob"}, g.Members)
|
||||
}
|
||||
|
||||
func TestIamApiDeleteUserTargeted(t *testing.T) {
|
||||
srv, cm, counter, rec := targetedIamApiServer()
|
||||
ctx := context.Background()
|
||||
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "alice"}))
|
||||
require.NoError(t, cm.CreateUser(ctx, &iam_pb.Identity{Name: "bob"}))
|
||||
require.NoError(t, cm.CreateGroup(ctx, &iam_pb.Group{Name: "devs", Members: []string{"alice", "bob"}}))
|
||||
|
||||
req, _ := iam.New(session.New()).DeleteUserRequest(&iam.DeleteUserInput{UserName: aws.String("alice")})
|
||||
_ = req.Build()
|
||||
out := DeleteUserResponse{}
|
||||
resp, err := executeRequestWith(srv, req.HTTPRequest, &out)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, resp.Code)
|
||||
|
||||
assert.Equal(t, 0, counter.putCalled, "DeleteUser must not PutS3ApiConfiguration")
|
||||
assert.Equal(t, 1, rec.deleteUsers)
|
||||
assert.Equal(t, 1, rec.updateGroups)
|
||||
|
||||
_, err = cm.GetUser(ctx, "alice")
|
||||
require.ErrorIs(t, err, credential.ErrUserNotFound)
|
||||
g, err := cm.GetGroup(ctx, "devs")
|
||||
require.NoError(t, err)
|
||||
assert.ElementsMatch(t, []string{"bob"}, g.Members)
|
||||
_, err = cm.GetUser(ctx, "bob")
|
||||
require.NoError(t, err, "other identities must be untouched")
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/jinzhu/copier"
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential/memory"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
@@ -607,6 +608,7 @@ func iamApiServerWithCredentialManager() (*IamApiServer, *credential.CredentialM
|
||||
type countingConfigSaver struct {
|
||||
cm *credential.CredentialManager
|
||||
putCalled int
|
||||
policies Policies
|
||||
}
|
||||
|
||||
func (c *countingConfigSaver) GetS3ApiConfiguration(s3cfg *iam_pb.S3ApiConfiguration) error {
|
||||
@@ -616,6 +618,8 @@ func (c *countingConfigSaver) GetS3ApiConfiguration(s3cfg *iam_pb.S3ApiConfigura
|
||||
}
|
||||
s3cfg.Identities = config.Identities
|
||||
s3cfg.Policies = config.Policies
|
||||
s3cfg.Groups = config.Groups
|
||||
s3cfg.ServiceAccounts = config.ServiceAccounts
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -625,10 +629,15 @@ func (c *countingConfigSaver) PutS3ApiConfiguration(s3cfg *iam_pb.S3ApiConfigura
|
||||
}
|
||||
|
||||
func (c *countingConfigSaver) GetPolicies(policies *Policies) error {
|
||||
*policies = c.policies
|
||||
if c.policies.Policies == nil && c.policies.InlinePolicies == nil {
|
||||
return filer_pb.ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *countingConfigSaver) PutPolicies(policies *Policies) error {
|
||||
c.policies = *policies
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -244,7 +244,31 @@ func Mkdir(ctx context.Context, filerClient FilerClient, parentDirectoryPath str
|
||||
})
|
||||
}
|
||||
|
||||
// MkdirExclusive is Mkdir that never replaces an entry already at the path:
|
||||
// the create is O_EXCL and a taken name answers ErrEntryAlreadyExists. The
|
||||
// taken name leaves the callback as a result, not an error: failover counts a
|
||||
// callback error against the filer and retries on the next one.
|
||||
func MkdirExclusive(ctx context.Context, filerClient FilerClient, parentDirectoryPath string, dirName string, fn func(entry *Entry)) error {
|
||||
var taken error
|
||||
err := filerClient.WithFilerClient(false, func(client SeaweedFilerClient) error {
|
||||
err := doMkdir(ctx, client, parentDirectoryPath, dirName, true, fn)
|
||||
if errors.Is(err, ErrEntryAlreadyExists) {
|
||||
taken = err
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err == nil {
|
||||
err = taken
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func DoMkdir(ctx context.Context, client SeaweedFilerClient, parentDirectoryPath string, dirName string, fn func(entry *Entry)) error {
|
||||
return doMkdir(ctx, client, parentDirectoryPath, dirName, false, fn)
|
||||
}
|
||||
|
||||
func doMkdir(ctx context.Context, client SeaweedFilerClient, parentDirectoryPath string, dirName string, exclusive bool, fn func(entry *Entry)) error {
|
||||
entry := &Entry{
|
||||
Name: dirName,
|
||||
IsDirectory: true,
|
||||
@@ -264,6 +288,7 @@ func DoMkdir(ctx context.Context, client SeaweedFilerClient, parentDirectoryPath
|
||||
request := &CreateEntryRequest{
|
||||
Directory: parentDirectoryPath,
|
||||
Entry: entry,
|
||||
OExcl: exclusive,
|
||||
}
|
||||
|
||||
glog.V(1).InfofCtx(ctx, "mkdir: %v", request)
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"time"
|
||||
|
||||
"cloud.google.com/go/storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
|
||||
@@ -348,6 +349,16 @@ func (gcs *gcsRemoteStorageClient) WriteFile(loc *remote_pb.RemoteStorageLocatio
|
||||
wc.ContentType = entry.Attributes.Mime
|
||||
}
|
||||
wc.ContentEncoding = remote_storage.EntryContentEncoding(entry)
|
||||
// A Writer reserves a buffer of ChunkSize bytes (16 MiB by default) so a
|
||||
// failed request can be retried. An object below that size takes a buffer
|
||||
// of its own size plus one 256 KiB unit, the SDK's granularity: a burst of
|
||||
// small uploads in flight does not hold 16 MiB each, every upload keeps
|
||||
// its retry buffer, and the object stays below ChunkSize so it goes in one
|
||||
// request rather than a resumable session. The size counts the chunks,
|
||||
// not only the attribute, which some write paths leave at zero.
|
||||
if size := filer.FileSize(entry); size < uint64(googleapi.DefaultUploadChunkSize) {
|
||||
wc.ChunkSize = int((size/googleapi.MinUploadChunkSize + 1) * googleapi.MinUploadChunkSize)
|
||||
}
|
||||
if _, err = io.Copy(wc, reader); err != nil {
|
||||
return nil, fmt.Errorf("upload to gcs %s/%s%s: %v", loc.Name, loc.Bucket, loc.Path, err)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
@@ -22,6 +23,23 @@ func (s3a *S3ApiServer) mkdir(parentDirectoryPath string, dirName string, fn fun
|
||||
|
||||
}
|
||||
|
||||
// mkdirExclusive never replaces an entry already at the path: PutBucket uses
|
||||
// it so a plain bucket cannot replace a table bucket created in its
|
||||
// check-to-create window.
|
||||
func (s3a *S3ApiServer) mkdirExclusive(parentDirectoryPath string, dirName string, fn func(entry *filer_pb.Entry)) error {
|
||||
|
||||
return filer_pb.MkdirExclusive(context.Background(), s3a, parentDirectoryPath, dirName, fn)
|
||||
|
||||
}
|
||||
|
||||
// concurrentEntryIsForeign: after PutBucket's exclusive mkdir met an entry,
|
||||
// whether that entry must be answered BucketAlreadyExists without looking at
|
||||
// its owner: a table bucket (it carries no S3 owner and must never read as
|
||||
// "owned by you"), or an entry that could not be read.
|
||||
func concurrentEntryIsForeign(entry *filer_pb.Entry, err error) bool {
|
||||
return err != nil || entry == nil || s3tables.IsTableBucketEntry(entry)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) mkFile(parentDirectoryPath string, fileName string, chunks []*filer_pb.FileChunk, fn func(entry *filer_pb.Entry)) error {
|
||||
|
||||
err := filer_pb.MkFile(context.Background(), s3a, parentDirectoryPath, fileName, chunks, fn)
|
||||
|
||||
@@ -182,20 +182,33 @@ func resolveFromQueryParameters(query url.Values, method string, hasObject bool)
|
||||
}
|
||||
}
|
||||
|
||||
// Tagging operations
|
||||
// Tagging operations. The routes match ?tagging whenever the key is
|
||||
// present (gorilla/mux does not compare the value), so any value counts.
|
||||
// A versionId retargets the request at a specific version, so the
|
||||
// version-tagging action applies, not the current-object one.
|
||||
if query.Has("tagging") {
|
||||
versioned := hasObject && query.Get("versionId") != ""
|
||||
switch method {
|
||||
case http.MethodGet:
|
||||
if versioned {
|
||||
return s3_constants.S3_ACTION_GET_OBJECT_VERSION_TAGGING
|
||||
}
|
||||
if hasObject {
|
||||
return s3_constants.S3_ACTION_GET_OBJECT_TAGGING
|
||||
}
|
||||
return s3_constants.S3_ACTION_GET_BUCKET_TAGGING
|
||||
case http.MethodPut:
|
||||
if versioned {
|
||||
return s3_constants.S3_ACTION_PUT_OBJECT_VERSION_TAGGING
|
||||
}
|
||||
if hasObject {
|
||||
return s3_constants.S3_ACTION_PUT_OBJECT_TAGGING
|
||||
}
|
||||
return s3_constants.S3_ACTION_PUT_BUCKET_TAGGING
|
||||
case http.MethodDelete:
|
||||
if versioned {
|
||||
return s3_constants.S3_ACTION_DELETE_OBJECT_VERSION_TAGGING
|
||||
}
|
||||
if hasObject {
|
||||
return s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING
|
||||
}
|
||||
|
||||
@@ -114,6 +114,38 @@ func TestResolveS3Action_AttributesBeforeVersionId(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A tagging request carrying versionId targets a specific version and must
|
||||
// resolve to the version-tagging action so a grant limited to current-object
|
||||
// tagging cannot reach historical versions.
|
||||
func TestResolveS3Action_VersionTagging(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
object string
|
||||
query string
|
||||
want string
|
||||
}{
|
||||
{"get current tags", http.MethodGet, "key", "tagging", s3_constants.S3_ACTION_GET_OBJECT_TAGGING},
|
||||
{"put current tags", http.MethodPut, "key", "tagging", s3_constants.S3_ACTION_PUT_OBJECT_TAGGING},
|
||||
{"delete current tags", http.MethodDelete, "key", "tagging", s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING},
|
||||
{"get version tags", http.MethodGet, "key", "tagging&versionId=v1", s3_constants.S3_ACTION_GET_OBJECT_VERSION_TAGGING},
|
||||
{"put version tags", http.MethodPut, "key", "tagging&versionId=v1", s3_constants.S3_ACTION_PUT_OBJECT_VERSION_TAGGING},
|
||||
{"delete version tags", http.MethodDelete, "key", "tagging&versionId=v1", s3_constants.S3_ACTION_DELETE_OBJECT_VERSION_TAGGING},
|
||||
{"empty versionId stays current", http.MethodGet, "key", "tagging&versionId=", s3_constants.S3_ACTION_GET_OBJECT_TAGGING},
|
||||
{"bucket tagging ignores versionId", http.MethodGet, "", "tagging&versionId=v1", s3_constants.S3_ACTION_GET_BUCKET_TAGGING},
|
||||
{"non-empty tagging is still tagging", http.MethodGet, "key", "tagging=x&versionId=v1", s3_constants.S3_ACTION_GET_OBJECT_VERSION_TAGGING},
|
||||
{"non-empty tagging plain", http.MethodGet, "key", "tagging=x", s3_constants.S3_ACTION_GET_OBJECT_TAGGING},
|
||||
}
|
||||
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.
|
||||
|
||||
@@ -20,6 +20,11 @@ const (
|
||||
S3_ACTION_PUT_OBJECT_TAGGING = "s3:PutObjectTagging"
|
||||
S3_ACTION_DELETE_OBJECT_TAGGING = "s3:DeleteObjectTagging"
|
||||
|
||||
// Version-specific tagging operations (?tagging&versionId)
|
||||
S3_ACTION_GET_OBJECT_VERSION_TAGGING = "s3:GetObjectVersionTagging"
|
||||
S3_ACTION_PUT_OBJECT_VERSION_TAGGING = "s3:PutObjectVersionTagging"
|
||||
S3_ACTION_DELETE_OBJECT_VERSION_TAGGING = "s3:DeleteObjectVersionTagging"
|
||||
|
||||
// Object retention and legal hold
|
||||
S3_ACTION_GET_OBJECT_RETENTION = "s3:GetObjectRetention"
|
||||
S3_ACTION_PUT_OBJECT_RETENTION = "s3:PutObjectRetention"
|
||||
|
||||
@@ -330,7 +330,7 @@ func (s3a *S3ApiServer) PutBucketHandler(w http.ResponseWriter, r *http.Request)
|
||||
// This ensures Object Lock configuration is set in the same CreateEntry call,
|
||||
// preventing race conditions where the bucket exists without Object Lock enabled
|
||||
var bucketCrtime int64
|
||||
if err := s3a.mkdir(s3a.option.BucketsPath, bucket, func(entry *filer_pb.Entry) {
|
||||
if err := s3a.mkdirExclusive(s3a.option.BucketsPath, bucket, func(entry *filer_pb.Entry) {
|
||||
bucketCrtime = entry.Attributes.Crtime
|
||||
|
||||
// Set bucket owner
|
||||
@@ -373,6 +373,16 @@ func (s3a *S3ApiServer) PutBucketHandler(w http.ResponseWriter, r *http.Request)
|
||||
// return the appropriate already-exists error instead of InternalError.
|
||||
if exist, checkErr := s3a.exists(s3a.option.BucketsPath, bucket, true); checkErr == nil && exist {
|
||||
glog.V(3).Infof("PutBucketHandler: bucket %s was created concurrently", bucket)
|
||||
// From the entry itself, not the bucket registry: the pre-check
|
||||
// above has just cached this name as not found, so in the race this
|
||||
// branch exists for the registry would still say "no table bucket".
|
||||
if concurrentEntryIsForeign(s3a.getEntry(s3a.option.BucketsPath, bucket)) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrBucketAlreadyExists)
|
||||
return
|
||||
}
|
||||
if s3a.bucketConfigCache != nil {
|
||||
s3a.bucketConfigCache.RemoveNegativeCache(bucket)
|
||||
}
|
||||
errCode := s3a.existingBucketError(r, bucket, currentIdentityId, requestHasACL)
|
||||
if errCode == s3err.ErrBucketAlreadyOwnedByYou {
|
||||
s3a.healBucketOwnerIndex(bucket, currentIdentityId)
|
||||
@@ -744,7 +754,7 @@ func (s3a *S3ApiServer) autoCreateBucket(r *http.Request, bucket string) error {
|
||||
|
||||
identityId := s3_constants.GetIdentityNameFromContext(r)
|
||||
var bucketCrtime int64
|
||||
if err := s3a.mkdir(s3a.option.BucketsPath, bucket, func(entry *filer_pb.Entry) {
|
||||
if err := s3a.mkdirExclusive(s3a.option.BucketsPath, bucket, func(entry *filer_pb.Entry) {
|
||||
bucketCrtime = entry.Attributes.Crtime
|
||||
setBucketOwner(r)(entry)
|
||||
}); err != nil {
|
||||
@@ -754,26 +764,35 @@ func (s3a *S3ApiServer) autoCreateBucket(r *http.Request, bucket string) error {
|
||||
glog.Warningf("autoCreateBucket: failed to check existence for bucket %s: %v", bucket, err2)
|
||||
return fmt.Errorf("failed to auto-create bucket %s: %w", bucket, errors.Join(err, err2))
|
||||
} else if exist {
|
||||
entry, getErr := s3a.getEntry(s3a.option.BucketsPath, bucket)
|
||||
if getErr != nil {
|
||||
glog.Warningf("autoCreateBucket: failed to get entry for existing bucket %s: %v", bucket, getErr)
|
||||
return fmt.Errorf("failed to auto-create bucket %s: %w", bucket, errors.Join(err, getErr))
|
||||
}
|
||||
if concurrentEntryIsForeign(entry, nil) {
|
||||
// A table bucket carries no S3 owner and must not gain one —
|
||||
// or a write intended for a missing plain bucket.
|
||||
if s3a.bucketConfigCache != nil {
|
||||
s3a.bucketConfigCache.RemoveNegativeCache(bucket)
|
||||
}
|
||||
return fmt.Errorf("auto-create bucket %s: name taken by a table bucket: %w", bucket, err)
|
||||
}
|
||||
// The bucket exists, which is fine. However, we should ensure it has an owner.
|
||||
// If it was created by a concurrent request that didn't set an owner,
|
||||
// we'll set it here to ensure consistency.
|
||||
if entry, getErr := s3a.getEntry(s3a.option.BucketsPath, bucket); getErr == nil {
|
||||
if entry.Extended == nil || len(entry.Extended[s3_constants.AmzIdentityId]) == 0 {
|
||||
// No owner set, assign current admin as owner
|
||||
setBucketOwner(r)(entry)
|
||||
if updateErr := s3a.updateEntry(s3a.option.BucketsPath, entry); updateErr != nil {
|
||||
glog.Warningf("autoCreateBucket: failed to set owner for existing bucket %s: %v", bucket, updateErr)
|
||||
} else {
|
||||
glog.V(1).Infof("Set owner for existing bucket %s (created by concurrent request)", bucket)
|
||||
if owner := bucketEntryOwner(entry); owner != "" {
|
||||
if indexErr := s3a.addBucketToOwnerIndex(owner, bucket, entry.Attributes.Crtime); indexErr != nil {
|
||||
glog.Warningf("autoCreateBucket: owner index add %s/%s: %v", owner, bucket, indexErr)
|
||||
}
|
||||
if entry.Extended == nil || len(entry.Extended[s3_constants.AmzIdentityId]) == 0 {
|
||||
// No owner set, assign current admin as owner
|
||||
setBucketOwner(r)(entry)
|
||||
if updateErr := s3a.updateEntry(s3a.option.BucketsPath, entry); updateErr != nil {
|
||||
glog.Warningf("autoCreateBucket: failed to set owner for existing bucket %s: %v", bucket, updateErr)
|
||||
} else {
|
||||
glog.V(1).Infof("Set owner for existing bucket %s (created by concurrent request)", bucket)
|
||||
if owner := bucketEntryOwner(entry); owner != "" {
|
||||
if indexErr := s3a.addBucketToOwnerIndex(owner, bucket, entry.Attributes.Crtime); indexErr != nil {
|
||||
glog.Warningf("autoCreateBucket: owner index add %s/%s: %v", owner, bucket, indexErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
glog.Warningf("autoCreateBucket: failed to get entry for existing bucket %s: %v", bucket, getErr)
|
||||
}
|
||||
// Remove bucket from negative cache — it exists now
|
||||
if s3a.bucketConfigCache != nil {
|
||||
|
||||
@@ -67,6 +67,136 @@ func (e *EmbeddedIamApi) refreshIAMConfiguration() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// canPersistIdentity reports whether a change to the named identity can be written through the
|
||||
// credential manager's single-identity methods instead of SaveConfiguration. It is false when
|
||||
// there is no credential manager, when the caller asked for no persistent write (skipPersist),
|
||||
// and for static identities, which live outside the store: those keep the full-save path.
|
||||
func (e *EmbeddedIamApi) canPersistIdentity(skipPersist bool, userName string) bool {
|
||||
return e.credentialManager != nil && !skipPersist && !e.credentialManager.IsStaticIdentity(userName)
|
||||
}
|
||||
|
||||
// groupsWithMember returns the groups in s3cfg that list userName as a member. Taken before a
|
||||
// handler renames or removes the user, it names the group records that handler will change.
|
||||
func groupsWithMember(s3cfg *iam_pb.S3ApiConfiguration, userName string) []*iam_pb.Group {
|
||||
var groups []*iam_pb.Group
|
||||
for _, g := range s3cfg.Groups {
|
||||
for _, m := range g.Members {
|
||||
if m == userName {
|
||||
groups = append(groups, g)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
// serviceAccountsOf returns the service accounts in s3cfg whose parent is userName.
|
||||
func serviceAccountsOf(s3cfg *iam_pb.S3ApiConfiguration, userName string) []*iam_pb.ServiceAccount {
|
||||
var accounts []*iam_pb.ServiceAccount
|
||||
for _, sa := range s3cfg.ServiceAccounts {
|
||||
if sa.ParentUser == userName {
|
||||
accounts = append(accounts, sa)
|
||||
}
|
||||
}
|
||||
return accounts
|
||||
}
|
||||
|
||||
// persistIdentity writes the one identity a handler changed in s3cfg through the credential
|
||||
// manager. The store writes that identity's record and propagates it alone; the other
|
||||
// identities are not rewritten.
|
||||
func (e *EmbeddedIamApi) persistIdentity(ctx context.Context, s3cfg *iam_pb.S3ApiConfiguration, userName string) error {
|
||||
ident := findIdentityByName(s3cfg, userName)
|
||||
if ident == nil {
|
||||
return credential.ErrUserNotFound
|
||||
}
|
||||
return e.credentialManager.UpdateUser(ctx, userName, ident)
|
||||
}
|
||||
|
||||
// persistRenamedIdentity writes a user renamed from oldName to newName by UpdateUser through the
|
||||
// credential manager: the identity, the groups that listed the old name and the service accounts
|
||||
// it parented. Where the store has RenameUser the handler already moved the record and its inline
|
||||
// policies, and the identity is written under the new name. Otherwise UpdateUser under the old
|
||||
// name moves the record in stores that treat a changed Name as a rename (filer_etc, memory), the
|
||||
// propagating store propagates the new identity and the old name's removal, and the inline policy
|
||||
// copies the handler left under the old name are removed. A store that did neither still holds
|
||||
// the user under the old name; the caller is told so (false) and keeps the full save, which is
|
||||
// what renames such a store today.
|
||||
func (e *EmbeddedIamApi) persistRenamedIdentity(ctx context.Context, s3cfg *iam_pb.S3ApiConfiguration, oldName, newName string, groups []*iam_pb.Group, accounts []*iam_pb.ServiceAccount) (bool, error) {
|
||||
ident := findIdentityByName(s3cfg, newName)
|
||||
if ident == nil {
|
||||
return false, credential.ErrUserNotFound
|
||||
}
|
||||
storedAs := oldName
|
||||
if _, err := e.credentialManager.GetUser(ctx, newName); err == nil {
|
||||
storedAs = newName
|
||||
}
|
||||
if err := e.credentialManager.UpdateUser(ctx, storedAs, ident); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if storedAs == oldName {
|
||||
if _, err := e.credentialManager.GetUser(ctx, newName); err != nil {
|
||||
return false, nil
|
||||
}
|
||||
policyNames, err := e.credentialManager.ListUserInlinePolicies(ctx, oldName)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("list inline policies for %s: %w", oldName, err)
|
||||
}
|
||||
for _, policyName := range policyNames {
|
||||
if err := e.credentialManager.DeleteUserInlinePolicy(ctx, oldName, policyName); err != nil {
|
||||
return false, fmt.Errorf("remove inline policy %s from %s: %w", policyName, oldName, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, g := range groups {
|
||||
if err := e.credentialManager.UpdateGroup(ctx, g); err != nil {
|
||||
return false, fmt.Errorf("update group %s: %w", g.Name, err)
|
||||
}
|
||||
}
|
||||
for _, sa := range accounts {
|
||||
if err := e.credentialManager.UpdateServiceAccount(ctx, sa.Id, sa); err != nil {
|
||||
return false, fmt.Errorf("update service account %s: %w", sa.Id, err)
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// deleteIdentity removes a user deleted by DeleteUser through the credential manager: its inline
|
||||
// policies, its record (the store propagates the one removal) and the groups that listed it,
|
||||
// whose membership DeleteUser already changed in s3cfg.
|
||||
func (e *EmbeddedIamApi) deleteIdentity(ctx context.Context, userName string, groups []*iam_pb.Group) error {
|
||||
policyNames, err := e.credentialManager.ListUserInlinePolicies(ctx, userName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list inline policies for %s: %w", userName, err)
|
||||
}
|
||||
for _, policyName := range policyNames {
|
||||
if err := e.credentialManager.DeleteUserInlinePolicy(ctx, userName, policyName); err != nil {
|
||||
return fmt.Errorf("remove inline policy %s from %s: %w", policyName, userName, err)
|
||||
}
|
||||
}
|
||||
if err := e.credentialManager.DeleteUser(ctx, userName); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, g := range groups {
|
||||
if err := e.credentialManager.UpdateGroup(ctx, g); err != nil {
|
||||
return fmt.Errorf("update group %s: %w", g.Name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// reloadsAfterTargetedWrite names the actions that persist through the credential manager
|
||||
// rather than SaveConfiguration; the in-memory identity maps are refreshed after them the way
|
||||
// they are after a full save.
|
||||
func reloadsAfterTargetedWrite(action string) bool {
|
||||
switch action {
|
||||
case "AttachUserPolicy", "DetachUserPolicy", "CreatePolicy", "CreatePolicyVersion", "DeletePolicy",
|
||||
"CreateUser", "UpdateUser", "DeleteUser", "CreateAccessKey", "DeleteAccessKey", "UpdateAccessKey",
|
||||
"SetUserStatus", "PutUserPolicy", "DeleteUserPolicy", "PutGroupPolicy", "DeleteGroupPolicy":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Constants for service account identifiers
|
||||
const (
|
||||
ServiceAccountIDLength = 12 // Length of the service account ID
|
||||
@@ -2735,27 +2865,79 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
|
||||
}
|
||||
changed = false
|
||||
case "UpdateUser":
|
||||
userName, newUserName := values.Get("UserName"), values.Get("NewUserName")
|
||||
// Taken before the rename: the records the handler changes besides the identity.
|
||||
groups := groupsWithMember(s3cfg, userName)
|
||||
accounts := serviceAccountsOf(s3cfg, userName)
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.UpdateUser(ctx, s3cfg, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
// Write the renamed identity, its groups and service accounts through the credential
|
||||
// manager instead of rewriting every identity via SaveConfiguration. A request that
|
||||
// renames nothing changed nothing, so there is nothing to write either way.
|
||||
if e.canPersistIdentity(skipPersist, userName) {
|
||||
renamed := true
|
||||
if newUserName != "" && newUserName != userName {
|
||||
var err error
|
||||
renamed, err = e.persistRenamedIdentity(ctx, s3cfg, userName, newUserName, groups, accounts)
|
||||
if err != nil {
|
||||
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
|
||||
}
|
||||
}
|
||||
changed = !renamed
|
||||
}
|
||||
case "DeleteUser":
|
||||
userName := values.Get("UserName")
|
||||
groups := groupsWithMember(s3cfg, userName)
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.DeleteUser(s3cfg, userName)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
// Targeted delete: one record removed and one removal propagated, plus the groups whose
|
||||
// membership changed, instead of rewriting every remaining identity.
|
||||
if e.canPersistIdentity(skipPersist, userName) {
|
||||
if err := e.deleteIdentity(ctx, userName, groups); err != nil {
|
||||
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
|
||||
}
|
||||
changed = false
|
||||
}
|
||||
case "CreateAccessKey":
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.CreateAccessKey(s3cfg, values)
|
||||
userName := values.Get("UserName")
|
||||
resp, iamErr := e.CreateAccessKey(s3cfg, values)
|
||||
if iamErr != nil {
|
||||
glog.Errorf("CreateAccessKey: %+v", iamErr.Error)
|
||||
return nil, iamErr
|
||||
}
|
||||
response = resp
|
||||
// Targeted write: credentialManager.CreateAccessKey adds the key to the one identity
|
||||
// and propagates that identity alone.
|
||||
if e.canPersistIdentity(skipPersist, userName) {
|
||||
cred := &iam_pb.Credential{
|
||||
AccessKey: *resp.CreateAccessKeyResult.AccessKey.AccessKeyId,
|
||||
SecretKey: *resp.CreateAccessKeyResult.AccessKey.SecretAccessKey,
|
||||
Status: iamAccessKeyStatusActive,
|
||||
}
|
||||
if err := e.credentialManager.CreateAccessKey(ctx, userName, cred); err != nil {
|
||||
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
|
||||
}
|
||||
changed = false
|
||||
}
|
||||
case "DeleteAccessKey":
|
||||
userName, accessKeyId := values.Get("UserName"), values.Get("AccessKeyId")
|
||||
response = e.DeleteAccessKey(s3cfg, values)
|
||||
// Targeted write: credentialManager.DeleteAccessKey removes the key from the one identity
|
||||
// and propagates that identity alone. The handler answers 200 for a key or user it does
|
||||
// not know, so a not-found from the store is the same no-op it always was.
|
||||
if e.canPersistIdentity(skipPersist, userName) {
|
||||
err := e.credentialManager.DeleteAccessKey(ctx, userName, accessKeyId)
|
||||
if err != nil && !errors.Is(err, credential.ErrAccessKeyNotFound) && !errors.Is(err, credential.ErrUserNotFound) {
|
||||
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
|
||||
}
|
||||
changed = false
|
||||
}
|
||||
case "CreatePolicy":
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.CreatePolicy(ctx, values)
|
||||
@@ -2773,12 +2955,21 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
|
||||
}
|
||||
changed = false
|
||||
case "PutUserPolicy":
|
||||
userName := values.Get("UserName")
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.PutUserPolicy(s3cfg, values)
|
||||
if iamErr != nil {
|
||||
glog.Errorf("PutUserPolicy: %+v", iamErr.Error)
|
||||
return nil, iamErr
|
||||
}
|
||||
// The policy document is already stored; what remains is the identity's recomputed
|
||||
// Actions, written and propagated for that identity alone.
|
||||
if e.canPersistIdentity(skipPersist, userName) {
|
||||
if err := e.persistIdentity(ctx, s3cfg, userName); err != nil {
|
||||
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
|
||||
}
|
||||
changed = false
|
||||
}
|
||||
case "GetUserPolicy":
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.GetUserPolicy(s3cfg, values)
|
||||
@@ -2787,11 +2978,18 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
|
||||
}
|
||||
changed = false
|
||||
case "DeleteUserPolicy":
|
||||
userName := values.Get("UserName")
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.DeleteUserPolicy(s3cfg, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
if e.canPersistIdentity(skipPersist, userName) {
|
||||
if err := e.persistIdentity(ctx, s3cfg, userName); err != nil {
|
||||
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
|
||||
}
|
||||
changed = false
|
||||
}
|
||||
case "ListUserPolicies":
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.ListUserPolicies(s3cfg, values)
|
||||
@@ -2883,17 +3081,31 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
|
||||
}
|
||||
changed = false
|
||||
case "SetUserStatus":
|
||||
userName := values.Get("UserName")
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.SetUserStatus(s3cfg, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
if e.canPersistIdentity(skipPersist, userName) {
|
||||
if err := e.persistIdentity(ctx, s3cfg, userName); err != nil {
|
||||
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
|
||||
}
|
||||
changed = false
|
||||
}
|
||||
case "UpdateAccessKey":
|
||||
userName := values.Get("UserName")
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.UpdateAccessKey(s3cfg, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
if e.canPersistIdentity(skipPersist, userName) {
|
||||
if err := e.persistIdentity(ctx, s3cfg, userName); err != nil {
|
||||
return nil, &iamError{Code: CredentialErrToIamErrCode(err), Error: err}
|
||||
}
|
||||
changed = false
|
||||
}
|
||||
// Service Account actions
|
||||
case "CreateServiceAccount":
|
||||
createdBy := values.Get("CreatedBy")
|
||||
@@ -3034,7 +3246,7 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
|
||||
glog.Errorf("Failed to reload IAM configuration after mutation: %v", err)
|
||||
// Don't fail the request since the persistent save succeeded
|
||||
}
|
||||
} else if action == "AttachUserPolicy" || action == "DetachUserPolicy" || action == "CreatePolicy" || action == "CreatePolicyVersion" || action == "DeletePolicy" || action == "CreateUser" || action == "PutGroupPolicy" || action == "DeleteGroupPolicy" {
|
||||
} else if reloadsAfterTargetedWrite(action) {
|
||||
// Even if changed=false (persisted via credentialManager), we should still reload
|
||||
// if we are utilizing the local in-memory cache for speed
|
||||
if err := e.ReloadConfiguration(); err != nil {
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
package s3api
|
||||
|
||||
// Targeted-write regression tests: single-identity IAM actions must write and
|
||||
// propagate only the identity they changed, not every identity via
|
||||
// SaveConfiguration. See https://github.com/seaweedfs/seaweedfs/issues/11865.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential/memory"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// recordingStore wraps a memory store and counts the write methods the
|
||||
// dispatcher used, so a test can assert the single-identity path was taken and
|
||||
// SaveConfiguration was not. It embeds the concrete store (rather than the
|
||||
// CredentialStore interface) so optional interfaces like InlinePolicyStore and
|
||||
// UserRenamer stay visible through the wrapper.
|
||||
type recordingStore struct {
|
||||
*memory.MemoryStore
|
||||
saves int
|
||||
createAccessKeys int
|
||||
deleteAccessKeys int
|
||||
updateUsers int
|
||||
deleteUsers int
|
||||
updateGroups int
|
||||
}
|
||||
|
||||
func (r *recordingStore) SaveConfiguration(ctx context.Context, config *iam_pb.S3ApiConfiguration) error {
|
||||
r.saves++
|
||||
return r.MemoryStore.SaveConfiguration(ctx, config)
|
||||
}
|
||||
|
||||
func (r *recordingStore) CreateAccessKey(ctx context.Context, username string, cred *iam_pb.Credential) error {
|
||||
r.createAccessKeys++
|
||||
return r.MemoryStore.CreateAccessKey(ctx, username, cred)
|
||||
}
|
||||
|
||||
func (r *recordingStore) DeleteAccessKey(ctx context.Context, username string, accessKey string) error {
|
||||
r.deleteAccessKeys++
|
||||
return r.MemoryStore.DeleteAccessKey(ctx, username, accessKey)
|
||||
}
|
||||
|
||||
func (r *recordingStore) UpdateUser(ctx context.Context, username string, identity *iam_pb.Identity) error {
|
||||
r.updateUsers++
|
||||
return r.MemoryStore.UpdateUser(ctx, username, identity)
|
||||
}
|
||||
|
||||
func (r *recordingStore) DeleteUser(ctx context.Context, username string) error {
|
||||
r.deleteUsers++
|
||||
return r.MemoryStore.DeleteUser(ctx, username)
|
||||
}
|
||||
|
||||
func (r *recordingStore) UpdateGroup(ctx context.Context, group *iam_pb.Group) error {
|
||||
r.updateGroups++
|
||||
return r.MemoryStore.UpdateGroup(ctx, group)
|
||||
}
|
||||
|
||||
// newTargetedWriteTestApi seeds cfg into the store and wraps the store in a
|
||||
// recordingStore. The initial sync save happens before the recorder is
|
||||
// installed so it does not count.
|
||||
func newTargetedWriteTestApi(t *testing.T, cfg *iam_pb.S3ApiConfiguration) (*EmbeddedIamApiForTest, *recordingStore) {
|
||||
t.Helper()
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = cfg
|
||||
// Trigger the one-time mockConfig -> store seed through a read action.
|
||||
_, iamErr := api.ExecuteAction(context.Background(), url.Values{"Action": {"ListUsers"}}, false, "")
|
||||
require.Nil(t, iamErr)
|
||||
rec := &recordingStore{MemoryStore: api.credentialManager.Store.(*memory.MemoryStore)}
|
||||
api.credentialManager.Store = rec
|
||||
return api, rec
|
||||
}
|
||||
|
||||
func executeAction(t *testing.T, api *EmbeddedIamApiForTest, vals url.Values) {
|
||||
t.Helper()
|
||||
_, iamErr := api.ExecuteAction(context.Background(), vals, false, "")
|
||||
require.Nil(t, iamErr)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamCreateAccessKeyTargeted(t *testing.T) {
|
||||
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "alice"}, {Name: "bob"}},
|
||||
})
|
||||
ctx := context.Background()
|
||||
|
||||
resp, iamErr := api.ExecuteAction(ctx, url.Values{
|
||||
"Action": {"CreateAccessKey"},
|
||||
"UserName": {"alice"},
|
||||
}, false, "")
|
||||
require.Nil(t, iamErr)
|
||||
require.Equal(t, 0, rec.saves, "CreateAccessKey must not SaveConfiguration")
|
||||
require.Equal(t, 1, rec.createAccessKeys)
|
||||
|
||||
out := resp.(*iamCreateAccessKeyResponse)
|
||||
ident, err := api.credentialManager.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, ident.Credentials, 1)
|
||||
assert.Equal(t, *out.CreateAccessKeyResult.AccessKey.AccessKeyId, ident.Credentials[0].AccessKey)
|
||||
|
||||
// The new key resolves in the store.
|
||||
byKey, err := api.credentialManager.GetUserByAccessKey(ctx, *out.CreateAccessKeyResult.AccessKey.AccessKeyId)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "alice", byKey.Name)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamDeleteAccessKeyTargeted(t *testing.T) {
|
||||
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{
|
||||
Name: "alice",
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: "AKIATESTFAKEKEY00001", SecretKey: "testsecretfake"}},
|
||||
}},
|
||||
})
|
||||
ctx := context.Background()
|
||||
|
||||
executeAction(t, api, url.Values{
|
||||
"Action": {"DeleteAccessKey"},
|
||||
"UserName": {"alice"},
|
||||
"AccessKeyId": {"AKIATESTFAKEKEY00001"},
|
||||
})
|
||||
require.Equal(t, 0, rec.saves, "DeleteAccessKey must not SaveConfiguration")
|
||||
require.Equal(t, 1, rec.deleteAccessKeys)
|
||||
|
||||
ident, err := api.credentialManager.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, ident.Credentials)
|
||||
_, err = api.credentialManager.GetUserByAccessKey(ctx, "AKIATESTFAKEKEY00001")
|
||||
require.ErrorIs(t, err, credential.ErrAccessKeyNotFound)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamUpdateAccessKeyTargeted(t *testing.T) {
|
||||
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{
|
||||
Name: "alice",
|
||||
Credentials: []*iam_pb.Credential{
|
||||
{AccessKey: "AKIATESTFAKEKEY00001", SecretKey: "testsecretfake", Status: iamAccessKeyStatusActive},
|
||||
},
|
||||
}},
|
||||
})
|
||||
ctx := context.Background()
|
||||
|
||||
executeAction(t, api, url.Values{
|
||||
"Action": {"UpdateAccessKey"},
|
||||
"UserName": {"alice"},
|
||||
"AccessKeyId": {"AKIATESTFAKEKEY00001"},
|
||||
"Status": {iamAccessKeyStatusInactive},
|
||||
})
|
||||
require.Equal(t, 0, rec.saves, "UpdateAccessKey must not SaveConfiguration")
|
||||
require.Equal(t, 1, rec.updateUsers)
|
||||
|
||||
ident, err := api.credentialManager.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, ident.Credentials, 1)
|
||||
assert.Equal(t, iamAccessKeyStatusInactive, ident.Credentials[0].Status)
|
||||
}
|
||||
|
||||
const iamTargetedTestPolicy = `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::bench/*"]}]
|
||||
}`
|
||||
|
||||
func TestEmbeddedIamPutUserPolicyTargeted(t *testing.T) {
|
||||
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "alice"}, {Name: "bob"}},
|
||||
})
|
||||
ctx := context.Background()
|
||||
|
||||
executeAction(t, api, url.Values{
|
||||
"Action": {"PutUserPolicy"},
|
||||
"UserName": {"alice"},
|
||||
"PolicyName": {"read-bench"},
|
||||
"PolicyDocument": {iamTargetedTestPolicy},
|
||||
})
|
||||
require.Equal(t, 0, rec.saves, "PutUserPolicy must not SaveConfiguration")
|
||||
require.Equal(t, 1, rec.updateUsers)
|
||||
|
||||
ident, err := api.credentialManager.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.NotEmpty(t, ident.Actions, "identity Actions must be recomputed and persisted")
|
||||
|
||||
doc, err := api.credentialManager.GetUserInlinePolicy(ctx, "alice", "read-bench")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, doc)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamDeleteUserPolicyTargeted(t *testing.T) {
|
||||
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "alice"}},
|
||||
})
|
||||
ctx := context.Background()
|
||||
|
||||
executeAction(t, api, url.Values{
|
||||
"Action": {"PutUserPolicy"},
|
||||
"UserName": {"alice"},
|
||||
"PolicyName": {"read-bench"},
|
||||
"PolicyDocument": {iamTargetedTestPolicy},
|
||||
})
|
||||
require.Equal(t, 1, rec.updateUsers)
|
||||
|
||||
executeAction(t, api, url.Values{
|
||||
"Action": {"DeleteUserPolicy"},
|
||||
"UserName": {"alice"},
|
||||
"PolicyName": {"read-bench"},
|
||||
})
|
||||
require.Equal(t, 0, rec.saves, "DeleteUserPolicy must not SaveConfiguration")
|
||||
require.Equal(t, 2, rec.updateUsers)
|
||||
|
||||
policies, err := api.credentialManager.ListUserInlinePolicies(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, policies)
|
||||
ident, err := api.credentialManager.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, ident.Actions)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamSetUserStatusTargeted(t *testing.T) {
|
||||
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "alice"}},
|
||||
})
|
||||
ctx := context.Background()
|
||||
|
||||
executeAction(t, api, url.Values{
|
||||
"Action": {"SetUserStatus"},
|
||||
"UserName": {"alice"},
|
||||
"Status": {iamAccessKeyStatusInactive},
|
||||
})
|
||||
require.Equal(t, 0, rec.saves, "SetUserStatus must not SaveConfiguration")
|
||||
require.Equal(t, 1, rec.updateUsers)
|
||||
|
||||
ident, err := api.credentialManager.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, ident.Disabled)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamUpdateUserRenameTargeted(t *testing.T) {
|
||||
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "alice"}, {Name: "bob"}},
|
||||
Groups: []*iam_pb.Group{
|
||||
{Name: "devs", Members: []string{"alice", "bob"}},
|
||||
{Name: "ops", Members: []string{"bob"}},
|
||||
},
|
||||
})
|
||||
ctx := context.Background()
|
||||
// Groups in the seed config must also be created in the store directly:
|
||||
// the memory store only surfaces groups written via CreateGroup.
|
||||
require.NoError(t, api.credentialManager.CreateGroup(ctx, &iam_pb.Group{Name: "devs", Members: []string{"alice", "bob"}}))
|
||||
require.NoError(t, api.credentialManager.CreateGroup(ctx, &iam_pb.Group{Name: "ops", Members: []string{"bob"}}))
|
||||
require.NoError(t, api.credentialManager.PutUserInlinePolicy(ctx, "alice", "p1", mustParseIamTargetedTestPolicy(t)))
|
||||
|
||||
executeAction(t, api, url.Values{
|
||||
"Action": {"UpdateUser"},
|
||||
"UserName": {"alice"},
|
||||
"NewUserName": {"alice-renamed"},
|
||||
})
|
||||
require.Equal(t, 0, rec.saves, "UpdateUser rename must not SaveConfiguration")
|
||||
|
||||
_, err := api.credentialManager.GetUser(ctx, "alice")
|
||||
require.ErrorIs(t, err, credential.ErrUserNotFound)
|
||||
_, err = api.credentialManager.GetUser(ctx, "alice-renamed")
|
||||
require.NoError(t, err)
|
||||
|
||||
// Group membership and inline policies follow the rename.
|
||||
g, err := api.credentialManager.GetGroup(ctx, "devs")
|
||||
require.NoError(t, err)
|
||||
assert.ElementsMatch(t, []string{"alice-renamed", "bob"}, g.Members)
|
||||
g, err = api.credentialManager.GetGroup(ctx, "ops")
|
||||
require.NoError(t, err)
|
||||
assert.ElementsMatch(t, []string{"bob"}, g.Members)
|
||||
|
||||
policies, err := api.credentialManager.ListUserInlinePolicies(ctx, "alice-renamed")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"p1"}, policies)
|
||||
policies, err = api.credentialManager.ListUserInlinePolicies(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, policies)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamDeleteUserTargeted(t *testing.T) {
|
||||
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "alice"}, {Name: "bob"}},
|
||||
Groups: []*iam_pb.Group{{Name: "devs", Members: []string{"alice", "bob"}}},
|
||||
})
|
||||
ctx := context.Background()
|
||||
require.NoError(t, api.credentialManager.CreateGroup(ctx, &iam_pb.Group{Name: "devs", Members: []string{"alice", "bob"}}))
|
||||
|
||||
executeAction(t, api, url.Values{
|
||||
"Action": {"DeleteUser"},
|
||||
"UserName": {"alice"},
|
||||
})
|
||||
require.Equal(t, 0, rec.saves, "DeleteUser must not SaveConfiguration")
|
||||
require.Equal(t, 1, rec.deleteUsers)
|
||||
require.Equal(t, 1, rec.updateGroups)
|
||||
|
||||
_, err := api.credentialManager.GetUser(ctx, "alice")
|
||||
require.ErrorIs(t, err, credential.ErrUserNotFound)
|
||||
g, err := api.credentialManager.GetGroup(ctx, "devs")
|
||||
require.NoError(t, err)
|
||||
assert.ElementsMatch(t, []string{"bob"}, g.Members)
|
||||
_, err = api.credentialManager.GetUser(ctx, "bob")
|
||||
require.NoError(t, err, "other identities must be untouched")
|
||||
}
|
||||
|
||||
// TestEmbeddedIamTargetedSkipPersist: skipPersist must suppress the targeted
|
||||
// write exactly like it suppresses the full save.
|
||||
func TestEmbeddedIamTargetedSkipPersist(t *testing.T) {
|
||||
api, rec := newTargetedWriteTestApi(t, &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "alice"}},
|
||||
})
|
||||
ctx := context.Background()
|
||||
|
||||
for _, vals := range []url.Values{
|
||||
{"Action": {"CreateAccessKey"}, "UserName": {"alice"}},
|
||||
{"Action": {"SetUserStatus"}, "UserName": {"alice"}, "Status": {iamAccessKeyStatusInactive}},
|
||||
{"Action": {"PutUserPolicy"}, "UserName": {"alice"}, "PolicyName": {"p"}, "PolicyDocument": {iamTargetedTestPolicy}},
|
||||
} {
|
||||
_, iamErr := api.ExecuteAction(ctx, vals, true /*skipPersist*/, "")
|
||||
require.Nil(t, iamErr, "action %v", vals.Get("Action"))
|
||||
}
|
||||
assert.Equal(t, 0, rec.saves)
|
||||
assert.Equal(t, 0, rec.createAccessKeys)
|
||||
assert.Equal(t, 0, rec.updateUsers)
|
||||
|
||||
ident, err := api.credentialManager.GetUser(ctx, "alice")
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, ident.Credentials)
|
||||
assert.False(t, ident.Disabled)
|
||||
}
|
||||
|
||||
// TestEmbeddedIamStaticIdentityKeepsFullSave: static identities live outside
|
||||
// the store, so a change to one still takes the full-save path.
|
||||
func TestEmbeddedIamStaticIdentityKeepsFullSave(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{}
|
||||
api.credentialManager.SetStaticIdentities([]*iam_pb.Identity{{Name: "static-admin"}})
|
||||
rec := &recordingStore{MemoryStore: api.credentialManager.Store.(*memory.MemoryStore)}
|
||||
api.credentialManager.Store = rec
|
||||
|
||||
// Seed via a read action; static identities are merged into the loaded config.
|
||||
_, iamErr := api.ExecuteAction(context.Background(), url.Values{"Action": {"ListUsers"}}, false, "")
|
||||
require.Nil(t, iamErr)
|
||||
rec.saves = 0
|
||||
|
||||
executeAction(t, api, url.Values{
|
||||
"Action": {"SetUserStatus"},
|
||||
"UserName": {"static-admin"},
|
||||
"Status": {iamAccessKeyStatusInactive},
|
||||
})
|
||||
assert.Equal(t, 1, rec.saves, "static identity changes keep the full-save path")
|
||||
assert.Equal(t, 0, rec.updateUsers)
|
||||
}
|
||||
|
||||
func mustParseIamTargetedTestPolicy(t *testing.T) (doc policy_engine.PolicyDocument) {
|
||||
t.Helper()
|
||||
require.NoError(t, json.Unmarshal([]byte(iamTargetedTestPolicy), &doc))
|
||||
return doc
|
||||
}
|
||||
@@ -174,7 +174,7 @@ func TestAnonymousObjectACLVersionedEmptyDirectoryMarker(t *testing.T) {
|
||||
require.Equal(t, "null", rr.Header().Get("x-amz-version-id"))
|
||||
}
|
||||
rr := serveAnonymousRead(s3a, method, "folder", "", nil)
|
||||
require.Equal(t, 404, rr.Code, "the bare prefix is still not an object")
|
||||
require.Equal(t, 403, rr.Code, "the bare prefix is not an object, and the miss stays masked for a non-listable bucket")
|
||||
marker.Extended[s3_constants.ExtAmzAclKey] = []byte(`[]`)
|
||||
rr = serveAnonymousRead(s3a, method, "folder/", "", nil)
|
||||
require.Equal(t, 403, rr.Code, rr.Body.String())
|
||||
@@ -238,8 +238,12 @@ func TestAnonymousObjectACLVersionedDirectoryIdentity(t *testing.T) {
|
||||
f.entries["/buckets/b/folder/.versions"] = &filer_pb.Entry{IsDirectory: true, Extended: map[string][]byte{s3_constants.ExtLatestVersionIdKey: []byte("")}}
|
||||
}
|
||||
// Equivalent filer-path spellings must not recover a different object's data.
|
||||
for _, object := range []string{"folder/", "folder//", "folder\\"} {
|
||||
assertMissing(serveAnonymousRead(s3a, method, object, route.query, headers))
|
||||
assertMissing(serveAnonymousRead(s3a, method, "folder/", route.query, headers))
|
||||
// Spellings the policy's folder/ grant does not cover are
|
||||
// masked: a miss must be indistinguishable from a denied read.
|
||||
for _, object := range []string{"folder//", "folder\\"} {
|
||||
rr := serveAnonymousRead(s3a, method, object, route.query, headers)
|
||||
require.Equal(t, http.StatusForbidden, rr.Code, rr.Body.String())
|
||||
}
|
||||
if kind == "regular file" || kind == "prefix object" || kind == "empty prefix object" {
|
||||
// A slash-only policy must not authorize data belonging to the bare key.
|
||||
|
||||
@@ -4,10 +4,12 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
@@ -110,3 +112,70 @@ func (s3a *S3ApiServer) authorizeAnonymousObjectRead(r *http.Request, bucket, ob
|
||||
}
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
// authorizeAnonymousBucketList reports whether an anonymous caller may learn
|
||||
// which keys exist in the bucket: bucket listing via policy or identity, or a
|
||||
// public-read bucket. Anything else masks the miss as AccessDenied.
|
||||
func (s3a *S3ApiServer) authorizeAnonymousBucketList(r *http.Request, bucket string) s3err.ErrorCode {
|
||||
identity, _ := s3_constants.GetIdentityFromContext(r).(*Identity)
|
||||
object := mux.Vars(r)["object"]
|
||||
// The caller's query parameters would otherwise retarget these checks
|
||||
// (?policy resolves to GetBucketPolicy) or satisfy a prefix condition on an
|
||||
// unrelated subtree, so each runs on a request with a fixed shape: a
|
||||
// ListBucket scoped to the probed key, and a plain read of the key itself.
|
||||
// A caller that could learn the key's existence either way — by listing or
|
||||
// by getting it — gets the real miss.
|
||||
listReq := r.Clone(r.Context())
|
||||
listReq.URL = &url.URL{Path: "/" + bucket, RawQuery: url.Values{"prefix": {object}}.Encode()}
|
||||
// versionId must survive: a read of a specific version resolves to
|
||||
// s3:GetObjectVersion, and dropping it would let a GetObject grant answer
|
||||
// for versions the caller may not read.
|
||||
readQuery := url.Values{}
|
||||
if v := r.URL.Query().Get("versionId"); v != "" {
|
||||
readQuery.Set("versionId", v)
|
||||
}
|
||||
readReq := r.Clone(r.Context())
|
||||
readReq.URL = &url.URL{Path: "/" + bucket + "/" + object, RawQuery: readQuery.Encode()}
|
||||
|
||||
principal := buildPrincipalARN(identity, r)
|
||||
policyAllowed := false
|
||||
code, allowed := s3a.checkPolicyWithEntry(listReq, bucket, "", string(s3_constants.ACTION_LIST), principal, nil)
|
||||
if code != s3err.ErrNone {
|
||||
return code
|
||||
}
|
||||
policyAllowed = allowed
|
||||
if !policyAllowed {
|
||||
code, allowed = s3a.checkPolicyWithEntry(readReq, bucket, object, string(s3_constants.ACTION_READ), principal, nil)
|
||||
if code != s3err.ErrNone {
|
||||
return code
|
||||
}
|
||||
policyAllowed = allowed
|
||||
}
|
||||
if s3a.iam.isActionExplicitlyDeniedByApplicablePolicies(listReq, identity, s3_constants.ACTION_LIST, bucket, "") ||
|
||||
s3a.iam.isActionExplicitlyDeniedByApplicablePolicies(readReq, identity, s3_constants.ACTION_READ, bucket, object) {
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
if policyAllowed {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if identity != nil &&
|
||||
(s3a.iam.VerifyActionPermission(listReq, identity, s3_constants.ACTION_LIST, bucket, "") == s3err.ErrNone ||
|
||||
s3a.iam.VerifyActionPermission(readReq, identity, s3_constants.ACTION_READ, bucket, object) == s3err.ErrNone) {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if config, code := s3a.getBucketConfig(bucket); code == s3err.ErrNone && config.IsPublicRead {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
// 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.
|
||||
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)
|
||||
return
|
||||
}
|
||||
s3err.WriteErrorResponse(w, r, code)
|
||||
}
|
||||
@@ -663,7 +663,7 @@ func (s3a *S3ApiServer) handleDirectoryObjectRequest(w http.ResponseWriter, r *h
|
||||
} else if isDirectoryObject {
|
||||
// Directory object but doesn't exist
|
||||
glog.V(2).Infof("%s: directory object %s/%s not found", handlerName, bucket, object)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return true // Request was handled (with not found)
|
||||
}
|
||||
|
||||
@@ -770,7 +770,11 @@ func (s3a *S3ApiServer) processConditionalHeaders(w http.ResponseWriter, r *http
|
||||
w.Header().Set("ETag", result.ETag)
|
||||
}
|
||||
|
||||
s3err.WriteErrorResponse(w, r, result.ErrorCode)
|
||||
if result.ErrorCode == s3err.ErrNoSuchKey || result.ErrorCode == s3err.ErrNoSuchBucket {
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, result.ErrorCode)
|
||||
} else {
|
||||
s3err.WriteErrorResponse(w, r, result.ErrorCode)
|
||||
}
|
||||
return result, true // request handled
|
||||
}
|
||||
return result, false // request not handled
|
||||
@@ -841,7 +845,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
versioningConfigured, err = s3a.isVersioningConfigured(bucket)
|
||||
if err != nil {
|
||||
if err == filer_pb.ErrNotFound {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchBucket)
|
||||
return
|
||||
}
|
||||
glog.Errorf("Error checking versioning status for bucket %s: %v", bucket, err)
|
||||
@@ -860,7 +864,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
if err != nil {
|
||||
glog.Errorf("Failed to get specific version %s: %v", versionId, err)
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchVersion)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchVersion)
|
||||
} else {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
}
|
||||
@@ -886,7 +890,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
entry, err = s3a.getLatestObjectVersion(bucket, object)
|
||||
if err != nil {
|
||||
glog.Errorf("GetObject: Failed to get latest version for %s/%s: %v", bucket, object, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
} else if errors.Is(versionsErr, filer_pb.ErrNotFound) {
|
||||
@@ -900,7 +904,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
} else {
|
||||
// No object at regular path either - object doesn't exist
|
||||
glog.V(3).Infof("GetObject: object not found at regular path or .versions for %s/%s", bucket, object)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
@@ -909,7 +913,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
entry, err = s3a.getLatestObjectVersion(bucket, object)
|
||||
if err != nil {
|
||||
glog.Errorf("GetObject: Failed to get latest version for %s/%s: %v", bucket, object, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -930,7 +934,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
// Check if this is a delete marker
|
||||
if entry.Extended != nil {
|
||||
if deleteMarker, exists := entry.Extended[s3_constants.ExtDeleteMarkerKey]; exists && string(deleteMarker) == "true" {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -975,7 +979,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
if objectEntryForSSE == nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -992,7 +996,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
// A bare directory path is not an object: 404 like AWS instead of an empty 200,
|
||||
// so Hadoop-style clients fall back to LIST discovery. HEAD and ranged GET already 404.
|
||||
if !strings.HasSuffix(object, "/") && isBareDirectory(objectEntryForSSE) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -2518,7 +2522,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
versioningConfigured, err = s3a.isVersioningConfigured(bucket)
|
||||
if err != nil {
|
||||
if err == filer_pb.ErrNotFound {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchBucket)
|
||||
return
|
||||
}
|
||||
glog.Errorf("Error checking versioning status for bucket %s: %v", bucket, err)
|
||||
@@ -2536,7 +2540,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
if err != nil {
|
||||
glog.Errorf("Failed to get specific version %s for %s/%s: %v", versionId, bucket, object, err)
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchVersion)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchVersion)
|
||||
} else {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
}
|
||||
@@ -2562,7 +2566,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
entry, err = s3a.getLatestObjectVersion(bucket, object)
|
||||
if err != nil {
|
||||
glog.Errorf("HeadObject: Failed to get latest version for %s/%s: %v", bucket, object, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
} else if errors.Is(versionsErr, filer_pb.ErrNotFound) {
|
||||
@@ -2576,7 +2580,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
} else {
|
||||
// No object at regular path either - object doesn't exist
|
||||
glog.V(3).Infof("HeadObject: object not found at regular path or .versions for %s/%s", bucket, object)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
@@ -2585,7 +2589,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
entry, err = s3a.getLatestObjectVersion(bucket, object)
|
||||
if err != nil {
|
||||
glog.Errorf("HeadObject: Failed to get latest version for %s/%s: %v", bucket, object, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -2606,7 +2610,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
// Check if this is a delete marker
|
||||
if entry.Extended != nil {
|
||||
if deleteMarker, exists := entry.Extended[s3_constants.ExtDeleteMarkerKey]; exists && string(deleteMarker) == "true" {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -2644,7 +2648,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
return
|
||||
}
|
||||
if objectEntryForSSE == nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -2710,7 +2714,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
isZeroByteFile := objectEntryForSSE.Attributes.FileSize == 0 && !objectEntryForSSE.IsDirectory
|
||||
// A directory with data (a promoted file) is retrievable; empty directories 404 for LIST fallback.
|
||||
if isBareDirectory(objectEntryForSSE) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
if isZeroByteFile {
|
||||
@@ -2718,7 +2722,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
if s3a.hasChildren(r.Context(), bucket, object) {
|
||||
// This is an implicit directory with children
|
||||
// Return 404 to force clients (like s3fs) to use LIST-based discovery
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// A conditional write with If-Match has nothing to compare against when the key has
|
||||
// no current version; AWS answers 404 there, not 412.
|
||||
func TestValidateConditionalHeadersMissingObject(t *testing.T) {
|
||||
s3a := &S3ApiServer{}
|
||||
|
||||
existing := &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: time.Now().Unix()},
|
||||
Extended: map[string][]byte{s3_constants.ExtETagKey: []byte("d41d8cd98f00b204e9800998ecf8427e")},
|
||||
}
|
||||
deleteMarker := &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: time.Now().Unix()},
|
||||
Extended: map[string][]byte{s3_constants.ExtDeleteMarkerKey: []byte("true")},
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
header string
|
||||
value string
|
||||
entry *filer_pb.Entry
|
||||
want s3err.ErrorCode
|
||||
}{
|
||||
{"if-match on missing object", s3_constants.IfMatch, "d41d8cd98f00b204e9800998ecf8427e", nil, s3err.ErrNoSuchKey},
|
||||
{"if-match star on missing object", s3_constants.IfMatch, "*", nil, s3err.ErrNoSuchKey},
|
||||
{"if-match on delete marker", s3_constants.IfMatch, "d41d8cd98f00b204e9800998ecf8427e", deleteMarker, s3err.ErrNoSuchKey},
|
||||
{"if-match mismatch on existing object", s3_constants.IfMatch, "0000", existing, s3err.ErrPreconditionFailed},
|
||||
{"if-match hit on existing object", s3_constants.IfMatch, "d41d8cd98f00b204e9800998ecf8427e", existing, s3err.ErrNone},
|
||||
{"if-none-match star on missing object", s3_constants.IfNoneMatch, "*", nil, s3err.ErrNone},
|
||||
{"if-none-match star on delete marker", s3_constants.IfNoneMatch, "*", deleteMarker, s3err.ErrNone},
|
||||
{"if-none-match star on existing object", s3_constants.IfNoneMatch, "*", existing, s3err.ErrPreconditionFailed},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
r := httptest.NewRequest(http.MethodPut, "/bucket/object", nil)
|
||||
r.Header.Set(tc.header, tc.value)
|
||||
headers, errCode := parseConditionalHeaders(r)
|
||||
if errCode != s3err.ErrNone {
|
||||
t.Fatalf("parseConditionalHeaders: %v", errCode)
|
||||
}
|
||||
if got := s3a.validateConditionalHeaders(r, headers, tc.entry, "bucket", "object"); got != tc.want {
|
||||
t.Errorf("got %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2796,8 +2796,9 @@ func (s3a *S3ApiServer) validateConditionalHeaders(r *http.Request, headers cond
|
||||
|
||||
// 1. Check If-Match
|
||||
if headers.ifMatch != "" {
|
||||
// AWS answers 404 when there is no current version (or it is a delete marker)
|
||||
if !objectExists {
|
||||
return s3err.ErrPreconditionFailed
|
||||
return s3err.ErrNoSuchKey
|
||||
}
|
||||
// If `ifMatch` is "*", the condition is met if the object exists.
|
||||
// Otherwise, we need to check the ETag.
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/gorilla/mux"
|
||||
iamlib "github.com/seaweedfs/seaweedfs/weed/iam"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -228,6 +229,22 @@ func TestObjectLockActionsRoundTrip(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Anonymous misses must not disclose bucket or key existence: 404 is only
|
||||
// served when anonymous listing is allowed.
|
||||
func TestAnonymousBucketListAuthorization(t *testing.T) {
|
||||
s3a := &S3ApiServer{iam: &IdentityAccessManagement{}, bucketConfigCache: NewBucketConfigCache(time.Minute)}
|
||||
s3a.bucketConfigCache.Set("open", &BucketConfig{Name: "open", IsPublicRead: true})
|
||||
s3a.bucketConfigCache.Set("private", &BucketConfig{Name: "private"})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "http://localhost:8333/open/key", nil)
|
||||
if got := s3a.authorizeAnonymousBucketList(req, "open"); got != s3err.ErrNone {
|
||||
t.Errorf("listable bucket: %v, want ErrNone", got)
|
||||
}
|
||||
if got := s3a.authorizeAnonymousBucketList(req, "private"); got != s3err.ErrAccessDenied {
|
||||
t.Errorf("private bucket: %v, want AccessDenied", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Internal Seaweed-X-Amz-* headers carry server-validated object lock values
|
||||
// into entry metadata; client-supplied ones must be dropped on entry or the
|
||||
// dedicated-permission check on x-amz-object-lock-* is bypassed.
|
||||
|
||||
@@ -27,10 +27,23 @@ const extendedAttributeUpdateAttempts = 5
|
||||
|
||||
// createDirectory creates a new directory at the specified path
|
||||
func (h *S3TablesHandler) createDirectory(ctx context.Context, client filer_pb.SeaweedFilerClient, path string) error {
|
||||
return h.createDirectoryEntry(ctx, client, path, false, nil)
|
||||
}
|
||||
|
||||
// createDirectoryExclusive creates a directory entry together with its
|
||||
// extended attributes in one CreateEntry that fails with
|
||||
// filer_pb.ErrEntryAlreadyExists when an entry is already there: nothing is
|
||||
// replaced and no reader sees the directory without its attributes.
|
||||
func (h *S3TablesHandler) createDirectoryExclusive(ctx context.Context, client filer_pb.SeaweedFilerClient, path string, extended map[string][]byte) error {
|
||||
return h.createDirectoryEntry(ctx, client, path, true, extended)
|
||||
}
|
||||
|
||||
func (h *S3TablesHandler) createDirectoryEntry(ctx context.Context, client filer_pb.SeaweedFilerClient, path string, exclusive bool, extended map[string][]byte) error {
|
||||
dir, name := splitPath(path)
|
||||
now := time.Now().Unix()
|
||||
return filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{
|
||||
Directory: dir,
|
||||
OExcl: exclusive,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: name,
|
||||
IsDirectory: true,
|
||||
@@ -39,6 +52,7 @@ func (h *S3TablesHandler) createDirectory(ctx context.Context, client filer_pb.S
|
||||
Crtime: now,
|
||||
FileMode: uint32(0755 | os.ModeDir),
|
||||
},
|
||||
Extended: extended,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package s3tables
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// competingCreateClient lands a foreign entry where the handler's existence
|
||||
// check just answered "not there": the create that follows must lose to it
|
||||
// rather than replace it, the way a second caller's create wins the window in
|
||||
// a check-then-create race.
|
||||
type competingCreateClient struct {
|
||||
filer_pb.SeaweedFilerClient
|
||||
f *s3tablestest.MemFiler
|
||||
dir string
|
||||
name string
|
||||
plant bool
|
||||
}
|
||||
|
||||
func (c *competingCreateClient) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest, opts ...grpc.CallOption) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
resp, err := c.SeaweedFilerClient.LookupDirectoryEntry(ctx, req, opts...)
|
||||
if c.plant && err != nil && req.Directory == c.dir && req.Name == c.name {
|
||||
c.plant = false
|
||||
c.f.Put(c.dir, c.name, map[string][]byte{
|
||||
ExtendedKeyTableBucket: []byte("true"),
|
||||
ExtendedKeyMetadata: []byte(`{"OwnerAccountID":"competitor"}`),
|
||||
})
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func runHandler(t *testing.T, m *Manager, client filer_pb.SeaweedFilerClient, operation string, input interface{}) (int, S3TablesError) {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(input)
|
||||
require.NoError(t, err)
|
||||
req, err := newManagerRequest(context.Background(), operation, body, "admin")
|
||||
require.NoError(t, err)
|
||||
recorder := httptest.NewRecorder()
|
||||
m.handler.HandleRequest(recorder, req, NewManagerClient(client))
|
||||
result := recorder.Result()
|
||||
defer result.Body.Close()
|
||||
var response S3TablesError
|
||||
json.NewDecoder(result.Body).Decode(&response)
|
||||
return result.StatusCode, response
|
||||
}
|
||||
|
||||
func TestCreateTableBucketLostRaceKeepsTheFirstCreate(t *testing.T) {
|
||||
fs := s3tablestest.Start(t)
|
||||
m := NewManager()
|
||||
client := &competingCreateClient{SeaweedFilerClient: fs.Client, f: fs, dir: TablesPath, name: "bucket", plant: true}
|
||||
|
||||
status, resp := runHandler(t, m, client, "CreateTableBucket", &CreateTableBucketRequest{Name: "bucket"})
|
||||
assert.Equal(t, http.StatusConflict, status)
|
||||
assert.Equal(t, ErrCodeBucketAlreadyExists, resp.Type)
|
||||
|
||||
survivor := fs.Get(TablesPath, "bucket")
|
||||
require.NotNil(t, survivor)
|
||||
assert.Equal(t, `{"OwnerAccountID":"competitor"}`, string(survivor.Extended[ExtendedKeyMetadata]))
|
||||
}
|
||||
|
||||
func TestCreateNamespaceLostRaceKeepsTheFirstCreate(t *testing.T) {
|
||||
fs := s3tablestest.Start(t)
|
||||
m := NewManager()
|
||||
bucketMetadata, _ := json.Marshal(&tableBucketMetadata{Name: "bucket", OwnerAccountID: DefaultAccountID})
|
||||
fs.Put(TablesPath, "bucket", map[string][]byte{ExtendedKeyTableBucket: []byte("true"), ExtendedKeyMetadata: bucketMetadata})
|
||||
|
||||
arn, err := BuildBucketARN(DefaultRegion, DefaultAccountID, "bucket")
|
||||
require.NoError(t, err)
|
||||
client := &competingCreateClient{SeaweedFilerClient: fs.Client, f: fs, dir: GetTableBucketPath("bucket"), name: "ns", plant: true}
|
||||
status, resp := runHandler(t, m, client, "CreateNamespace", &CreateNamespaceRequest{
|
||||
TableBucketARN: arn,
|
||||
Namespace: []string{"ns"},
|
||||
})
|
||||
assert.Equal(t, http.StatusConflict, status)
|
||||
assert.Equal(t, ErrCodeNamespaceAlreadyExists, resp.Type)
|
||||
|
||||
survivor := fs.Get(GetTableBucketPath("bucket"), "ns")
|
||||
require.NotNil(t, survivor)
|
||||
assert.Equal(t, `{"OwnerAccountID":"competitor"}`, string(survivor.Extended[ExtendedKeyMetadata]))
|
||||
}
|
||||
@@ -140,6 +140,7 @@ func (h *S3TablesHandler) handleCreateTableBucket(w http.ResponseWriter, r *http
|
||||
return err
|
||||
}
|
||||
|
||||
var taken error
|
||||
err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
// Ensure root tables directory exists
|
||||
if !h.entryExists(r.Context(), client, TablesPath) {
|
||||
@@ -148,35 +149,35 @@ func (h *S3TablesHandler) handleCreateTableBucket(w http.ResponseWriter, r *http
|
||||
}
|
||||
}
|
||||
|
||||
// Create bucket directory
|
||||
if err := h.createDirectory(r.Context(), client, bucketPath); err != nil {
|
||||
return err
|
||||
extended := map[string][]byte{
|
||||
ExtendedKeyTableBucket: []byte("true"),
|
||||
ExtendedKeyMetadata: metadataBytes,
|
||||
}
|
||||
|
||||
// Mark as a table bucket
|
||||
if err := h.setExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyTableBucket, []byte("true")); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Set metadata as extended attribute
|
||||
if err := h.setExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyMetadata, metadataBytes); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Set tags if provided
|
||||
if len(req.Tags) > 0 {
|
||||
tagsBytes, err := json.Marshal(req.Tags)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal tags: %w", err)
|
||||
}
|
||||
if err := h.setExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyTags, tagsBytes); err != nil {
|
||||
return err
|
||||
extended[ExtendedKeyTags] = tagsBytes
|
||||
}
|
||||
if err := h.createDirectoryExclusive(r.Context(), client, bucketPath, extended); err != nil {
|
||||
if errors.Is(err, filer_pb.ErrEntryAlreadyExists) {
|
||||
taken = err // an answer, not a filer failure
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err == nil && taken != nil {
|
||||
err = taken
|
||||
}
|
||||
|
||||
if errors.Is(err, filer_pb.ErrEntryAlreadyExists) {
|
||||
h.writeError(w, http.StatusConflict, ErrCodeBucketAlreadyExists, fmt.Sprintf("table bucket %s already exists", req.Name))
|
||||
return err
|
||||
}
|
||||
if err != nil {
|
||||
glog.Errorf("S3Tables: failed to create table bucket %s: %v", req.Name, err)
|
||||
h.writeError(w, http.StatusInternalServerError, ErrCodeInternalError, "failed to create table bucket")
|
||||
|
||||
@@ -11,8 +11,29 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
// errOwnerlessBucket marks a table bucket that has the marker but no
|
||||
// metadata: damaged, and answered with the operation's own denial rather than
|
||||
// letting the caller name itself the bucket's owner before any check runs.
|
||||
var errOwnerlessBucket = fmt.Errorf("table bucket has no owner metadata")
|
||||
|
||||
// mayRepairOwnerlessBucket reports whether the caller may repair a bucket in
|
||||
// that state: the admin or a trusted internal handler. hasAdminAction also
|
||||
// answers s3tables:*, an operation grant, not administrator status.
|
||||
func (h *S3TablesHandler) mayRepairOwnerlessBucket(r *http.Request) bool {
|
||||
if h.trusted || h.getAccountID(r) == s3_constants.AccountAdminId {
|
||||
return true
|
||||
}
|
||||
for _, action := range getIdentityActions(r) {
|
||||
if action == s3_constants.ACTION_ADMIN {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// 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")
|
||||
@@ -66,16 +87,29 @@ func (h *S3TablesHandler) handleCreateNamespace(w http.ResponseWriter, r *http.R
|
||||
if entryResp.Entry == nil || !IsTableBucketEntry(entryResp.Entry) {
|
||||
return filer_pb.ErrNotFound
|
||||
}
|
||||
bucketMetadata = tableBucketMetadata{
|
||||
Name: bucketName,
|
||||
CreatedAt: time.Now(),
|
||||
OwnerAccountID: ownerAccountID,
|
||||
if !h.mayRepairOwnerlessBucket(r) {
|
||||
return errOwnerlessBucket
|
||||
}
|
||||
metadataBytes, err := json.Marshal(&bucketMetadata)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal bucket metadata: %w", err)
|
||||
}
|
||||
if err := h.setExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyMetadata, metadataBytes); err != nil {
|
||||
// Repair the marker-only entry under the entry lock so a
|
||||
// creator finishing its own create in the meantime keeps its
|
||||
// owner: adopt whatever metadata is there, write only when it
|
||||
// is still absent.
|
||||
if err := h.mutateEntryExtended(r.Context(), client, bucketPath, func(extended map[string][]byte) error {
|
||||
if data, ok := extended[ExtendedKeyMetadata]; ok {
|
||||
return json.Unmarshal(data, &bucketMetadata)
|
||||
}
|
||||
bucketMetadata = tableBucketMetadata{
|
||||
Name: bucketName,
|
||||
CreatedAt: time.Now(),
|
||||
OwnerAccountID: ownerAccountID,
|
||||
}
|
||||
metadataBytes, err := json.Marshal(&bucketMetadata)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal bucket metadata: %w", err)
|
||||
}
|
||||
extended[ExtendedKeyMetadata] = metadataBytes
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
@@ -101,6 +135,10 @@ func (h *S3TablesHandler) handleCreateNamespace(w http.ResponseWriter, r *http.R
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, errOwnerlessBucket) {
|
||||
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to create namespace in this bucket")
|
||||
return ErrAccessDenied
|
||||
}
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
h.writeError(w, http.StatusNotFound, ErrCodeNoSuchBucket, fmt.Sprintf("table bucket %s not found", bucketName))
|
||||
} else {
|
||||
@@ -159,20 +197,22 @@ func (h *S3TablesHandler) handleCreateNamespace(w http.ResponseWriter, r *http.R
|
||||
return fmt.Errorf("failed to marshal metadata: %w", err)
|
||||
}
|
||||
|
||||
var taken error
|
||||
err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
// Create namespace directory
|
||||
if err := h.createDirectory(r.Context(), client, namespacePath); err != nil {
|
||||
return err
|
||||
err := h.createDirectoryExclusive(r.Context(), client, namespacePath, map[string][]byte{ExtendedKeyMetadata: metadataBytes})
|
||||
if errors.Is(err, filer_pb.ErrEntryAlreadyExists) {
|
||||
taken = err // an answer, not a filer failure
|
||||
return nil
|
||||
}
|
||||
|
||||
// Set metadata as extended attribute
|
||||
if err := h.setExtendedAttribute(r.Context(), client, namespacePath, ExtendedKeyMetadata, metadataBytes); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
return err
|
||||
})
|
||||
|
||||
if err == nil && taken != nil {
|
||||
err = taken
|
||||
}
|
||||
if errors.Is(err, filer_pb.ErrEntryAlreadyExists) {
|
||||
h.writeError(w, http.StatusConflict, ErrCodeNamespaceAlreadyExists, fmt.Sprintf("namespace %s already exists", namespaceName))
|
||||
return err
|
||||
}
|
||||
if err != nil {
|
||||
h.writeError(w, http.StatusInternalServerError, ErrCodeInternalError, "failed to create namespace")
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package s3tables
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// A table bucket with the marker but no metadata is damaged, not ownerless for
|
||||
// the taking: an ordinary caller is answered with the operation's own denial,
|
||||
// and the admin or a trusted handler may repair it.
|
||||
func TestCreateNamespaceOnAnOwnerlessBucket(t *testing.T) {
|
||||
const bucket = "broken"
|
||||
plant := func(fs *s3tablestest.MemFiler) {
|
||||
fs.Put(TablesPath, bucket, map[string][]byte{ExtendedKeyTableBucket: []byte("true")})
|
||||
}
|
||||
arn, err := BuildBucketARN(DefaultRegion, DefaultAccountID, bucket)
|
||||
require.NoError(t, err)
|
||||
request := &CreateNamespaceRequest{TableBucketARN: arn, Namespace: []string{"ns"}}
|
||||
|
||||
t.Run("an outsider gets the denial and writes nothing", func(t *testing.T) {
|
||||
fs := s3tablestest.Start(t)
|
||||
plant(fs)
|
||||
m := NewManager()
|
||||
body, err := json.Marshal(request)
|
||||
require.NoError(t, err)
|
||||
identity := &testIdentity{Name: "outsider", Account: &testIdentityAccount{Id: "outsider"}, Actions: []string{"Read"}}
|
||||
req, err := newManagerRequest(s3_constants.SetIdentityInContext(context.Background(), identity), "CreateNamespace", body, "outsider")
|
||||
require.NoError(t, err)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
m.handler.HandleRequest(recorder, req, NewManagerClient(fs.Client))
|
||||
assert.Equal(t, http.StatusForbidden, recorder.Code, recorder.Body.String())
|
||||
entry := fs.Get(TablesPath, bucket)
|
||||
require.NotNil(t, entry)
|
||||
assert.Empty(t, entry.Extended[ExtendedKeyMetadata], "the denied caller wrote itself in as the bucket owner")
|
||||
assert.Nil(t, fs.Get(GetTableBucketPath(bucket), "ns"))
|
||||
})
|
||||
|
||||
t.Run("a trusted handler repairs it and owns it", func(t *testing.T) {
|
||||
fs := s3tablestest.Start(t)
|
||||
plant(fs)
|
||||
m := NewManager()
|
||||
m.SetTrusted(true)
|
||||
body, err := json.Marshal(request)
|
||||
require.NoError(t, err)
|
||||
identity := &testIdentity{Name: "svc", Account: &testIdentityAccount{Id: "svc"}, Actions: []string{"Read"}}
|
||||
req, err := newManagerRequest(s3_constants.SetIdentityInContext(context.Background(), identity), "CreateNamespace", body, "svc")
|
||||
require.NoError(t, err)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
m.handler.HandleRequest(recorder, req, NewManagerClient(fs.Client))
|
||||
assert.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
|
||||
entry := fs.Get(TablesPath, bucket)
|
||||
require.NotNil(t, entry)
|
||||
var metadata tableBucketMetadata
|
||||
require.NoError(t, json.Unmarshal(entry.Extended[ExtendedKeyMetadata], &metadata))
|
||||
assert.Equal(t, "svc", metadata.OwnerAccountID)
|
||||
require.NotNil(t, fs.Get(GetTableBucketPath(bucket), "ns"))
|
||||
})
|
||||
|
||||
t.Run("an untrusted admin repairs it too", func(t *testing.T) {
|
||||
fs := s3tablestest.Start(t)
|
||||
plant(fs)
|
||||
m := NewManager()
|
||||
body, err := json.Marshal(request)
|
||||
require.NoError(t, err)
|
||||
identity := &testIdentity{Name: "admin", Account: &testIdentityAccount{Id: s3_constants.AccountAdminId}, Actions: []string{"Admin"}}
|
||||
req, err := newManagerRequest(s3_constants.SetIdentityInContext(context.Background(), identity), "CreateNamespace", body, "admin")
|
||||
require.NoError(t, err)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
m.handler.HandleRequest(recorder, req, NewManagerClient(fs.Client))
|
||||
assert.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
|
||||
entry := fs.Get(TablesPath, bucket)
|
||||
require.NotNil(t, entry)
|
||||
var metadata tableBucketMetadata
|
||||
require.NoError(t, json.Unmarshal(entry.Extended[ExtendedKeyMetadata], &metadata))
|
||||
assert.Equal(t, s3_constants.AccountAdminId, metadata.OwnerAccountID)
|
||||
})
|
||||
}
|
||||
@@ -15,7 +15,9 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/maintenance"
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/telemetry"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
@@ -28,6 +30,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/sequence"
|
||||
"github.com/seaweedfs/seaweedfs/weed/shell"
|
||||
@@ -162,6 +165,22 @@ func NewMasterServer(r *mux.Router, option *MasterOption, peers map[string]pb.Se
|
||||
ms.Topo.SetGrowthFreezeConfig(
|
||||
v.GetBool("master.volume_growth.freeze_on_topology_mismatch"),
|
||||
v.GetDuration("master.volume_growth.state_loss_recovery_wait"))
|
||||
ms.Topo.QuarantineVolumeFn = func(dn *topology.DataNode, vid needle.VolumeId, readOnly bool) error {
|
||||
err := operation.WithVolumeServerClient(false, dn.ServerAddress(), ms.grpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if readOnly {
|
||||
_, err := client.VolumeMarkReadonly(ctx, &volume_server_pb.VolumeMarkReadonlyRequest{VolumeId: uint32(vid), CanDelete: true})
|
||||
return err
|
||||
}
|
||||
_, err := client.VolumeMarkWritable(ctx, &volume_server_pb.VolumeMarkWritableRequest{VolumeId: uint32(vid)})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
glog.Warningf("quarantine volume %d on %s readOnly=%v: %v", vid, dn.Id(), readOnly, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
ms.vg = topology.NewDefaultVolumeGrowth()
|
||||
glog.V(0).Infoln("Volume Size Limit is", ms.option.VolumeSizeLimitMB, "MB")
|
||||
|
||||
|
||||
@@ -54,6 +54,22 @@ func (vs *VolumeServer) lookupRaftLeaderMaster(ctx context.Context) (pb.ServerAd
|
||||
return leader, nil
|
||||
}
|
||||
|
||||
// refreshLeaderFromPeers publishes the leader the configured masters report,
|
||||
// so lookups stop going to a master the heartbeat just lost while the loop
|
||||
// retries. Without an answer within timeout no leader is published: the lost
|
||||
// master is dead or no longer leader, and a follower answers lookups from its
|
||||
// own cache rather than refusing them, so failing fast is the safer answer.
|
||||
func (vs *VolumeServer) refreshLeaderFromPeers(timeout time.Duration) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
leader, err := vs.lookupRaftLeaderMaster(ctx)
|
||||
if err != nil {
|
||||
vs.setCurrentMaster("")
|
||||
return
|
||||
}
|
||||
vs.setCurrentMaster(leader)
|
||||
}
|
||||
|
||||
func isContextDoneErr(err error) bool {
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return true
|
||||
@@ -74,7 +90,10 @@ func (vs *VolumeServer) getCurrentMaster() pb.ServerAddress {
|
||||
}
|
||||
|
||||
// setCurrentMaster updates vs.currentMaster under a write lock. The
|
||||
// heartbeat goroutine calls this whenever it (re)connects to a master.
|
||||
// heartbeat goroutine calls this only with a master known to be the leader:
|
||||
// one that answered a heartbeat as leader, or the one a follower named, on
|
||||
// the heartbeat stream or, after the stream failed, in its configuration.
|
||||
// After a failed stream with no leader named, it is cleared to "".
|
||||
func (vs *VolumeServer) setCurrentMaster(master pb.ServerAddress) {
|
||||
vs.currentMasterLock.Lock()
|
||||
vs.currentMaster = master
|
||||
@@ -122,7 +141,6 @@ func (vs *VolumeServer) heartbeat() {
|
||||
time.Sleep(3 * time.Second)
|
||||
master = newLeader
|
||||
}
|
||||
vs.store.MasterAddress = master
|
||||
newLeader, err = vs.doHeartbeatWithRetry(master, grpcDialOption, vs.pulsePeriod, duplicateRetryCount)
|
||||
if err != nil {
|
||||
glog.V(0).Infof("heartbeat to %s error: %v", master, err)
|
||||
@@ -136,12 +154,15 @@ func (vs *VolumeServer) heartbeat() {
|
||||
} else {
|
||||
// Regular error, reset duplicate retry count
|
||||
duplicateRetryCount = 0
|
||||
time.Sleep(vs.pulsePeriod)
|
||||
// The lookup spends part of the retry delay rather than
|
||||
// adding to it.
|
||||
retryAt := time.Now().Add(vs.pulsePeriod)
|
||||
vs.refreshLeaderFromPeers(vs.pulsePeriod)
|
||||
time.Sleep(time.Until(retryAt))
|
||||
}
|
||||
|
||||
stats.VolumeServerMasterDisconnections.WithLabelValues(master.String()).Inc()
|
||||
newLeader = ""
|
||||
vs.store.MasterAddress = ""
|
||||
} else {
|
||||
// Successful connection, reset retry count
|
||||
duplicateRetryCount = 0
|
||||
@@ -180,17 +201,42 @@ func (vs *VolumeServer) doHeartbeatWithRetry(masterAddress pb.ServerAddress, grp
|
||||
return "", err
|
||||
}
|
||||
glog.V(0).Infof("Heartbeat to: %v", masterAddress)
|
||||
vs.setCurrentMaster(masterAddress)
|
||||
|
||||
doneChan := make(chan error, 1)
|
||||
// The receiver asks for a fresh heartbeat here rather than sending it,
|
||||
// since a gRPC stream allows only one sender at a time.
|
||||
resendChan := make(chan struct{}, 1)
|
||||
|
||||
go func() {
|
||||
confirmedLeader := false
|
||||
for {
|
||||
in, err := stream.Recv()
|
||||
if err != nil {
|
||||
doneChan <- err
|
||||
return
|
||||
}
|
||||
// A reply names the leader or comes from it, so it settles where
|
||||
// lookups go before anything else on the reply is handled: a
|
||||
// follower reply carries no other fields, and a leader stays the
|
||||
// lookup target even when it rejects this registration.
|
||||
if in.GetLeader() != "" {
|
||||
// Only a follower names the leader. Publish the named leader right
|
||||
// away, so lookups stop landing on this follower while the loop
|
||||
// reconnects.
|
||||
leader := pb.ServerAddress(in.GetLeader())
|
||||
if !masterAddress.Equals(leader) {
|
||||
glog.V(0).Infof("Volume Server found a new master newLeader: %v instead of %v", leader, masterAddress)
|
||||
vs.setCurrentMaster(leader)
|
||||
newLeader = leader
|
||||
doneChan <- nil
|
||||
return
|
||||
}
|
||||
} else if !confirmedLeader {
|
||||
// The leader answers every new heartbeat stream without naming a
|
||||
// leader, so this peer is the one lookups should go to.
|
||||
confirmedLeader = true
|
||||
vs.setCurrentMaster(masterAddress)
|
||||
}
|
||||
if len(in.DuplicatedUuids) > 0 {
|
||||
var duplicateDir []string
|
||||
for _, loc := range vs.store.Locations {
|
||||
@@ -231,9 +277,9 @@ func (vs *VolumeServer) doHeartbeatWithRetry(masterAddress pb.ServerAddress, grp
|
||||
}
|
||||
if volumeOptsChanged {
|
||||
if vs.store.MaybeAdjustVolumeMax() {
|
||||
if err = stream.Send(vs.store.CollectHeartbeat()); err != nil {
|
||||
glog.V(0).Infof("Volume Server Failed to talk with master %s: %v", vs.getCurrentMaster(), err)
|
||||
return
|
||||
select {
|
||||
case resendChan <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -244,15 +290,6 @@ func (vs *VolumeServer) doHeartbeatWithRetry(masterAddress pb.ServerAddress, grp
|
||||
glog.V(0).Infof("master %s asked for the full volume list", masterAddress)
|
||||
vs.store.RequestFullVolumeList()
|
||||
}
|
||||
if in.GetLeader() != "" {
|
||||
current := vs.getCurrentMaster()
|
||||
if !current.Equals(pb.ServerAddress(in.GetLeader())) {
|
||||
glog.V(0).Infof("Volume Server found a new master newLeader: %v instead of %v", in.GetLeader(), current)
|
||||
newLeader = pb.ServerAddress(in.GetLeader())
|
||||
doneChan <- nil
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -359,6 +396,11 @@ func (vs *VolumeServer) doHeartbeatWithRetry(masterAddress pb.ServerAddress, grp
|
||||
glog.V(0).Infof("Volume Server Failed to update to master %s: %v", masterAddress, err)
|
||||
return "", err
|
||||
}
|
||||
case <-resendChan:
|
||||
if err = stream.Send(vs.store.CollectHeartbeat()); err != nil {
|
||||
glog.V(0).Infof("Volume Server Failed to talk with master %s: %v", masterAddress, err)
|
||||
return "", err
|
||||
}
|
||||
case <-volumeTickChan.C:
|
||||
glog.V(4).Infof("volume server %s:%d heartbeat", vs.store.Ip, vs.store.Port)
|
||||
vs.store.MaybeAdjustVolumeMax()
|
||||
|
||||
@@ -4,11 +4,17 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
@@ -60,3 +66,279 @@ func startFakeMasterServerForLeaderLookup(t *testing.T, srv master_pb.SeaweedSer
|
||||
_, port, _ := net.SplitHostPort(lis.Addr().String())
|
||||
return pb.ServerAddress(fmt.Sprintf("127.0.0.1:0.%s", port))
|
||||
}
|
||||
|
||||
// fakeHeartbeatMaster answers SendHeartbeat the way a master does: a follower
|
||||
// names the leader on every heartbeat, the leader answers the first one with
|
||||
// its volume options and never names itself.
|
||||
type fakeHeartbeatMaster struct {
|
||||
master_pb.UnimplementedSeaweedServer
|
||||
leader string // set on a follower
|
||||
release chan struct{} // a follower waits on it before answering
|
||||
heartbeats chan *master_pb.Heartbeat
|
||||
}
|
||||
|
||||
func (m *fakeHeartbeatMaster) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServer) error {
|
||||
answered := false
|
||||
for {
|
||||
hb, err := stream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if m.heartbeats != nil {
|
||||
m.heartbeats <- hb
|
||||
}
|
||||
if m.leader != "" {
|
||||
if m.release != nil {
|
||||
<-m.release
|
||||
}
|
||||
if err := stream.Send(&master_pb.HeartbeatResponse{Leader: m.leader}); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !answered {
|
||||
answered = true
|
||||
if err := stream.Send(&master_pb.HeartbeatResponse{VolumeSizeLimit: 1 << 30}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newHeartbeatTestVolumeServer(t *testing.T) *VolumeServer {
|
||||
t.Helper()
|
||||
store := storage.NewStore(nil, "127.0.0.1", 8080, 18080, "http://127.0.0.1:8080", "store-id",
|
||||
[]string{t.TempDir()},
|
||||
[]int32{0},
|
||||
[]util.MinFreeSpace{{}},
|
||||
"",
|
||||
storage.NeedleMapInMemory,
|
||||
[]types.DiskType{types.HardDriveType},
|
||||
nil,
|
||||
3,
|
||||
stats.DefaultDiskIOProbeConfig(),
|
||||
)
|
||||
t.Cleanup(store.Close)
|
||||
vs := &VolumeServer{
|
||||
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
store: store,
|
||||
stopChan: make(chan bool),
|
||||
isHeartbeating: true,
|
||||
}
|
||||
store.MasterFn = vs.getCurrentMaster
|
||||
return vs
|
||||
}
|
||||
|
||||
func waitForCurrentMaster(t *testing.T, vs *VolumeServer, want pb.ServerAddress) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !vs.getCurrentMaster().Equals(want) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("currentMaster = %q, want %q", vs.getCurrentMaster(), want)
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// heartbeatRun is one doHeartbeatWithRetry call running in the background.
|
||||
type heartbeatRun struct {
|
||||
done chan heartbeatResult // receives the call's result once
|
||||
exited chan struct{}
|
||||
stop func()
|
||||
}
|
||||
|
||||
type heartbeatResult struct {
|
||||
newLeader pb.ServerAddress
|
||||
err error
|
||||
}
|
||||
|
||||
// startHeartbeat runs doHeartbeatWithRetry against master until it returns or
|
||||
// is stopped. Its cleanup stops the heartbeat and waits for it, and runs before
|
||||
// the cleanups registered earlier, so a failed assertion cannot leave the stream
|
||||
// open for the fake master's GracefulStop to wait on.
|
||||
func startHeartbeat(t *testing.T, vs *VolumeServer, master pb.ServerAddress) *heartbeatRun {
|
||||
t.Helper()
|
||||
var stopOnce sync.Once
|
||||
run := &heartbeatRun{
|
||||
done: make(chan heartbeatResult, 1),
|
||||
exited: make(chan struct{}),
|
||||
stop: func() { stopOnce.Do(func() { close(vs.stopChan) }) },
|
||||
}
|
||||
go func() {
|
||||
defer close(run.exited)
|
||||
newLeader, err := vs.doHeartbeatWithRetry(master, vs.grpcDialOption, time.Hour, 0)
|
||||
run.done <- heartbeatResult{newLeader, err}
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
run.stop()
|
||||
select {
|
||||
case <-run.exited:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("heartbeat did not stop")
|
||||
}
|
||||
})
|
||||
return run
|
||||
}
|
||||
|
||||
// A follower must never become the master lookups go to: until it names the
|
||||
// leader the previous one stays, and then the named leader takes over before
|
||||
// the heartbeat loop has reconnected.
|
||||
func TestHeartbeatToFollowerPublishesNamedLeaderOnly(t *testing.T) {
|
||||
const leader = pb.ServerAddress("leader.example.com:9333.19333")
|
||||
follower := &fakeHeartbeatMaster{
|
||||
leader: string(leader),
|
||||
release: make(chan struct{}),
|
||||
heartbeats: make(chan *master_pb.Heartbeat, 8),
|
||||
}
|
||||
followerAddr := startFakeMasterServerForLeaderLookup(t, follower)
|
||||
// cleanups run last-in first-out, so a failed assertion still lets the
|
||||
// follower answer before its server stops gracefully
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(follower.release) }) }
|
||||
t.Cleanup(release)
|
||||
|
||||
vs := newHeartbeatTestVolumeServer(t)
|
||||
previous := pb.ServerAddress("previous.example.com:9333.19333")
|
||||
vs.setCurrentMaster(previous)
|
||||
run := startHeartbeat(t, vs, followerAddr)
|
||||
|
||||
select {
|
||||
case <-follower.heartbeats:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("follower got no heartbeat")
|
||||
}
|
||||
if got := vs.getCurrentMaster(); got != previous {
|
||||
t.Fatalf("currentMaster = %q while connected to follower %q, want unchanged %q", string(got), string(followerAddr), string(previous))
|
||||
}
|
||||
if got := vs.store.MasterFn(); got != previous {
|
||||
t.Fatalf("store master = %q, want %q", got, previous)
|
||||
}
|
||||
release()
|
||||
|
||||
select {
|
||||
case r := <-run.done:
|
||||
if r.err != nil {
|
||||
t.Fatalf("heartbeat: %v", r.err)
|
||||
}
|
||||
if r.newLeader != leader {
|
||||
t.Fatalf("newLeader = %q, want %q", r.newLeader, leader)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("heartbeat did not return after the follower named the leader")
|
||||
}
|
||||
if got := vs.getCurrentMaster(); got != leader {
|
||||
t.Fatalf("currentMaster = %q, want named leader %q", got, leader)
|
||||
}
|
||||
}
|
||||
|
||||
// The leader's first answer confirms it, and the size limit that answer carries
|
||||
// makes the receiver ask for a fresh heartbeat, which the send loop delivers.
|
||||
func TestHeartbeatToLeaderPublishesItAndResendsFromSendLoop(t *testing.T) {
|
||||
leader := &fakeHeartbeatMaster{heartbeats: make(chan *master_pb.Heartbeat, 8)}
|
||||
leaderAddr := startFakeMasterServerForLeaderLookup(t, leader)
|
||||
|
||||
vs := newHeartbeatTestVolumeServer(t)
|
||||
run := startHeartbeat(t, vs, leaderAddr)
|
||||
|
||||
waitForCurrentMaster(t, vs, leaderAddr)
|
||||
if got := vs.store.MasterFn(); got != leaderAddr {
|
||||
t.Fatalf("store master = %q, want %q", got, leaderAddr)
|
||||
}
|
||||
|
||||
// the initial volume and ec heartbeats, then the resend
|
||||
for i := 0; i < 3; i++ {
|
||||
select {
|
||||
case <-leader.heartbeats:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("leader got %d heartbeats, want 3", i)
|
||||
}
|
||||
}
|
||||
|
||||
run.stop()
|
||||
select {
|
||||
case r := <-run.done:
|
||||
if r.err != nil {
|
||||
t.Fatalf("heartbeat: %v", r.err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("heartbeat did not stop")
|
||||
}
|
||||
}
|
||||
|
||||
// duplicateUUIDMaster answers every heartbeat the way a leader holding a stale
|
||||
// registration does: a duplicate-uuid response and nothing else.
|
||||
type duplicateUUIDMaster struct {
|
||||
master_pb.UnimplementedSeaweedServer
|
||||
}
|
||||
|
||||
func (m *duplicateUUIDMaster) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServer) error {
|
||||
for {
|
||||
if _, err := stream.Recv(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := stream.Send(&master_pb.HeartbeatResponse{DuplicatedUuids: []string{"uuid-1"}}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A leader that rejects the registration over duplicate uuids still answers
|
||||
// lookups, so it is published before the retry error goes out.
|
||||
func TestHeartbeatPublishesLeaderBeforeDuplicateUuidError(t *testing.T) {
|
||||
masterAddr := startFakeMasterServerForLeaderLookup(t, &duplicateUUIDMaster{})
|
||||
vs := newHeartbeatTestVolumeServer(t)
|
||||
vs.setCurrentMaster("previous.example.com:9333.19333")
|
||||
|
||||
_, err := vs.doHeartbeatWithRetry(masterAddr, vs.grpcDialOption, time.Hour, 0)
|
||||
if err == nil || !strings.Contains(err.Error(), "duplicate UUIDs") {
|
||||
t.Fatalf("err = %v, want duplicate UUIDs", err)
|
||||
}
|
||||
if got := vs.getCurrentMaster(); got != masterAddr {
|
||||
t.Fatalf("currentMaster = %q, want the answering leader %q", got, masterAddr)
|
||||
}
|
||||
}
|
||||
|
||||
// After the heartbeat loses its master, lookups move to the leader the other
|
||||
// masters report instead of dialing the lost one until a new stream answers.
|
||||
func TestRefreshLeaderFromPeersPublishesReportedLeader(t *testing.T) {
|
||||
const leader = pb.ServerAddress("leader.example.com:9333.19333")
|
||||
peer := startFakeMasterServerForLeaderLookup(t, &fakeLeaderConfigServer{leader: string(leader)})
|
||||
vs := &VolumeServer{
|
||||
SeedMasterNodes: []pb.ServerAddress{peer},
|
||||
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
store: &storage.Store{Ip: "127.0.0.1", Port: 8080},
|
||||
}
|
||||
vs.store.MasterFn = vs.getCurrentMaster
|
||||
vs.setCurrentMaster("lost.example.com:9333.19333")
|
||||
|
||||
vs.refreshLeaderFromPeers(5 * time.Second)
|
||||
|
||||
if got := vs.getCurrentMaster(); got != leader {
|
||||
t.Fatalf("currentMaster = %q, want reported leader %q", string(got), string(leader))
|
||||
}
|
||||
if got := vs.store.MasterFn(); got != leader {
|
||||
t.Fatalf("store master = %q, want %q", string(got), string(leader))
|
||||
}
|
||||
}
|
||||
|
||||
// Mid-election no master names a leader. The lost master is dead or now a
|
||||
// follower that would answer lookups from its own cache, so none is published.
|
||||
func TestRefreshLeaderFromPeersClearsLeaderWithoutAnswer(t *testing.T) {
|
||||
peer := startFakeMasterServerForLeaderLookup(t, &fakeLeaderConfigServer{})
|
||||
vs := &VolumeServer{
|
||||
SeedMasterNodes: []pb.ServerAddress{peer},
|
||||
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
store: &storage.Store{Ip: "127.0.0.1", Port: 8080},
|
||||
}
|
||||
vs.store.MasterFn = vs.getCurrentMaster
|
||||
vs.setCurrentMaster("lost.example.com:9333.19333")
|
||||
|
||||
vs.refreshLeaderFromPeers(5 * time.Second)
|
||||
|
||||
if got := vs.getCurrentMaster(); got != "" {
|
||||
t.Fatalf("currentMaster = %q, want none", string(got))
|
||||
}
|
||||
if got := vs.store.MasterFn(); got != "" {
|
||||
t.Fatalf("store master = %q, want none", string(got))
|
||||
}
|
||||
}
|
||||
@@ -148,6 +148,7 @@ func NewVolumeServer(adminMux, publicMux *http.ServeMux, ip string,
|
||||
vs.checkWithMaster()
|
||||
|
||||
vs.store = storage.NewStore(vs.grpcDialOption, ip, port, grpcPort, publicUrl, id, folders, maxCounts, minFreeSpaces, idxFolder, vs.needleMapKind, diskTypes, diskTags, ldbTimeout, diskProbeConfig)
|
||||
vs.store.MasterFn = vs.getCurrentMaster
|
||||
vs.guard = security.NewGuard(whiteList, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec)
|
||||
|
||||
handleStaticResources(adminMux)
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Commands = append(Commands, &commandVolumeCheckDuplicateIds{})
|
||||
}
|
||||
|
||||
type commandVolumeCheckDuplicateIds struct {
|
||||
}
|
||||
|
||||
func (c *commandVolumeCheckDuplicateIds) Name() string {
|
||||
return "volume.check.duplicate_ids"
|
||||
}
|
||||
|
||||
func (c *commandVolumeCheckDuplicateIds) Help() string {
|
||||
return `find volume ids registered under more than one layout
|
||||
|
||||
volume.check.duplicate_ids
|
||||
|
||||
Volume ids are global. The same id under two collections, replica
|
||||
placements, TTLs, or disk types means the allocator reused an id, for
|
||||
example after master state loss. See volume.growth.resume.
|
||||
|
||||
`
|
||||
}
|
||||
|
||||
func (c *commandVolumeCheckDuplicateIds) HasTag(CommandTag) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *commandVolumeCheckDuplicateIds) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
|
||||
topoInfo, _, err := collectTopologyInfo(commandEnv, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// vid -> layout key -> locations; ec shards tracked per collection since
|
||||
// shards plus regular copies of the same encoded volume are legitimate
|
||||
seen := make(map[needle.VolumeId]map[string][]string)
|
||||
ecSeen := make(map[needle.VolumeId]map[string][]string)
|
||||
collections := make(map[needle.VolumeId]map[string]bool)
|
||||
ecCollections := make(map[needle.VolumeId]map[string]bool)
|
||||
add := func(m map[needle.VolumeId]map[string][]string, id uint32, key, location string) {
|
||||
layouts := m[needle.VolumeId(id)]
|
||||
if layouts == nil {
|
||||
layouts = make(map[string][]string)
|
||||
m[needle.VolumeId(id)] = layouts
|
||||
}
|
||||
layouts[key] = append(layouts[key], location)
|
||||
}
|
||||
addCollection := func(m map[needle.VolumeId]map[string]bool, id uint32, collection string) {
|
||||
if m[needle.VolumeId(id)] == nil {
|
||||
m[needle.VolumeId(id)] = make(map[string]bool)
|
||||
}
|
||||
m[needle.VolumeId(id)][collection] = true
|
||||
}
|
||||
for _, dc := range topoInfo.DataCenterInfos {
|
||||
for _, r := range dc.RackInfos {
|
||||
for _, dn := range r.DataNodeInfos {
|
||||
for diskKey, di := range dn.DiskInfos {
|
||||
for _, vi := range di.VolumeInfos {
|
||||
rp, _ := super_block.NewReplicaPlacementFromByte(byte(vi.ReplicaPlacement))
|
||||
add(seen, vi.Id, fmt.Sprintf("collection=%q replication=%s ttl=%s disk=%s",
|
||||
vi.Collection, rp.String(), needle.LoadTTLFromUint32(vi.Ttl), vi.DiskType),
|
||||
fmt.Sprintf("%s %s", dn.Id, diskKey))
|
||||
addCollection(collections, vi.Id, vi.Collection)
|
||||
}
|
||||
for _, si := range di.EcShardInfos {
|
||||
add(ecSeen, si.Id, fmt.Sprintf("collection=%q ec_shards", si.Collection),
|
||||
fmt.Sprintf("%s %s disk=%s", dn.Id, diskKey, si.DiskType))
|
||||
addCollection(ecCollections, si.Id, si.Collection)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vids := make(map[needle.VolumeId]struct{}, len(seen)+len(ecSeen))
|
||||
for vid := range seen {
|
||||
vids[vid] = struct{}{}
|
||||
}
|
||||
for vid := range ecSeen {
|
||||
vids[vid] = struct{}{}
|
||||
}
|
||||
|
||||
duplicates := 0
|
||||
for _, vid := range sortedKeys(vids) {
|
||||
layouts := seen[vid]
|
||||
shardLayouts := ecSeen[vid]
|
||||
ecForeign := false
|
||||
if len(collections[vid]) > 0 {
|
||||
for collection := range ecCollections[vid] {
|
||||
if !collections[vid][collection] {
|
||||
ecForeign = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(layouts) < 2 && len(shardLayouts) < 2 && !ecForeign {
|
||||
continue
|
||||
}
|
||||
duplicates++
|
||||
fmt.Fprintf(writer, "volume %d is registered under %d layouts:\n", vid, len(layouts)+len(shardLayouts))
|
||||
for _, key := range sortedKeysString(layouts) {
|
||||
fmt.Fprintf(writer, " %-60s %v\n", key, layouts[key])
|
||||
}
|
||||
for _, key := range sortedKeysString(shardLayouts) {
|
||||
fmt.Fprintf(writer, " %-60s %v\n", key, shardLayouts[key])
|
||||
}
|
||||
}
|
||||
if duplicates == 0 {
|
||||
fmt.Fprintf(writer, "no duplicate volume ids found\n")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sortedKeys[V any](m map[needle.VolumeId]V) []needle.VolumeId {
|
||||
keys := make([]needle.VolumeId, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
slices.Sort(keys)
|
||||
return keys
|
||||
}
|
||||
|
||||
func sortedKeysString[V any](m map[string]V) []string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
slices.Sort(keys)
|
||||
return keys
|
||||
}
|
||||
@@ -109,6 +109,14 @@ var (
|
||||
Help: "1 while volume growth is frozen after detected master state loss",
|
||||
})
|
||||
|
||||
MasterDuplicateVolumeIds = prometheus.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Namespace: Namespace,
|
||||
Subsystem: subsystemMaster,
|
||||
Name: "duplicate_volume_ids",
|
||||
Help: "volume id registered under two different layouts",
|
||||
}, []string{"collection", "volumeId"})
|
||||
|
||||
MasterReceivedHeartbeatCounter = prometheus.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Namespace: Namespace,
|
||||
@@ -1000,6 +1008,7 @@ func init() {
|
||||
Gather.MustRegister(MasterRaftIsleader)
|
||||
Gather.MustRegister(MasterAdminLock)
|
||||
Gather.MustRegister(MasterVolumeGrowthFrozen)
|
||||
Gather.MustRegister(MasterDuplicateVolumeIds)
|
||||
Gather.MustRegister(MasterReceivedHeartbeatCounter)
|
||||
Gather.MustRegister(MasterLeaderChangeCounter)
|
||||
Gather.MustRegister(MasterReplicaPlacementMismatch)
|
||||
|
||||
+20
-5
@@ -61,14 +61,25 @@ type ReadOption struct {
|
||||
ReadBufferSize int
|
||||
}
|
||||
|
||||
// masterAddress returns the master to ask for volume and shard locations, or
|
||||
// "" while no leader is known.
|
||||
func (s *Store) masterAddress() pb.ServerAddress {
|
||||
if s.MasterFn == nil {
|
||||
return ""
|
||||
}
|
||||
return s.MasterFn()
|
||||
}
|
||||
|
||||
/*
|
||||
* A VolumeServer contains one Store
|
||||
*/
|
||||
type Store struct {
|
||||
MasterAddress pb.ServerAddress
|
||||
// MasterFn reports the master the volume server currently takes as leader.
|
||||
// The heartbeat loop owns that answer; the store only reads it.
|
||||
MasterFn func() pb.ServerAddress
|
||||
grpcDialOption grpc.DialOption
|
||||
volumeSizeLimit uint64 // read from the master
|
||||
preallocate atomic.Bool // read from the master
|
||||
volumeSizeLimit atomic.Uint64 // read from the master
|
||||
preallocate atomic.Bool // read from the master
|
||||
Ip string
|
||||
Port int
|
||||
GrpcPort int
|
||||
@@ -913,6 +924,8 @@ func (s *Store) MarkVolumeReadonly(i needle.VolumeId, canDelete bool, persist bo
|
||||
}
|
||||
// Wait for in-flight appends so a mark acked mid-write cannot race an
|
||||
// encode that reads the index and deletes the replica the write lands on.
|
||||
v.dataFileSyncLock.Lock()
|
||||
defer v.dataFileSyncLock.Unlock()
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
if canDelete && !v.HasRemoteFile() {
|
||||
@@ -1207,6 +1220,7 @@ func (s *Store) deleteVolumeGuarded(i needle.VolumeId, onlyEmpty bool, onlyGarba
|
||||
unlockAll := func() {
|
||||
for _, v := range lockedVolumes {
|
||||
v.dataFileAccessLock.Unlock()
|
||||
v.dataFileSyncLock.Unlock()
|
||||
}
|
||||
for _, location := range lockedLocations {
|
||||
location.volumesLock.Unlock()
|
||||
@@ -1217,6 +1231,7 @@ func (s *Store) deleteVolumeGuarded(i needle.VolumeId, onlyEmpty bool, onlyGarba
|
||||
for _, location := range s.Locations {
|
||||
location.volumesLock.Lock()
|
||||
if v, ok := location.volumes[i]; ok {
|
||||
v.dataFileSyncLock.Lock()
|
||||
v.dataFileAccessLock.Lock()
|
||||
lockedLocations = append(lockedLocations, location)
|
||||
lockedVolumes = append(lockedVolumes, v)
|
||||
@@ -1298,11 +1313,11 @@ func (s *Store) ConfigureVolume(i needle.VolumeId, replication string) error {
|
||||
}
|
||||
|
||||
func (s *Store) SetVolumeSizeLimit(x uint64) {
|
||||
atomic.StoreUint64(&s.volumeSizeLimit, x)
|
||||
s.volumeSizeLimit.Store(x)
|
||||
}
|
||||
|
||||
func (s *Store) GetVolumeSizeLimit() uint64 {
|
||||
return atomic.LoadUint64(&s.volumeSizeLimit)
|
||||
return s.volumeSizeLimit.Load()
|
||||
}
|
||||
|
||||
func (s *Store) SetPreallocate(x bool) {
|
||||
|
||||
@@ -568,7 +568,7 @@ const ecIntervalReadConcurrency = 8
|
||||
|
||||
func (s *Store) readEcShardIntervals(needleId types.NeedleId, ecVolume *erasure_coding.EcVolume, intervals []erasure_coding.Interval) (data []byte, is_deleted bool, err error) {
|
||||
if err = s.cachedLookupEcShardLocations(ecVolume); err != nil {
|
||||
return nil, false, fmt.Errorf("failed to locate shard via master grpc %s: %v", s.MasterAddress, err)
|
||||
return nil, false, fmt.Errorf("failed to locate shard via master grpc %s: %v", s.masterAddress(), err)
|
||||
}
|
||||
|
||||
var totalSize int
|
||||
@@ -721,7 +721,7 @@ func (s *Store) cachedLookupEcShardLocations(ecVolume *erasure_coding.EcVolume)
|
||||
|
||||
glog.V(3).Infof("lookup and cache ec volume %d locations", ecVolume.VolumeId)
|
||||
|
||||
err = operation.WithMasterServerClient(context.Background(), false, s.MasterAddress, s.grpcDialOption, func(masterClient master_pb.SeaweedClient) error {
|
||||
err = operation.WithMasterServerClient(context.Background(), false, s.masterAddress(), s.grpcDialOption, func(masterClient master_pb.SeaweedClient) error {
|
||||
req := &master_pb.LookupEcVolumeRequest{
|
||||
VolumeId: uint32(ecVolume.VolumeId),
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ func rewindShardLocationsRefresh(ecVolume *erasure_coding.EcVolume, d time.Durat
|
||||
func TestCachedLookupEcShardLocationsRefreshesAfterAFailedRead(t *testing.T) {
|
||||
master, masterAddr := startCountingMaster(t)
|
||||
store := &Store{
|
||||
MasterAddress: masterAddr,
|
||||
MasterFn: func() pb.ServerAddress { return masterAddr },
|
||||
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
ecVolume := &erasure_coding.EcVolume{
|
||||
@@ -127,7 +127,7 @@ func TestCachedLookupEcShardLocationsRefreshesAfterAFailedRead(t *testing.T) {
|
||||
func TestCachedLookupEcShardLocationsSettlesAfterRefresh(t *testing.T) {
|
||||
master, masterAddr := startCountingMaster(t)
|
||||
store := &Store{
|
||||
MasterAddress: masterAddr,
|
||||
MasterFn: func() pb.ServerAddress { return masterAddr },
|
||||
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
ecVolume := &erasure_coding.EcVolume{
|
||||
@@ -257,7 +257,7 @@ func TestReadOneEcShardIntervalMarksTheMapAfterADirectReadFails(t *testing.T) {
|
||||
func TestCachedLookupEcShardLocationsKeepsAMarkRaisedDuringTheLookup(t *testing.T) {
|
||||
master, masterAddr := startCountingMaster(t)
|
||||
store := &Store{
|
||||
MasterAddress: masterAddr,
|
||||
MasterFn: func() pb.ServerAddress { return masterAddr },
|
||||
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
ecVolume := &erasure_coding.EcVolume{
|
||||
@@ -295,7 +295,7 @@ func TestCachedLookupEcShardLocationsKeepsAMarkRaisedDuringTheLookup(t *testing.
|
||||
func TestCachedLookupEcShardLocationsKeepsTheMarkWhenTheLookupFails(t *testing.T) {
|
||||
master, masterAddr := startCountingMaster(t)
|
||||
store := &Store{
|
||||
MasterAddress: masterAddr,
|
||||
MasterFn: func() pb.ServerAddress { return masterAddr },
|
||||
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
ecVolume := &erasure_coding.EcVolume{
|
||||
|
||||
@@ -23,7 +23,7 @@ func (s *Store) ScrubEcVolume(vid needle.VolumeId, mode volume_server_pb.VolumeS
|
||||
return 0, nil, []error{fmt.Errorf("EC volume id %d not found", vid)}
|
||||
}
|
||||
if err := s.cachedLookupEcShardLocations(ecv); err != nil {
|
||||
return 0, nil, []error{fmt.Errorf("failed to locate shard via master grpc %s: %v", s.MasterAddress, err)}
|
||||
return 0, nil, []error{fmt.Errorf("failed to locate shard via master grpc %s: %v", s.masterAddress(), err)}
|
||||
}
|
||||
return s.scrubEcVolumeWalk(ecv, mode, forceDeletedNeedlesCheck)
|
||||
}
|
||||
@@ -56,7 +56,7 @@ func (s *Store) ScrubEcVolumeMerged(merged *erasure_coding.MergedEcRuntimes, mod
|
||||
}
|
||||
}
|
||||
if err := s.cachedLookupEcShardLocations(ecv); err != nil {
|
||||
return 0, nil, []error{fmt.Errorf("failed to locate shard via master grpc %s: %v", s.MasterAddress, err)}
|
||||
return 0, nil, []error{fmt.Errorf("failed to locate shard via master grpc %s: %v", s.masterAddress(), err)}
|
||||
}
|
||||
|
||||
files, shardInfos, errs := s.scrubEcVolumeWalk(ecv, mode, forceDeletedNeedlesCheck)
|
||||
|
||||
+25
-7
@@ -43,7 +43,12 @@ type Volume struct {
|
||||
|
||||
super_block.SuperBlock
|
||||
|
||||
dataFileAccessLock sync.RWMutex
|
||||
dataFileAccessLock sync.RWMutex
|
||||
// Serializes a data-file mutation with the sync that makes it durable:
|
||||
// write, delete, lifecycle and compaction paths hold it for their whole
|
||||
// critical section, while the fsync itself runs with dataFileAccessLock
|
||||
// released so readers of this volume do not wait on it.
|
||||
dataFileSyncLock sync.Mutex
|
||||
superBlockAccessLock sync.Mutex
|
||||
|
||||
// The batch worker exists only once the volume takes a durable write. Most
|
||||
@@ -129,6 +134,8 @@ func (v *Volume) FileName(ext string) (fileName string) {
|
||||
// gone. A no-op when the index already lives in newIdxDir. A derived .ldb is
|
||||
// not moved: the reload rebuilds it in newIdxDir from the .idx.
|
||||
func (v *Volume) RelocateIndexTo(newIdxDir string) error {
|
||||
v.dataFileSyncLock.Lock()
|
||||
defer v.dataFileSyncLock.Unlock()
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
|
||||
@@ -290,32 +297,41 @@ func (v *Volume) DiskType() types.DiskType {
|
||||
}
|
||||
|
||||
func (v *Volume) SyncToDisk() {
|
||||
v.dataFileSyncLock.Lock()
|
||||
defer v.dataFileSyncLock.Unlock()
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
if v.nm != nil {
|
||||
if err := v.nm.Sync(); err != nil {
|
||||
// Flush with the access lock dropped so readers are not stalled by the
|
||||
// fsync; writers and file swaps stay excluded by dataFileSyncLock.
|
||||
nm, backend := v.nm, v.DataBackend
|
||||
v.dataFileAccessLock.Unlock()
|
||||
if nm != nil {
|
||||
if err := nm.Sync(); err != nil {
|
||||
glog.Warningf("Volume Close fail to sync volume idx %d", v.Id)
|
||||
}
|
||||
}
|
||||
if v.DataBackend != nil {
|
||||
if err := v.DataBackend.Sync(); err != nil {
|
||||
if backend != nil {
|
||||
if err := backend.Sync(); err != nil {
|
||||
glog.Warningf("Volume Close fail to sync volume %d", v.Id)
|
||||
}
|
||||
}
|
||||
v.dataFileAccessLock.Lock()
|
||||
}
|
||||
|
||||
// Close cleanly shuts down this volume
|
||||
func (v *Volume) Close() {
|
||||
// Wait for any in-progress compaction to finish and claim the flag so no
|
||||
// new compaction can start. This must happen BEFORE acquiring
|
||||
// dataFileAccessLock to avoid deadlocking with CommitCompact which holds
|
||||
// the flag while waiting for the lock.
|
||||
// dataFileSyncLock and dataFileAccessLock to avoid deadlocking with
|
||||
// CommitCompact which holds the flag while waiting for the locks.
|
||||
for !v.isCompactionInProgress.CompareAndSwap(false, true) {
|
||||
time.Sleep(521 * time.Millisecond)
|
||||
glog.Warningf("Volume Close wait for compaction %d", v.Id)
|
||||
}
|
||||
defer v.isCompactionInProgress.Store(false)
|
||||
|
||||
v.dataFileSyncLock.Lock()
|
||||
defer v.dataFileSyncLock.Unlock()
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
|
||||
@@ -331,6 +347,8 @@ func (v *Volume) Close() {
|
||||
// stale-false flag would make doDeleteRequest skip the new .dat's tombstones and
|
||||
// disable the phantom-.dat guard.
|
||||
func (v *Volume) SwapDataBackend(newBackend backend.BackendStorageFile, hasRemoteFile bool) {
|
||||
v.dataFileSyncLock.Lock()
|
||||
defer v.dataFileSyncLock.Unlock()
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
v.swapDataBackendLocked(newBackend, hasRemoteFile)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/idx"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
@@ -143,7 +145,25 @@ func CheckVolumeDataIntegrity(v *Volume, indexFile *os.File) (lastAppendAtNs uin
|
||||
return 0, fmt.Errorf("verifyIndexFileIntegrity %s failed: %v", indexFile.Name(), err)
|
||||
}
|
||||
if indexSize == 0 {
|
||||
return 0, nil
|
||||
if v.noWriteOrDelete {
|
||||
return 0, nil
|
||||
}
|
||||
// An empty index can hide writes a crash stranded in the .dat: the
|
||||
// writable index loader creates the .idx before the first needle
|
||||
// append, so a crash after that append leaves a volume whose data
|
||||
// nothing indexes — and every check below skips an empty index. The
|
||||
// same repair runs from the first record past the superblock; a tail
|
||||
// it cannot explain fails the check, since an unaccounted-for .dat
|
||||
// must not load writable either.
|
||||
if _, _, err = repairUnindexedDatTail(v, indexFile, 0, -1); err != nil {
|
||||
return 0, fmt.Errorf("CheckVolumeDataIntegrity %s: repair unindexed .dat tail: %v", indexFile.Name(), err)
|
||||
}
|
||||
if indexSize, err = verifyIndexFileIntegrity(indexFile); err != nil {
|
||||
return 0, fmt.Errorf("verifyIndexFileIntegrity %s after re-indexing failed: %v", indexFile.Name(), err)
|
||||
}
|
||||
if indexSize == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
}
|
||||
// The deeper-than-tail structural check (every (offset + actual size)
|
||||
// fits inside .dat) lives in volume.load(): it reads
|
||||
@@ -166,6 +186,32 @@ func CheckVolumeDataIntegrity(v *Volume, indexFile *os.File) (lastAppendAtNs uin
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// A crash between appending a needle to the .dat and appending its entry to
|
||||
// the .idx leaves a .dat tail no index entry covers. Re-index the complete
|
||||
// needles in it and cut an incomplete remainder before the check below,
|
||||
// which would otherwise load the volume read-only. Only a volume that is
|
||||
// about to load writable is repaired; a read-only one is left as it is.
|
||||
// A repair that fails for any other reason than an unexplained tail (a
|
||||
// read, write, truncate or sync error) fails the check, so the volume
|
||||
// loads read-only instead of writable on a repair that may not be on disk.
|
||||
if !v.noWriteOrDelete {
|
||||
reindexed, _, err := repairUnindexedDatTail(v, indexFile, indexSize, tailEntryPos)
|
||||
if err != nil {
|
||||
if !errors.Is(err, errTailNotTorn) {
|
||||
return 0, fmt.Errorf("CheckVolumeDataIntegrity %s: repair unindexed .dat tail: %v", indexFile.Name(), err)
|
||||
}
|
||||
glog.Warningf("volume %d: unindexed .dat tail not repaired: %v", v.Id, err)
|
||||
}
|
||||
if reindexed > 0 {
|
||||
if indexSize, err = verifyIndexFileIntegrity(indexFile); err != nil {
|
||||
return 0, fmt.Errorf("verifyIndexFileIntegrity %s after re-indexing failed: %v", indexFile.Name(), err)
|
||||
}
|
||||
if tailEntryPos, err = findDatTailEntryOffset(v, indexFile, indexSize); err != nil {
|
||||
return 0, fmt.Errorf("CheckVolumeDataIntegrity %s: %v", indexFile.Name(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if lastAppendAtNs, err = doCheckAndFixVolumeData(v, indexFile, tailEntryPos); err != nil {
|
||||
return lastAppendAtNs, fmt.Errorf("CheckVolumeDataIntegrity %s failed: %v", indexFile.Name(), err)
|
||||
}
|
||||
@@ -219,6 +265,238 @@ func needleDiskEnd(offset types.Offset, size types.Size, version needle.Version)
|
||||
return offset.ToActualOffset() + needle.GetActualSize(types.Size(size.Raw()), version)
|
||||
}
|
||||
|
||||
// errTailNotTorn marks a .dat tail that is not the result of an interrupted
|
||||
// append; the volume keeps loading read-only.
|
||||
var errTailNotTorn = errors.New("not a torn tail")
|
||||
|
||||
// repairUnindexedDatTail re-indexes the complete needles a crash left past the
|
||||
// last indexed needle of a local version 3 volume, cuts an incomplete
|
||||
// remainder, and returns how many needles it indexed and how many bytes it cut.
|
||||
//
|
||||
// A write appends the needle to the .dat, then its entry to the .idx, then
|
||||
// answers the client. A process killed between the first two steps leaves a
|
||||
// needle, or part of one, past the end of the needle at the highest indexed
|
||||
// offset; a crash after the very first append leaves it past an index with
|
||||
// no entry at all, which tailEntryPos < 0 marks: the walk then starts at the
|
||||
// first record past the superblock with no anchor needle and no append
|
||||
// timestamp to compare against. After a power loss the order on disk is
|
||||
// whatever the page cache
|
||||
// flushed: a complete needle can survive whose .idx entry did not, although
|
||||
// the client was answered. So a complete needle is never dropped: every
|
||||
// complete needle in the tail (its header, body, checksum, timestamp and
|
||||
// padding inside the file, its CRC valid, its append timestamp later than the
|
||||
// needle before it) gets the .idx entry the volume server would have written,
|
||||
// in .dat order; the .dat is synced first so the rows never become durable
|
||||
// ahead of the records they name, and the .idx is synced after. A size 0
|
||||
// record is indexed at size 0,
|
||||
// the same live entry the write path publishes for a write with no data. A
|
||||
// delete appends the identical record, so a recovered size 0 record can also
|
||||
// be a delete whose key then reads back as an empty object rather than
|
||||
// not-found -- the two cannot be told apart, and resurrecting an empty
|
||||
// placeholder beats a wrong tombstone, which drops an acknowledged write's
|
||||
// object entirely. Only what follows the last complete
|
||||
// needle and is itself incomplete is cut: fewer bytes than a header, a record
|
||||
// running past the end of the file, or a last record whose bytes are damaged
|
||||
// (its CRC fails or its body does not parse); the .dat is synced after the
|
||||
// cut. A record that cannot be read is not cut: a read error is returned and
|
||||
// nothing is changed.
|
||||
//
|
||||
// Nothing is changed when the tail is anything else: the .idx entry at the
|
||||
// highest offset does not describe the needle there (id, size, CRC), a record
|
||||
// inside the tail is damaged while more data follows it, a header carries id 0
|
||||
// or a negative size, append timestamps go backwards, the .dat is beyond what
|
||||
// 4-byte offsets can address, the needle version is not 3, or the .idx size is
|
||||
// not a whole number of entries. The integrity check that follows then marks
|
||||
// the volume read-only exactly as before.
|
||||
func repairUnindexedDatTail(v *Volume, indexFile *os.File, indexSize int64, tailEntryPos int64) (int, int64, error) {
|
||||
version := v.Version()
|
||||
if version != needle.Version3 || v.DataBackend == nil {
|
||||
return 0, 0, nil
|
||||
}
|
||||
datSize, _, err := v.DataBackend.GetStat()
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("stat %s: %v", v.FileName(".dat"), err)
|
||||
}
|
||||
if datSize <= int64(super_block.SuperBlockSize) || datSize > int64(types.MaxPossibleVolumeSize) {
|
||||
// past MaxPossibleVolumeSize the .idx offsets wrap: an entry's offset
|
||||
// does not name its needle's position on its own
|
||||
return 0, 0, nil
|
||||
}
|
||||
var start int64
|
||||
var lastAppendAtNs uint64
|
||||
if tailEntryPos < 0 {
|
||||
// The index holds no row at all, so no entry can anchor the walk:
|
||||
// it starts at the first record past the superblock.
|
||||
start = int64(v.SuperBlock.BlockSize())
|
||||
} else {
|
||||
entry, err := readIndexEntryAtOffset(indexFile, tailEntryPos)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("read index entry at %d: %v", tailEntryPos, err)
|
||||
}
|
||||
key, offset, size := idx.IdxFileEntry(entry)
|
||||
if offset.IsZero() {
|
||||
return 0, 0, nil
|
||||
}
|
||||
start = needleDiskEnd(offset, size, version)
|
||||
if start >= datSize {
|
||||
// the .dat ends at the last needle (clean), or the index references
|
||||
// bytes the .dat does not have: not a torn tail, not ours to fix
|
||||
return 0, 0, nil
|
||||
}
|
||||
|
||||
// Anchor: the needle at the highest indexed offset must be the one its
|
||||
// entry describes, whole and with a valid CRC.
|
||||
onDiskSize := size
|
||||
if size.IsDeleted() {
|
||||
onDiskSize = 0
|
||||
}
|
||||
anchor, err := readTailNeedle(v.DataBackend, version, offset.ToActualOffset(), onDiskSize)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("last indexed needle %v at %d: %v: %w", key, offset.ToActualOffset(), err, errTailNotTorn)
|
||||
}
|
||||
if anchor.Id != key {
|
||||
return 0, 0, fmt.Errorf("needle at %d is id %v, its index entry says id %v: %w", offset.ToActualOffset(), anchor.Id, key, errTailNotTorn)
|
||||
}
|
||||
lastAppendAtNs = anchor.AppendAtNs
|
||||
}
|
||||
if start >= datSize {
|
||||
// no record past the superblock: nothing to index
|
||||
return 0, 0, nil
|
||||
}
|
||||
// The backend rounds its size up to the needle alignment; the walk needs
|
||||
// the bytes that are really there.
|
||||
fileSize := datSize
|
||||
if st, statErr := os.Stat(v.DataBackend.Name()); statErr == nil {
|
||||
fileSize = st.Size()
|
||||
}
|
||||
|
||||
entries, cutAt, err := walkUnindexedDatTail(v.DataBackend, version, start, fileSize, lastAppendAtNs)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
reindexed := len(entries) / types.NeedleMapEntrySize
|
||||
if reindexed > 0 {
|
||||
// The new .idx rows must not become durable before the .dat records
|
||||
// they name: a power loss between the two would leave the .idx
|
||||
// pointing past the end of the .dat.
|
||||
if err := v.DataBackend.Sync(); err != nil {
|
||||
return 0, 0, fmt.Errorf("sync %s before re-indexing: %v", v.FileName(".dat"), err)
|
||||
}
|
||||
if err := appendIndexEntries(indexFile, entries, indexSize); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
}
|
||||
var cut int64
|
||||
if cutAt < fileSize {
|
||||
if err := v.DataBackend.Truncate(cutAt); err != nil {
|
||||
return reindexed, 0, fmt.Errorf("truncate %s to %d: %v", v.FileName(".dat"), cutAt, err)
|
||||
}
|
||||
if err := v.DataBackend.Sync(); err != nil {
|
||||
return reindexed, fileSize - cutAt, fmt.Errorf("sync %s after truncating to %d: %v", v.FileName(".dat"), cutAt, err)
|
||||
}
|
||||
cut = fileSize - cutAt
|
||||
}
|
||||
glog.Warningf("volume %d: repaired the unindexed tail of %s: re-indexed %d needle(s), cut %d bytes (%d -> %d bytes)",
|
||||
v.Id, v.FileName(".dat"), reindexed, cut, fileSize, fileSize-cut)
|
||||
return reindexed, cut, nil
|
||||
}
|
||||
|
||||
// indexAppender is the part of the .idx file the repair writes through.
|
||||
type indexAppender interface {
|
||||
io.WriterAt
|
||||
Truncate(size int64) error
|
||||
Sync() error
|
||||
Name() string
|
||||
}
|
||||
|
||||
// appendIndexEntries writes entries at the end (at) of the .idx and syncs it.
|
||||
// A failed write can leave part of the entries behind, which would make the
|
||||
// next load reject the .idx as a partial entry; they are removed again.
|
||||
func appendIndexEntries(indexFile indexAppender, entries []byte, at int64) error {
|
||||
if _, err := indexFile.WriteAt(entries, at); err != nil {
|
||||
if truncErr := indexFile.Truncate(at); truncErr != nil {
|
||||
return fmt.Errorf("append %d bytes to %s: %v; truncate back to %d: %v", len(entries), indexFile.Name(), err, at, truncErr)
|
||||
}
|
||||
return fmt.Errorf("append %d bytes to %s: %v", len(entries), indexFile.Name(), err)
|
||||
}
|
||||
if err := indexFile.Sync(); err != nil {
|
||||
return fmt.Errorf("sync %s: %v", indexFile.Name(), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// readTailNeedle reads and verifies the whole record of a needle of the given
|
||||
// on-disk size at offset: header, body, CRC and timestamp.
|
||||
func readTailNeedle(datFile backend.BackendStorageFile, version needle.Version, at int64, size types.Size) (*needle.Needle, error) {
|
||||
if size > 0 && size < 4 && version != needle.Version1 {
|
||||
// a v2+ body always starts with its 4-byte data-size field; size 1-3
|
||||
// is damaged bytes, not a record — decoding it slices out of range
|
||||
return nil, fmt.Errorf("record at %d has size %d: %w", at, size, needle.ErrorCorrupted)
|
||||
}
|
||||
blob, err := needle.ReadNeedleBlob(datFile, at, size, version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n := new(needle.Needle)
|
||||
if err := n.ReadBytes(blob, at, size, version); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if size > 0 && len(n.Data) == 0 {
|
||||
// A needle with no data is written with size 0, so a record with a
|
||||
// body whose data size reads 0 is damaged. The CRC covers only the
|
||||
// data, and ReadBytes does not check it for empty data.
|
||||
return nil, fmt.Errorf("needle %v at %d has size %d but no data: %w", n.Id, at, size, needle.ErrorCorrupted)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// walkUnindexedDatTail walks the needles from start to fileSize and returns
|
||||
// the .idx entries of the complete ones, and the offset from which the rest is
|
||||
// an incomplete last record (fileSize when there is none). It fails with
|
||||
// errTailNotTorn when the tail is damaged in a way an interrupted append does
|
||||
// not explain.
|
||||
func walkUnindexedDatTail(datFile backend.BackendStorageFile, version needle.Version, start, fileSize int64, lastAppendAtNs uint64) ([]byte, int64, error) {
|
||||
var entries []byte
|
||||
at := start
|
||||
for at < fileSize {
|
||||
if fileSize-at < types.NeedleHeaderSize {
|
||||
return entries, at, nil // a partial header
|
||||
}
|
||||
header, _, _, err := needle.ReadNeedleHeader(datFile, version, at)
|
||||
if err != nil || header == nil {
|
||||
return nil, 0, fmt.Errorf("read needle header at %d: %v", at, err)
|
||||
}
|
||||
if header.Id == 0 || header.Size < 0 {
|
||||
return nil, 0, fmt.Errorf("record at %d has id %v size %d: %w", at, header.Id, header.Size, errTailNotTorn)
|
||||
}
|
||||
end := at + needle.GetActualSize(header.Size, version)
|
||||
if end > fileSize {
|
||||
return entries, at, nil // the last record runs past the end of the file
|
||||
}
|
||||
n, err := readTailNeedle(datFile, version, at, header.Size)
|
||||
if err != nil {
|
||||
if !errors.Is(err, needle.ErrorCorrupted) {
|
||||
// a read error says nothing about the bytes: leave them
|
||||
return nil, 0, fmt.Errorf("read record %v at %d: %w", header.Id, at, err)
|
||||
}
|
||||
if end == fileSize {
|
||||
return entries, at, nil // the last record is damaged: it never completed
|
||||
}
|
||||
return nil, 0, fmt.Errorf("record %v at %d is damaged and %d bytes follow it: %v: %w", header.Id, at, fileSize-end, err, errTailNotTorn)
|
||||
}
|
||||
if n.AppendAtNs <= lastAppendAtNs {
|
||||
return nil, 0, fmt.Errorf("record %v at %d was appended at %d, not after %d: %w", n.Id, at, n.AppendAtNs, lastAppendAtNs, errTailNotTorn)
|
||||
}
|
||||
lastAppendAtNs = n.AppendAtNs
|
||||
// A size 0 record is a delete or an empty write; the two append the
|
||||
// identical record, so it is indexed at size 0 the way the write path
|
||||
// indexes an empty write.
|
||||
entries = append(entries, needle_map.ToBytes(n.Id, types.ToOffset(at), header.Size)...)
|
||||
at = end
|
||||
}
|
||||
return entries, fileSize, nil
|
||||
}
|
||||
|
||||
func doCheckAndFixVolumeData(v *Volume, indexFile *os.File, indexOffset int64) (lastAppendAtNs uint64, err error) {
|
||||
var lastIdxEntry []byte
|
||||
if lastIdxEntry, err = readIndexEntryAtOffset(indexFile, indexOffset); err != nil {
|
||||
|
||||
@@ -0,0 +1,792 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// A torn tail is what a crash between the two appends of a write leaves: the
|
||||
// needle is in the .dat, its entry never reached the .idx. After a process
|
||||
// crash the client was never answered; after a power loss it may have been.
|
||||
// These tests write needles (and deletes) normally, drop the last .idx
|
||||
// entries, cut or damage the .dat as a crash would, and reload the volume
|
||||
// through the real load path.
|
||||
|
||||
type tornOp struct {
|
||||
id uint64
|
||||
del bool
|
||||
empty bool // a write with no data, which appends a size 0 record like a delete
|
||||
}
|
||||
|
||||
type tornFixture struct {
|
||||
dir string
|
||||
datName string
|
||||
idxName string
|
||||
starts []int64 // .dat offset of each op's record
|
||||
end int64 // .dat size after every op
|
||||
written map[uint64]*needle.Needle
|
||||
}
|
||||
|
||||
func newTornTailTestVolume(t *testing.T, dir string) *Volume {
|
||||
t.Helper()
|
||||
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("load volume: %v", err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// buildTornFixture runs ops against a fresh volume (each op appends one .dat
|
||||
// record and one .idx entry), closes it and drops the last unindexed entries.
|
||||
func buildTornFixture(t *testing.T, ops []tornOp, unindexed int) *tornFixture {
|
||||
t.Helper()
|
||||
f := &tornFixture{dir: t.TempDir(), written: map[uint64]*needle.Needle{}}
|
||||
v := newTornTailTestVolume(t, f.dir)
|
||||
for _, op := range ops {
|
||||
at, _, err := v.DataBackend.GetStat()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.starts = append(f.starts, at)
|
||||
if op.del {
|
||||
if _, err := v.doDeleteRequest(newEmptyNeedle(op.id)); err != nil {
|
||||
t.Fatalf("delete needle %d: %v", op.id, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
n := newRandomNeedle(op.id)
|
||||
if op.empty {
|
||||
n = newEmptyNeedle(op.id)
|
||||
}
|
||||
if _, _, _, err := v.writeNeedle2(n, true, false, false); err != nil {
|
||||
t.Fatalf("write needle %d: %v", op.id, err)
|
||||
}
|
||||
f.written[op.id] = n
|
||||
}
|
||||
f.end, _, _ = v.DataBackend.GetStat()
|
||||
f.datName, f.idxName = v.FileName(".dat"), v.FileName(".idx")
|
||||
v.Close()
|
||||
if unindexed > 0 {
|
||||
if err := os.Truncate(f.idxName, fileSize(t, f.idxName)-int64(unindexed)*types.NeedleMapEntrySize); err != nil {
|
||||
t.Fatalf("drop %d .idx entries: %v", unindexed, err)
|
||||
}
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// midRecord is an offset inside the body of op i's record: past its header,
|
||||
// short of its end. A fixed offset is not: a needle with a few bytes of data
|
||||
// is a 40-byte record, which a cut at +40 leaves whole.
|
||||
func (f *tornFixture) midRecord(i int) int64 {
|
||||
end := f.end
|
||||
if i+1 < len(f.starts) {
|
||||
end = f.starts[i+1]
|
||||
}
|
||||
return midRecordBody(f.starts[i], end)
|
||||
}
|
||||
|
||||
func midRecordBody(start, end int64) int64 {
|
||||
return start + types.NeedleHeaderSize + (end-start-types.NeedleHeaderSize)/2
|
||||
}
|
||||
|
||||
func (f *tornFixture) truncateDat(t *testing.T, size int64) {
|
||||
t.Helper()
|
||||
if err := os.Truncate(f.datName, size); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// flipDataByte damages the data of the record at the given offset, so its
|
||||
// CRC no longer matches.
|
||||
func (f *tornFixture) flipDataByte(t *testing.T, at int64) {
|
||||
t.Helper()
|
||||
file, err := os.OpenFile(f.datName, os.O_RDWR, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer file.Close()
|
||||
b := make([]byte, 1)
|
||||
pos := at + types.NeedleHeaderSize + 4 // past the 4-byte DataSize field
|
||||
if _, err := file.ReadAt(b, pos); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b[0] ^= 0xff
|
||||
if _, err := file.WriteAt(b, pos); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// zeroDataSize zeroes the DataSize field and the first data byte (read as
|
||||
// the flags once DataSize is 0) of the record at the given offset: the header
|
||||
// still claims a body, the body parses as an empty needle.
|
||||
func (f *tornFixture) zeroDataSize(t *testing.T, at int64) {
|
||||
t.Helper()
|
||||
file, err := os.OpenFile(f.datName, os.O_RDWR, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer file.Close()
|
||||
if _, err := file.WriteAt(make([]byte, 5), at+types.NeedleHeaderSize); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func assertReadable(t *testing.T, v *Volume, want *needle.Needle) {
|
||||
t.Helper()
|
||||
got := &needle.Needle{Id: want.Id}
|
||||
if _, err := v.readNeedle(got, nil, nil); err != nil {
|
||||
t.Fatalf("read needle %d: %v", want.Id, err)
|
||||
}
|
||||
if !bytes.Equal(got.Data, want.Data) {
|
||||
t.Fatalf("needle %d reads back different data", want.Id)
|
||||
}
|
||||
}
|
||||
|
||||
func assertNotReadable(t *testing.T, v *Volume, id uint64) {
|
||||
t.Helper()
|
||||
if _, err := v.readNeedle(&needle.Needle{Id: types.Uint64ToNeedleId(id)}, nil, nil); err == nil {
|
||||
t.Fatalf("needle %d reads back; it should be deleted or absent", id)
|
||||
}
|
||||
}
|
||||
|
||||
// A recovered size 0 record indexes as a live empty needle: a delete and a
|
||||
// write with no data append the identical record, so the repair cannot tell
|
||||
// them apart and indexes the entry the write path would have written.
|
||||
func assertEmpty(t *testing.T, v *Volume, id uint64) {
|
||||
t.Helper()
|
||||
n := &needle.Needle{Id: types.Uint64ToNeedleId(id)}
|
||||
if _, err := v.readNeedle(n, nil, nil); err != nil {
|
||||
t.Fatalf("read needle %d: %v", id, err)
|
||||
}
|
||||
if len(n.Data) != 0 {
|
||||
t.Fatalf("needle %d reads back %d bytes, want an empty needle", id, len(n.Data))
|
||||
}
|
||||
}
|
||||
|
||||
func writes(ids ...uint64) []tornOp {
|
||||
ops := make([]tornOp, len(ids))
|
||||
for i, id := range ids {
|
||||
ops[i] = tornOp{id: id}
|
||||
}
|
||||
return ops
|
||||
}
|
||||
|
||||
func TestVolumeLoadRepairsUnindexedDatTail(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
ops []tornOp
|
||||
unindexed int
|
||||
damage func(t *testing.T, f *tornFixture)
|
||||
wantSize func(f *tornFixture) int64 // .dat size after the repair
|
||||
reindexed int
|
||||
readable []uint64
|
||||
empty []uint64 // readable as an empty live needle
|
||||
absent []uint64
|
||||
}{
|
||||
{name: "one complete unindexed needle is re-indexed",
|
||||
ops: writes(1, 2, 3, 4), unindexed: 1,
|
||||
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 1,
|
||||
readable: []uint64{1, 2, 3, 4}},
|
||||
{name: "two complete unindexed needles are re-indexed",
|
||||
ops: writes(1, 2, 3, 4, 5), unindexed: 2,
|
||||
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 2,
|
||||
readable: []uint64{1, 2, 3, 4, 5}},
|
||||
{name: "an unindexed delete is re-indexed as an empty live needle",
|
||||
ops: append(writes(1, 2, 3), tornOp{id: 2, del: true}), unindexed: 1,
|
||||
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 1,
|
||||
readable: []uint64{1, 3}, empty: []uint64{2}},
|
||||
{name: "an unindexed empty write of a live id stays an empty needle",
|
||||
ops: append(writes(1, 2, 3), tornOp{id: 2, empty: true}), unindexed: 1,
|
||||
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 1,
|
||||
readable: []uint64{1, 3}, empty: []uint64{2}},
|
||||
{name: "a partial header is cut",
|
||||
ops: writes(1, 2, 3, 4), unindexed: 1,
|
||||
damage: func(t *testing.T, f *tornFixture) { f.truncateDat(t, f.starts[3]+7) },
|
||||
wantSize: func(f *tornFixture) int64 { return f.starts[3] },
|
||||
readable: []uint64{1, 2, 3}, absent: []uint64{4}},
|
||||
{name: "a partial body is cut",
|
||||
ops: writes(1, 2, 3, 4), unindexed: 1,
|
||||
damage: func(t *testing.T, f *tornFixture) { f.truncateDat(t, f.midRecord(3)) },
|
||||
wantSize: func(f *tornFixture) int64 { return f.starts[3] },
|
||||
readable: []uint64{1, 2, 3}, absent: []uint64{4}},
|
||||
{name: "a complete needle is re-indexed and the partial one after it cut",
|
||||
ops: writes(1, 2, 3, 4, 5), unindexed: 2,
|
||||
damage: func(t *testing.T, f *tornFixture) { f.truncateDat(t, f.midRecord(4)) },
|
||||
wantSize: func(f *tornFixture) int64 { return f.starts[4] }, reindexed: 1,
|
||||
readable: []uint64{1, 2, 3, 4}, absent: []uint64{5}},
|
||||
{name: "a last needle with a bad CRC is cut",
|
||||
ops: writes(1, 2, 3, 4), unindexed: 1,
|
||||
damage: func(t *testing.T, f *tornFixture) { f.flipDataByte(t, f.starts[3]) },
|
||||
wantSize: func(f *tornFixture) int64 { return f.starts[3] },
|
||||
readable: []uint64{1, 2, 3}, absent: []uint64{4}},
|
||||
{name: "a last needle whose data size field reads 0 is cut",
|
||||
ops: writes(1, 2, 3, 4), unindexed: 1,
|
||||
damage: func(t *testing.T, f *tornFixture) { f.zeroDataSize(t, f.starts[3]) },
|
||||
wantSize: func(f *tornFixture) int64 { return f.starts[3] },
|
||||
readable: []uint64{1, 2, 3}, absent: []uint64{4}},
|
||||
{name: "an unindexed empty write of a new id stays an empty needle",
|
||||
ops: append(writes(1, 2), tornOp{id: 3, empty: true}), unindexed: 1,
|
||||
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 1,
|
||||
readable: []uint64{1, 2, 3}},
|
||||
{name: "an unindexed empty write after a delete of the same id stays an empty needle",
|
||||
ops: append(append(writes(1, 2), tornOp{id: 2, del: true}), tornOp{id: 2, empty: true}), unindexed: 1,
|
||||
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 1,
|
||||
readable: []uint64{1, 2}},
|
||||
{name: "an unindexed write and delete of the same id are re-indexed in order",
|
||||
ops: append(writes(1, 2, 3), tornOp{id: 3, del: true}), unindexed: 2,
|
||||
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 2,
|
||||
readable: []uint64{1, 2}, empty: []uint64{3}},
|
||||
{name: "an unindexed empty write and its delete are re-indexed in order",
|
||||
ops: append(writes(1, 2), tornOp{id: 3, empty: true}, tornOp{id: 3, del: true}), unindexed: 2,
|
||||
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 2,
|
||||
readable: []uint64{1, 2}, empty: []uint64{3}},
|
||||
{name: "a partial needle after an indexed tombstone is cut",
|
||||
ops: append(append(writes(1, 2, 3), tornOp{id: 2, del: true}), tornOp{id: 4}), unindexed: 1,
|
||||
damage: func(t *testing.T, f *tornFixture) { f.truncateDat(t, f.midRecord(4)) },
|
||||
wantSize: func(f *tornFixture) int64 { return f.starts[4] },
|
||||
readable: []uint64{1, 3}, absent: []uint64{2, 4}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := buildTornFixture(t, tc.ops, tc.unindexed)
|
||||
if tc.damage != nil {
|
||||
tc.damage(t, f)
|
||||
}
|
||||
idxBefore := fileSize(t, f.idxName)
|
||||
|
||||
v := newTornTailTestVolume(t, f.dir)
|
||||
defer v.Close()
|
||||
if v.noWriteOrDelete || v.noWriteCanDelete {
|
||||
t.Fatal("volume with an unindexed .dat tail loaded read-only")
|
||||
}
|
||||
if got, want := fileSize(t, f.datName), tc.wantSize(f); got != want {
|
||||
t.Fatalf(".dat is %d bytes after load, want %d", got, want)
|
||||
}
|
||||
if got, want := fileSize(t, f.idxName), idxBefore+int64(tc.reindexed)*types.NeedleMapEntrySize; got != want {
|
||||
t.Fatalf(".idx is %d bytes after load, want %d (%d entries re-indexed)", got, want, tc.reindexed)
|
||||
}
|
||||
for _, id := range tc.readable {
|
||||
assertReadable(t, v, f.written[id])
|
||||
}
|
||||
for _, id := range tc.empty {
|
||||
assertEmpty(t, v, id)
|
||||
}
|
||||
for _, id := range tc.absent {
|
||||
assertNotReadable(t, v, id)
|
||||
}
|
||||
extra := newRandomNeedle(100)
|
||||
if _, _, _, err := v.writeNeedle2(extra, true, false, false); err != nil {
|
||||
t.Fatalf("write after repair: %v", err)
|
||||
}
|
||||
assertReadable(t, v, extra)
|
||||
v.Close()
|
||||
|
||||
// the repaired volume reloads clean, and keeps what it indexed
|
||||
v2 := newTornTailTestVolume(t, f.dir)
|
||||
defer v2.Close()
|
||||
if v2.noWriteOrDelete {
|
||||
t.Fatal("repaired volume loaded read-only on the next load")
|
||||
}
|
||||
for _, id := range tc.readable {
|
||||
assertReadable(t, v2, f.written[id])
|
||||
}
|
||||
assertReadable(t, v2, extra)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An empty index can hide writes a crash stranded in the .dat: the writable
|
||||
// index loader creates the .idx before the first needle append, so a crash
|
||||
// after that append leaves a volume whose data nothing indexes. The same
|
||||
// repair runs from the first record past the superblock.
|
||||
func TestVolumeLoadRepairsTailPastEmptyIndex(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
ops []tornOp
|
||||
damage func(t *testing.T, f *tornFixture)
|
||||
wantSize func(f *tornFixture) int64 // .dat size after the repair
|
||||
reindexed int
|
||||
readable []uint64
|
||||
empty []uint64
|
||||
absent []uint64
|
||||
}{
|
||||
{name: "the only write is re-indexed",
|
||||
ops: writes(7),
|
||||
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 1,
|
||||
readable: []uint64{7}},
|
||||
{name: "every write is re-indexed",
|
||||
ops: writes(1, 2, 3),
|
||||
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 3,
|
||||
readable: []uint64{1, 2, 3}},
|
||||
{name: "an unindexed delete is re-indexed as an empty live needle",
|
||||
ops: append(writes(1, 2, 3), tornOp{id: 2, del: true}),
|
||||
wantSize: func(f *tornFixture) int64 { return f.end }, reindexed: 4,
|
||||
readable: []uint64{1, 3}, empty: []uint64{2}},
|
||||
{name: "a complete needle is re-indexed and the partial one after it cut",
|
||||
ops: writes(1, 2),
|
||||
damage: func(t *testing.T, f *tornFixture) { f.truncateDat(t, f.midRecord(1)) },
|
||||
wantSize: func(f *tornFixture) int64 { return f.starts[1] }, reindexed: 1,
|
||||
readable: []uint64{1}, absent: []uint64{2}},
|
||||
{name: "a last needle with a bad CRC is cut",
|
||||
ops: writes(1, 2),
|
||||
damage: func(t *testing.T, f *tornFixture) { f.flipDataByte(t, f.starts[1]) },
|
||||
wantSize: func(f *tornFixture) int64 { return f.starts[1] }, reindexed: 1,
|
||||
readable: []uint64{1}, absent: []uint64{2}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := buildTornFixture(t, tc.ops, len(tc.ops))
|
||||
if tc.damage != nil {
|
||||
tc.damage(t, f)
|
||||
}
|
||||
|
||||
v := newTornTailTestVolume(t, f.dir)
|
||||
defer v.Close()
|
||||
if v.noWriteOrDelete || v.noWriteCanDelete {
|
||||
t.Fatal("volume with an unindexed .dat tail loaded read-only")
|
||||
}
|
||||
if got, want := fileSize(t, f.datName), tc.wantSize(f); got != want {
|
||||
t.Fatalf(".dat is %d bytes after load, want %d", got, want)
|
||||
}
|
||||
if got, want := fileSize(t, f.idxName), int64(tc.reindexed)*types.NeedleMapEntrySize; got != want {
|
||||
t.Fatalf(".idx is %d bytes after load, want %d (%d entries re-indexed)", got, want, tc.reindexed)
|
||||
}
|
||||
for _, id := range tc.readable {
|
||||
assertReadable(t, v, f.written[id])
|
||||
}
|
||||
for _, id := range tc.empty {
|
||||
assertEmpty(t, v, id)
|
||||
}
|
||||
for _, id := range tc.absent {
|
||||
assertNotReadable(t, v, id)
|
||||
}
|
||||
v.Close()
|
||||
|
||||
// the repaired volume reloads clean, and keeps what it indexed
|
||||
v2 := newTornTailTestVolume(t, f.dir)
|
||||
defer v2.Close()
|
||||
if v2.noWriteOrDelete {
|
||||
t.Fatal("repaired volume loaded read-only on the next load")
|
||||
}
|
||||
for _, id := range tc.readable {
|
||||
assertReadable(t, v2, f.written[id])
|
||||
}
|
||||
for _, id := range tc.empty {
|
||||
assertEmpty(t, v2, id)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An .dat an interrupted append does not explain, over an index with no rows
|
||||
// at all, loads the volume read-only: the checks that would quarantine it
|
||||
// otherwise all skip an empty index.
|
||||
func TestVolumeLoadKeepsUnexplainedTailPastEmptyIndexReadOnly(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
damage func(t *testing.T, f *tornFixture)
|
||||
}{
|
||||
{name: "zero bytes where the first record would be (id 0)",
|
||||
damage: func(t *testing.T, f *tornFixture) {
|
||||
file, err := os.OpenFile(f.datName, os.O_RDWR|os.O_APPEND, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer file.Close()
|
||||
if _, err := file.Write(make([]byte, 64)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}},
|
||||
{name: "a damaged record more data follows",
|
||||
damage: func(t *testing.T, f *tornFixture) { f.flipDataByte(t, f.starts[0]) }},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := buildTornFixture(t, writes(1, 2), 2)
|
||||
tc.damage(t, f)
|
||||
datBefore, idxBefore := fileSize(t, f.datName), fileSize(t, f.idxName)
|
||||
|
||||
v := newTornTailTestVolume(t, f.dir)
|
||||
defer v.Close()
|
||||
if !v.noWriteOrDelete {
|
||||
t.Fatal("volume with an unexplained tail past an empty index loaded writable")
|
||||
}
|
||||
if got := fileSize(t, f.datName); got != datBefore {
|
||||
t.Fatalf(".dat changed from %d to %d bytes", datBefore, got)
|
||||
}
|
||||
if got := fileSize(t, f.idxName); got != idxBefore {
|
||||
t.Fatalf(".idx changed from %d to %d bytes", idxBefore, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Every tail an interrupted append does not explain is left exactly as it is,
|
||||
// and the volume loads read-only as before.
|
||||
func TestVolumeLoadKeepsUnexplainedTailReadOnly(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
ops []tornOp
|
||||
unindexed int
|
||||
damage func(t *testing.T, f *tornFixture)
|
||||
}{
|
||||
{name: "the last indexed needle's id differs from its entry",
|
||||
ops: writes(1, 2, 3, 4), unindexed: 1,
|
||||
damage: func(t *testing.T, f *tornFixture) {
|
||||
file, err := os.OpenFile(f.datName, os.O_RDWR, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer file.Close()
|
||||
if _, err := file.WriteAt([]byte{0xff}, f.starts[2]+types.CookieSize+types.NeedleIdSize-1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}},
|
||||
{name: "the last indexed needle fails its CRC",
|
||||
ops: writes(1, 2, 3, 4), unindexed: 1,
|
||||
damage: func(t *testing.T, f *tornFixture) { f.flipDataByte(t, f.starts[2]) }},
|
||||
{name: "a zeroed data size field followed by more data",
|
||||
ops: writes(1, 2, 3, 4, 5), unindexed: 2,
|
||||
damage: func(t *testing.T, f *tornFixture) { f.zeroDataSize(t, f.starts[3]) }},
|
||||
{name: "a bad CRC followed by more data",
|
||||
ops: writes(1, 2, 3, 4, 5), unindexed: 2,
|
||||
damage: func(t *testing.T, f *tornFixture) { f.flipDataByte(t, f.starts[3]) }},
|
||||
{name: "zero bytes past the last needle (id 0)",
|
||||
ops: writes(1, 2, 3),
|
||||
damage: func(t *testing.T, f *tornFixture) {
|
||||
file, err := os.OpenFile(f.datName, os.O_RDWR|os.O_APPEND, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer file.Close()
|
||||
if _, err := file.Write(make([]byte, 64)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}},
|
||||
{name: "the index ends past the data",
|
||||
ops: writes(1, 2, 3),
|
||||
damage: func(t *testing.T, f *tornFixture) { f.truncateDat(t, f.end-10) }},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := buildTornFixture(t, tc.ops, tc.unindexed)
|
||||
tc.damage(t, f)
|
||||
datBefore, idxBefore := fileSize(t, f.datName), fileSize(t, f.idxName)
|
||||
|
||||
v := newTornTailTestVolume(t, f.dir)
|
||||
defer v.Close()
|
||||
if !v.noWriteOrDelete {
|
||||
t.Fatal("volume with an unexplained tail loaded writable")
|
||||
}
|
||||
if got := fileSize(t, f.datName); got != datBefore {
|
||||
t.Fatalf(".dat changed from %d to %d bytes", datBefore, got)
|
||||
}
|
||||
if got := fileSize(t, f.idxName); got != idxBefore {
|
||||
t.Fatalf(".idx changed from %d to %d bytes", idxBefore, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVolumeLoadLeavesCleanVolumeUntouched(t *testing.T) {
|
||||
f := buildTornFixture(t, append(writes(1, 2, 3), tornOp{id: 2, del: true}), 0)
|
||||
datBefore, idxBefore := fileSize(t, f.datName), fileSize(t, f.idxName)
|
||||
|
||||
v := newTornTailTestVolume(t, f.dir)
|
||||
defer v.Close()
|
||||
if v.noWriteOrDelete || v.noWriteCanDelete {
|
||||
t.Fatal("clean volume loaded read-only")
|
||||
}
|
||||
if got := fileSize(t, f.datName); got != datBefore {
|
||||
t.Fatalf("clean .dat changed from %d to %d bytes", datBefore, got)
|
||||
}
|
||||
if got := fileSize(t, f.idxName); got != idxBefore {
|
||||
t.Fatalf("clean .idx changed from %d to %d bytes", idxBefore, got)
|
||||
}
|
||||
assertReadable(t, v, f.written[1])
|
||||
assertReadable(t, v, f.written[3])
|
||||
assertNotReadable(t, v, 2)
|
||||
}
|
||||
|
||||
// A volume persisted read-only is not repaired: the tail stays for whoever
|
||||
// marked it.
|
||||
func TestVolumeLoadLeavesReadOnlyVolumeTailAlone(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
v := newTornTailTestVolume(t, dir)
|
||||
for _, id := range []uint64{1, 2, 99} {
|
||||
if _, _, _, err := v.writeNeedle2(newRandomNeedle(id), true, false, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := v.PersistReadOnly(true, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
datName, idxName := v.FileName(".dat"), v.FileName(".idx")
|
||||
v.Close()
|
||||
if err := os.Truncate(idxName, fileSize(t, idxName)-types.NeedleMapEntrySize); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
datBefore, idxBefore := fileSize(t, datName), fileSize(t, idxName)
|
||||
|
||||
v = newTornTailTestVolume(t, dir)
|
||||
defer v.Close()
|
||||
if !v.noWriteOrDelete {
|
||||
t.Fatal("volume persisted read-only loaded writable")
|
||||
}
|
||||
if got := fileSize(t, datName); got != datBefore {
|
||||
t.Fatalf(".dat of a read-only volume changed from %d to %d bytes", datBefore, got)
|
||||
}
|
||||
if got := fileSize(t, idxName); got != idxBefore {
|
||||
t.Fatalf(".idx of a read-only volume changed from %d to %d bytes", idxBefore, got)
|
||||
}
|
||||
}
|
||||
|
||||
// A canDelete volume still appends a tombstone record on every delete, so it
|
||||
// can tear a tail the same way: it is repaired and keeps taking deletes.
|
||||
func TestVolumeLoadRepairsTailOnCanDeleteVolume(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
v := newTornTailTestVolume(t, dir)
|
||||
var last *needle.Needle
|
||||
for _, id := range []uint64{1, 2, 99} {
|
||||
last = newRandomNeedle(id)
|
||||
if _, _, _, err := v.writeNeedle2(last, true, false, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := v.PersistReadOnly(true, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
idxName := v.FileName(".idx")
|
||||
v.Close()
|
||||
if err := os.Truncate(idxName, fileSize(t, idxName)-types.NeedleMapEntrySize); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
v = newTornTailTestVolume(t, dir)
|
||||
defer v.Close()
|
||||
if v.noWriteOrDelete || !v.noWriteCanDelete {
|
||||
t.Fatal("canDelete volume with a torn tail did not load canDelete after the repair")
|
||||
}
|
||||
assertReadable(t, v, last)
|
||||
}
|
||||
|
||||
// A torn record whose header advertises a positive size smaller than the
|
||||
// body's own 4-byte data-size field is damaged, not decodable — reading it
|
||||
// used to panic on the slice. As the last record it is cut, and a canDelete
|
||||
// volume keeps taking deletes after the repair.
|
||||
func TestVolumeLoadCutsDamagedSmallSizeTailOnCanDeleteVolume(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
v := newTornTailTestVolume(t, dir)
|
||||
var last *needle.Needle
|
||||
for _, id := range []uint64{1, 2, 99} {
|
||||
last = newRandomNeedle(id)
|
||||
if _, _, _, err := v.writeNeedle2(last, true, false, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := v.PersistReadOnly(true, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
datName, idxName := v.FileName(".dat"), v.FileName(".idx")
|
||||
version := v.Version()
|
||||
v.Close()
|
||||
if err := os.Truncate(idxName, fileSize(t, idxName)-types.NeedleMapEntrySize); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
datBefore := fileSize(t, datName)
|
||||
|
||||
// a complete-looking record whose header claims a 2-byte body
|
||||
damagedSize := types.Size(2)
|
||||
record := make([]byte, needle.GetActualSize(damagedSize, version))
|
||||
util.Uint32toBytes(record[0:types.CookieSize], 0xabcd)
|
||||
util.Uint64toBytes(record[types.CookieSize:types.CookieSize+types.NeedleIdSize], uint64(types.Uint64ToNeedleId(7)))
|
||||
util.Uint32toBytes(record[types.CookieSize+types.NeedleIdSize:types.NeedleHeaderSize], uint32(damagedSize))
|
||||
dat, err := os.OpenFile(datName, os.O_WRONLY|os.O_APPEND, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := dat.Write(record); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := dat.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
v = newTornTailTestVolume(t, dir)
|
||||
defer v.Close()
|
||||
if v.noWriteOrDelete || !v.noWriteCanDelete {
|
||||
t.Fatal("canDelete volume with a damaged-size tail did not load canDelete after the repair")
|
||||
}
|
||||
assertReadable(t, v, last)
|
||||
if got := fileSize(t, datName); got != datBefore {
|
||||
t.Fatalf("damaged tail was not cut: .dat is %d bytes, want %d", got, datBefore)
|
||||
}
|
||||
}
|
||||
|
||||
// An .idx that ends in a partial entry keeps the existing behaviour:
|
||||
// the volume does not load writable and neither file is changed.
|
||||
func TestVolumeLoadLeavesPartialIdxEntryAlone(t *testing.T) {
|
||||
f := buildTornFixture(t, writes(1, 2, 3), 0)
|
||||
idxPartial := fileSize(t, f.idxName) - types.NeedleMapEntrySize/2
|
||||
if err := os.Truncate(f.idxName, idxPartial); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
datBefore := fileSize(t, f.datName)
|
||||
|
||||
v2, err := NewVolume(f.dir, f.dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
|
||||
if err == nil {
|
||||
t.Logf("partial .idx: volume loaded, noWriteOrDelete=%v", v2.noWriteOrDelete)
|
||||
if !v2.noWriteOrDelete {
|
||||
v2.Close()
|
||||
t.Fatal("volume with a partial .idx entry loaded writable")
|
||||
}
|
||||
v2.Close()
|
||||
} else {
|
||||
t.Logf("partial .idx: volume not loaded: %v", err)
|
||||
}
|
||||
if got := fileSize(t, f.datName); got != datBefore {
|
||||
t.Fatalf(".dat changed from %d to %d bytes", datBefore, got)
|
||||
}
|
||||
if got := fileSize(t, f.idxName); got != idxPartial {
|
||||
t.Fatalf(".idx changed from %d to %d bytes", idxPartial, got)
|
||||
}
|
||||
}
|
||||
|
||||
// faultyDatFile fails Sync, or the read of a whole record at one offset, the
|
||||
// way a failing disk does.
|
||||
type faultyDatFile struct {
|
||||
backend.BackendStorageFile
|
||||
failSync bool
|
||||
failRecordAt int64
|
||||
failRecordSet bool
|
||||
}
|
||||
|
||||
var errFaultyDisk = errors.New("input/output error")
|
||||
|
||||
func (f *faultyDatFile) Sync() error {
|
||||
if f.failSync {
|
||||
return errFaultyDisk
|
||||
}
|
||||
return f.BackendStorageFile.Sync()
|
||||
}
|
||||
|
||||
func (f *faultyDatFile) ReadAt(p []byte, off int64) (int, error) {
|
||||
if f.failRecordSet && off == f.failRecordAt && len(p) > types.NeedleHeaderSize {
|
||||
return 0, errFaultyDisk
|
||||
}
|
||||
return f.BackendStorageFile.ReadAt(p, off)
|
||||
}
|
||||
|
||||
// A read error is not evidence of a torn write: the last record is kept.
|
||||
func TestWalkUnindexedDatTailKeepsRecordOnReadError(t *testing.T) {
|
||||
f := buildTornFixture(t, writes(1, 2, 3, 4), 1)
|
||||
file, err := os.Open(f.datName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dat := &faultyDatFile{BackendStorageFile: backend.NewDiskFile(file), failRecordAt: f.starts[3], failRecordSet: true}
|
||||
defer dat.Close()
|
||||
|
||||
records, cutAt, err := walkUnindexedDatTail(dat, needle.Version3, f.starts[3], f.end, 0)
|
||||
if err == nil {
|
||||
t.Fatalf("read error on the last record: walk returned %d record(s) and a cut at %d, want an error", len(records), cutAt)
|
||||
}
|
||||
if errors.Is(err, errTailNotTorn) {
|
||||
t.Fatalf("read error reported as an unexplained tail: %v", err)
|
||||
}
|
||||
if !errors.Is(err, errFaultyDisk) {
|
||||
t.Fatalf("walk error %v does not carry the read error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A repair that changed a file but could not sync it fails the integrity
|
||||
// check, so the volume loads read-only rather than writable on an unsynced
|
||||
// repair.
|
||||
func TestCheckVolumeDataIntegrityFailsOnUnsyncedRepair(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
v := newTornTailTestVolume(t, dir)
|
||||
var starts []int64
|
||||
for _, id := range []uint64{1, 2, 3, 4} {
|
||||
at, _, _ := v.DataBackend.GetStat()
|
||||
starts = append(starts, at)
|
||||
if _, _, _, err := v.writeNeedle2(newRandomNeedle(id), true, false, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
end, _, _ := v.DataBackend.GetStat()
|
||||
// persisted read-only so the load below does not repair the tail itself
|
||||
if err := v.PersistReadOnly(true, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
datName, idxName := v.FileName(".dat"), v.FileName(".idx")
|
||||
v.Close()
|
||||
if err := os.Truncate(idxName, fileSize(t, idxName)-types.NeedleMapEntrySize); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Truncate(datName, midRecordBody(starts[3], end)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
v = newTornTailTestVolume(t, dir)
|
||||
defer v.Close()
|
||||
v.noWriteOrDelete = false
|
||||
v.DataBackend = &faultyDatFile{BackendStorageFile: v.DataBackend, failSync: true}
|
||||
indexFile, err := os.OpenFile(idxName, os.O_RDWR, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer indexFile.Close()
|
||||
|
||||
if _, err := CheckVolumeDataIntegrity(v, indexFile); err == nil {
|
||||
t.Fatal("integrity check passed although the repaired .dat was not synced")
|
||||
}
|
||||
}
|
||||
|
||||
// partialWriteIndex accepts only the first n bytes of a write, as a full disk
|
||||
// does.
|
||||
type partialWriteIndex struct {
|
||||
data []byte
|
||||
accept int
|
||||
truncated bool
|
||||
}
|
||||
|
||||
func (p *partialWriteIndex) WriteAt(b []byte, off int64) (int, error) {
|
||||
n := min(len(b), p.accept)
|
||||
if end := int(off) + n; end > len(p.data) {
|
||||
p.data = append(p.data, make([]byte, end-len(p.data))...)
|
||||
}
|
||||
copy(p.data[off:], b[:n])
|
||||
if n < len(b) {
|
||||
return n, errors.New("no space left on device")
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (p *partialWriteIndex) Truncate(size int64) error {
|
||||
p.data = p.data[:size]
|
||||
p.truncated = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *partialWriteIndex) Sync() error { return nil }
|
||||
func (p *partialWriteIndex) Name() string { return "test.idx" }
|
||||
|
||||
// A failed append leaves no partial entry behind.
|
||||
func TestAppendIndexEntriesRemovesPartialWrite(t *testing.T) {
|
||||
idxFile := &partialWriteIndex{data: make([]byte, 2*types.NeedleMapEntrySize), accept: types.NeedleMapEntrySize + 5}
|
||||
entries := make([]byte, 2*types.NeedleMapEntrySize)
|
||||
if err := appendIndexEntries(idxFile, entries, 2*types.NeedleMapEntrySize); err == nil {
|
||||
t.Fatal("a partial append reported success")
|
||||
}
|
||||
if got, want := len(idxFile.data), 2*types.NeedleMapEntrySize; got != want {
|
||||
t.Fatalf(".idx is %d bytes after a failed append, want %d", got, want)
|
||||
}
|
||||
}
|
||||
@@ -427,9 +427,21 @@ func TestCheckVolumeDataIntegrityVerifiesDeletionTail(t *testing.T) {
|
||||
}
|
||||
defer idxFile.Close()
|
||||
|
||||
// A read-only volume keeps its tail: the check must report it.
|
||||
v.noWriteOrDelete = true
|
||||
if _, err := CheckVolumeDataIntegrity(v, idxFile); err == nil {
|
||||
t.Fatal("CheckVolumeDataIntegrity should detect bytes past a deletion-tombstone tail")
|
||||
}
|
||||
|
||||
// A writable volume would have a torn needle re-indexed or cut, but 64 zero
|
||||
// bytes are no needle (id 0): they are reported and left in place.
|
||||
v.noWriteOrDelete = false
|
||||
if _, err := CheckVolumeDataIntegrity(v, idxFile); err == nil {
|
||||
t.Fatal("CheckVolumeDataIntegrity should detect zero bytes past a deletion-tombstone tail on a writable volume")
|
||||
}
|
||||
if got, _, _ := v.DataBackend.GetStat(); got != datSize+64 {
|
||||
t.Fatalf(".dat is %d bytes after the check, want %d (nothing cut)", got, datSize+64)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVolumeLoadStaysWritableWithKeySortedIndex exercises end to
|
||||
|
||||
@@ -63,6 +63,8 @@ func loadVolumeWithoutWorker(dirname string, dirIdx string, collection string, i
|
||||
//
|
||||
// No-op when v.nm is already a writable form.
|
||||
func (v *Volume) reopenIdxForWrite() error {
|
||||
v.dataFileSyncLock.Lock()
|
||||
defer v.dataFileSyncLock.Unlock()
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
return v.reopenIdxForWriteLocked()
|
||||
|
||||
@@ -80,6 +80,8 @@ func (v *Volume) HasRemoteFile() bool {
|
||||
// backend concurrently. load() must instead use loadRemoteFileLocked, since it
|
||||
// can be reached with the lock already held (CommitCompact).
|
||||
func (v *Volume) LoadRemoteFile() error {
|
||||
v.dataFileSyncLock.Lock()
|
||||
defer v.dataFileSyncLock.Unlock()
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
return v.loadRemoteFileLocked()
|
||||
|
||||
@@ -177,6 +177,8 @@ func (v *Volume) CommitCompact() error {
|
||||
}
|
||||
defer v.isCompactionInProgress.Store(false)
|
||||
|
||||
v.dataFileSyncLock.Lock()
|
||||
defer v.dataFileSyncLock.Unlock()
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
|
||||
@@ -367,6 +369,8 @@ func (v *Volume) cleanupCompact() error {
|
||||
// Serialize with CommitCompact's swap and refuse to unlink .cpd/.cpx while a
|
||||
// .cpc marker exists: those temp files are the only inputs reconcile can roll
|
||||
// forward to, so removing them mid-commit would strand a decided swap.
|
||||
v.dataFileSyncLock.Lock()
|
||||
defer v.dataFileSyncLock.Unlock()
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
if util.FileExists(v.FileName(".cpc")) {
|
||||
|
||||
+195
-205
@@ -16,101 +16,6 @@ var ErrorNotFound = errors.New("not found")
|
||||
var ErrorDeleted = errors.New("already deleted")
|
||||
var ErrorSizeMismatch = errors.New("size mismatch")
|
||||
|
||||
type batchNeedleSnapshot struct {
|
||||
id NeedleId
|
||||
found bool
|
||||
offset Offset
|
||||
size Size
|
||||
changed bool
|
||||
}
|
||||
|
||||
func newBatchNeedleSnapshot(v *Volume, id NeedleId) *batchNeedleSnapshot {
|
||||
snapshot := &batchNeedleSnapshot{id: id}
|
||||
if element, found := v.nm.Get(id); found && element != nil {
|
||||
snapshot.found = true
|
||||
snapshot.offset = element.Offset
|
||||
snapshot.size = element.Size
|
||||
}
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func (s *batchNeedleSnapshot) observeCurrent(v *Volume) {
|
||||
element, found := v.nm.Get(s.id)
|
||||
if found != s.found {
|
||||
s.changed = true
|
||||
return
|
||||
}
|
||||
if found && (element == nil || element.Offset != s.offset || element.Size != s.size) {
|
||||
s.changed = true
|
||||
}
|
||||
}
|
||||
|
||||
func (v *Volume) restoreBatchNeedle(snapshot *batchNeedleSnapshot) error {
|
||||
mapRollbacker, ok := v.nm.(batchMapRollbacker)
|
||||
if !ok {
|
||||
return fmt.Errorf("mapper %T cannot restore its mappings", v.nm)
|
||||
}
|
||||
if snapshot.found {
|
||||
return mapRollbacker.restoreMapping(snapshot.id, snapshot.offset, snapshot.size)
|
||||
}
|
||||
// A plain Delete would leave a tombstoned entry whose stale offset makes
|
||||
// the next write to this needle fail reading a header that no longer exists.
|
||||
return mapRollbacker.removeMapping(snapshot.id)
|
||||
}
|
||||
|
||||
func (v *Volume) rollbackBatch(end int64, indexEnd int64, snapshots []*batchNeedleSnapshot,
|
||||
metricRollbacker batchMetricRollbacker, metrics batchMapMetricSnapshot) error {
|
||||
var recoveryErrors []error
|
||||
for _, snapshot := range snapshots {
|
||||
if !snapshot.changed {
|
||||
continue
|
||||
}
|
||||
if err := v.restoreBatchNeedle(snapshot); err != nil {
|
||||
recoveryErrors = append(recoveryErrors,
|
||||
fmt.Errorf("restore needle %d: %w", snapshot.id, err))
|
||||
}
|
||||
}
|
||||
|
||||
if len(recoveryErrors) == 0 {
|
||||
rollbacker, ok := v.nm.(batchIndexRollbacker)
|
||||
if !ok {
|
||||
recoveryErrors = append(recoveryErrors,
|
||||
fmt.Errorf("mapper %T cannot truncate its index", v.nm))
|
||||
} else if err := rollbacker.truncateIndex(indexEnd); err != nil {
|
||||
recoveryErrors = append(recoveryErrors,
|
||||
fmt.Errorf("truncate index to %d: %w", indexEnd, err))
|
||||
}
|
||||
}
|
||||
|
||||
if len(recoveryErrors) == 0 {
|
||||
if err := v.nm.Sync(); err != nil {
|
||||
recoveryErrors = append(recoveryErrors,
|
||||
fmt.Errorf("sync recovered index: %w", err))
|
||||
}
|
||||
}
|
||||
|
||||
if len(recoveryErrors) == 0 {
|
||||
if err := v.DataBackend.Truncate(end); err != nil {
|
||||
recoveryErrors = append(recoveryErrors,
|
||||
fmt.Errorf("truncate %s to %d: %w", v.DataBackend.Name(), end, err))
|
||||
} else if err := v.DataBackend.Sync(); err != nil {
|
||||
recoveryErrors = append(recoveryErrors,
|
||||
fmt.Errorf("sync truncated %s: %w", v.DataBackend.Name(), err))
|
||||
}
|
||||
}
|
||||
|
||||
if len(recoveryErrors) == 0 {
|
||||
if metricRollbacker == nil {
|
||||
recoveryErrors = append(recoveryErrors,
|
||||
fmt.Errorf("mapper %T cannot restore its metrics", v.nm))
|
||||
} else {
|
||||
metricRollbacker.restoreBatchMetrics(metrics)
|
||||
}
|
||||
}
|
||||
|
||||
return errors.Join(recoveryErrors...)
|
||||
}
|
||||
|
||||
// isFileUnchanged checks whether this needle to write is same as last one.
|
||||
// It requires serialized access in the same volume.
|
||||
func (v *Volume) isFileUnchanged(n *needle.Needle) bool {
|
||||
@@ -140,6 +45,8 @@ var ErrVolumeNotEmpty = fmt.Errorf("volume not empty")
|
||||
// true the cloud-tier object backing the volume is left intact — used by
|
||||
// moves where another server is taking over the same .vif.
|
||||
func (v *Volume) Destroy(onlyEmpty bool, onlyGarbage bool, keepRemoteData bool) (err error) {
|
||||
v.dataFileSyncLock.Lock()
|
||||
defer v.dataFileSyncLock.Unlock()
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
return v.destroyLocked(onlyEmpty, onlyGarbage, keepRemoteData)
|
||||
@@ -264,6 +171,8 @@ func (v *Volume) asyncRequestAppend(request *needle.AsyncRequest) bool {
|
||||
|
||||
func (v *Volume) syncWrite(n *needle.Needle, checkCookie bool, fsync bool) (offset uint64, size Size, isUnchanged bool, err error) {
|
||||
// glog.V(4).Infof("writing needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
|
||||
v.dataFileSyncLock.Lock()
|
||||
defer v.dataFileSyncLock.Unlock()
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
|
||||
@@ -288,65 +197,47 @@ func (v *Volume) syncWrite(n *needle.Needle, checkCookie bool, fsync bool) (offs
|
||||
if statErr != nil {
|
||||
return 0, 0, false, fmt.Errorf("cannot read current volume position: %v", statErr)
|
||||
}
|
||||
priorOffset, priorSize, hasPrior := Offset{}, Size(0), false
|
||||
if nv, found := v.nm.Get(n.Id); found {
|
||||
priorOffset, priorSize, hasPrior = nv.Offset, nv.Size, true
|
||||
}
|
||||
|
||||
offset, size, isUnchanged, err = v.doWriteRequest(n, checkCookie, fsync)
|
||||
lastAppendAtNs := v.lastAppendAtNs
|
||||
lastWriteAppendAtNs := v.lastWriteAppendAtNs
|
||||
lastWriteNeedleKey := v.lastWriteNeedleKey
|
||||
lastWriteDeleted := v.lastWriteDeleted
|
||||
lastModifiedTsSeconds := v.lastModifiedTsSeconds
|
||||
|
||||
offset, size, isUnchanged, err = v.appendWriteRequest(n, checkCookie, fsync)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if syncErr := v.DataBackend.Sync(); syncErr != nil {
|
||||
// fsync with the access lock dropped so same-volume reads do not wait on
|
||||
// it; writers and compaction stay excluded by dataFileSyncLock. Nothing
|
||||
// has been published yet, so no reader can capture the appended offset.
|
||||
backend := v.DataBackend
|
||||
v.dataFileAccessLock.Unlock()
|
||||
syncErr := backend.Sync()
|
||||
v.dataFileAccessLock.Lock()
|
||||
if syncErr != nil {
|
||||
v.checkReadWriteError(syncErr)
|
||||
v.lastAppendAtNs = lastAppendAtNs
|
||||
v.lastWriteAppendAtNs = lastWriteAppendAtNs
|
||||
v.lastWriteNeedleKey = lastWriteNeedleKey
|
||||
v.lastWriteDeleted = lastWriteDeleted
|
||||
v.lastModifiedTsSeconds = lastModifiedTsSeconds
|
||||
if !isUnchanged {
|
||||
v.rollbackUnflushedWrite(n, offset, end, priorOffset, priorSize, hasPrior)
|
||||
// Nothing was published, so the whole rollback is taking the
|
||||
// unflushed append back off the .dat.
|
||||
if te := v.DataBackend.Truncate(end); te != nil {
|
||||
v.markIoUnavailable(fmt.Errorf("truncate %s back to %d after a failed fsync: %w",
|
||||
v.DataBackend.Name(), end, te))
|
||||
}
|
||||
}
|
||||
return 0, 0, false, syncErr
|
||||
}
|
||||
if !isUnchanged {
|
||||
err = v.publishWriteRequest(n, offset, fsync)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// rollbackUnflushedWrite undoes an append whose fsync failed: the bytes are not
|
||||
// data we can vouch for, so they come back off the .dat and the needle map goes
|
||||
// back to what it pointed at before, rather than at an offset past the new end.
|
||||
func (v *Volume) rollbackUnflushedWrite(n *needle.Needle, offset uint64, end int64, priorOffset Offset, priorSize Size, hasPrior bool) {
|
||||
var recoveryErr error
|
||||
if te := v.DataBackend.Truncate(end); te != nil {
|
||||
recoveryErr = fmt.Errorf("truncate %s back to %d: %w", v.DataBackend.Name(), end, te)
|
||||
}
|
||||
current, found := v.nm.Get(n.Id)
|
||||
if found && current.Offset.ToActualOffset() == int64(offset) {
|
||||
var err error
|
||||
if hasPrior {
|
||||
err = v.nm.Put(n.Id, priorOffset, priorSize)
|
||||
} else {
|
||||
// The tombstone must reach .idx so a replay forgets the needle, but
|
||||
// the negated entry it leaves in memory points at truncated bytes
|
||||
// and would fail the next write, so erase the mapping as well.
|
||||
err = v.nm.Delete(n.Id, ToOffset(int64(offset)))
|
||||
if err == nil {
|
||||
if rb, ok := v.nm.(batchMapRollbacker); ok {
|
||||
err = rb.removeMapping(n.Id)
|
||||
} else {
|
||||
err = fmt.Errorf("mapper %T cannot remove mapping", v.nm)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil && n.Id == v.lastWriteNeedleKey {
|
||||
v.lastWriteAppendAtNs, v.lastWriteNeedleKey = 0, 0
|
||||
v.lastWriteDeleted = true
|
||||
}
|
||||
if err != nil {
|
||||
recoveryErr = errors.Join(recoveryErr,
|
||||
fmt.Errorf("roll back the index of needle %d in volume %d: %w", n.Id, v.Id, err))
|
||||
}
|
||||
}
|
||||
if recoveryErr != nil {
|
||||
v.markIoUnavailable(recoveryErr)
|
||||
}
|
||||
}
|
||||
|
||||
// writeNeedle2 appends a needle. A durable write normally goes through the
|
||||
// async batch worker, which fsyncs once for the whole batch; while the server
|
||||
// is stopping the worker is winding down, so it is flushed inline instead. Both
|
||||
@@ -379,6 +270,17 @@ func (v *Volume) writeNeedle2(n *needle.Needle, checkCookie bool, fsync bool, is
|
||||
}
|
||||
|
||||
func (v *Volume) doWriteRequest(n *needle.Needle, checkCookie bool, fsync bool) (offset uint64, size Size, isUnchanged bool, err error) {
|
||||
offset, size, isUnchanged, err = v.appendWriteRequest(n, checkCookie, fsync)
|
||||
if err != nil || isUnchanged {
|
||||
return
|
||||
}
|
||||
err = v.publishWriteRequest(n, offset, fsync)
|
||||
return
|
||||
}
|
||||
|
||||
// appendWriteRequest is doWriteRequest through the .dat append, leaving the
|
||||
// needle-map update to publishWriteRequest.
|
||||
func (v *Volume) appendWriteRequest(n *needle.Needle, checkCookie bool, fsync bool) (offset uint64, size Size, isUnchanged bool, err error) {
|
||||
// glog.V(4).Infof("writing needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
|
||||
// Re-check under the write lock: the outer checks run before the needle
|
||||
// is assembled, and VolumeMarkReadonly can land in between.
|
||||
@@ -426,7 +328,16 @@ func (v *Volume) doWriteRequest(n *needle.Needle, checkCookie bool, fsync bool)
|
||||
v.lastWriteNeedleKey = n.Id
|
||||
v.lastWriteDeleted = false
|
||||
|
||||
// add to needle map
|
||||
return
|
||||
}
|
||||
|
||||
// publishWriteRequest indexes an already-appended needle. It is split from
|
||||
// appendWriteRequest so a durable write can fsync before the mapping exists:
|
||||
// an index entry that outlives the bytes it points at loads read-only, and
|
||||
// an unpublished offset can never be captured by an in-flight read before a
|
||||
// failed sync truncates it.
|
||||
func (v *Volume) publishWriteRequest(n *needle.Needle, offset uint64, fsync bool) (err error) {
|
||||
nv, ok := v.nm.Get(n.Id)
|
||||
if !ok || uint64(nv.Offset.ToActualOffset()) < offset {
|
||||
if err = v.nm.Put(n.Id, ToOffset(int64(offset)), n.Size); err != nil {
|
||||
err = fmt.Errorf("index needle %d of volume %d at offset %d: %w", n.Id, v.Id, offset, err)
|
||||
@@ -449,6 +360,8 @@ func (v *Volume) doWriteRequest(n *needle.Needle, checkCookie bool, fsync bool)
|
||||
|
||||
func (v *Volume) syncDelete(n *needle.Needle) (Size, error) {
|
||||
// glog.V(4).Infof("delete needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
|
||||
v.dataFileSyncLock.Lock()
|
||||
defer v.dataFileSyncLock.Unlock()
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
|
||||
@@ -487,37 +400,81 @@ func (v *Volume) deleteNeedle2(n *needle.Needle) (Size, error) {
|
||||
|
||||
func (v *Volume) doDeleteRequest(n *needle.Needle) (Size, error) {
|
||||
glog.V(4).Infof("delete needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
|
||||
nv, ok := v.nm.Get(n.Id)
|
||||
// fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
|
||||
if ok && !nv.Size.IsDeleted() {
|
||||
var offset uint64
|
||||
var err error
|
||||
size := nv.Size
|
||||
if !v.HasRemoteFile() {
|
||||
n.Data = nil
|
||||
n.UpdateAppendAtNs(v.lastAppendAtNs)
|
||||
offset, _, _, err = n.Append(v.DataBackend, v.Version())
|
||||
v.checkReadWriteError(err)
|
||||
if err != nil {
|
||||
return size, err
|
||||
}
|
||||
}
|
||||
v.lastAppendAtNs = n.AppendAtNs
|
||||
if err = v.nm.Delete(n.Id, ToOffset(int64(offset))); err != nil {
|
||||
return size, err
|
||||
}
|
||||
if n.Id == v.lastWriteNeedleKey {
|
||||
v.lastWriteAppendAtNs, v.lastWriteNeedleKey = 0, 0
|
||||
v.lastWriteDeleted = true
|
||||
}
|
||||
size, offset, tombstoned, err := v.appendDeleteRequest(n)
|
||||
if err != nil || !tombstoned {
|
||||
return size, err
|
||||
}
|
||||
return 0, nil
|
||||
if err = v.publishDeleteRequest(n, offset); err != nil {
|
||||
return size, err
|
||||
}
|
||||
return size, nil
|
||||
}
|
||||
|
||||
// appendDeleteRequest writes the tombstone record but leaves the map update
|
||||
// to publishDeleteRequest, so a batch can fsync before any deletion is
|
||||
// visible — same publication-after-sync ordering as writes.
|
||||
func (v *Volume) appendDeleteRequest(n *needle.Needle) (size Size, offset uint64, tombstoned bool, err error) {
|
||||
nv, ok := v.nm.Get(n.Id)
|
||||
// fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
|
||||
if !ok || nv.Size.IsDeleted() {
|
||||
return 0, 0, false, nil
|
||||
}
|
||||
size = nv.Size
|
||||
if !v.HasRemoteFile() {
|
||||
n.Data = nil
|
||||
n.UpdateAppendAtNs(v.lastAppendAtNs)
|
||||
offset, _, _, err = n.Append(v.DataBackend, v.Version())
|
||||
v.checkReadWriteError(err)
|
||||
if err != nil {
|
||||
return size, 0, false, err
|
||||
}
|
||||
}
|
||||
v.lastAppendAtNs = n.AppendAtNs
|
||||
return size, offset, true, nil
|
||||
}
|
||||
|
||||
func (v *Volume) publishDeleteRequest(n *needle.Needle, offset uint64) error {
|
||||
if err := v.nm.Delete(n.Id, ToOffset(int64(offset))); err != nil {
|
||||
return err
|
||||
}
|
||||
if n.Id == v.lastWriteNeedleKey {
|
||||
v.lastWriteAppendAtNs, v.lastWriteNeedleKey = 0, 0
|
||||
v.lastWriteDeleted = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *Volume) processBatch(currentRequests []*needle.AsyncRequest) {
|
||||
v.dataFileSyncLock.Lock()
|
||||
defer v.dataFileSyncLock.Unlock()
|
||||
|
||||
// The batch is applied in runs of distinct needle ids: a repeated id
|
||||
// starts a new run so its dedup, cookie and delete checks see the earlier
|
||||
// operation's published result — the same rule as Rust's
|
||||
// write_needles_grouped.
|
||||
seen := make(map[NeedleId]bool, len(currentRequests))
|
||||
start := 0
|
||||
for i := 0; i < len(currentRequests); i++ {
|
||||
if seen[currentRequests[i].N.Id] {
|
||||
v.processBatchRun(currentRequests[start:i])
|
||||
seen = make(map[NeedleId]bool, len(currentRequests)-i)
|
||||
start = i
|
||||
}
|
||||
seen[currentRequests[i].N.Id] = true
|
||||
}
|
||||
if start < len(currentRequests) {
|
||||
v.processBatchRun(currentRequests[start:])
|
||||
}
|
||||
}
|
||||
|
||||
// processBatchRun applies one run of distinct-id requests: every .dat
|
||||
// mutation is staged, the run is synced once with the access lock dropped,
|
||||
// and only then are the map changes published — in request order, and only
|
||||
// over an older offset — so a failed sync rolls back bytes no reader ever
|
||||
// resolved. A durable entry that fails to index stops the volume taking
|
||||
// writes, and the entries after it in the run are refused read only.
|
||||
func (v *Volume) processBatchRun(run []*needle.AsyncRequest) {
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
|
||||
end, e := int64(0), error(nil)
|
||||
if unavailableErr := v.UnavailableError(); unavailableErr != nil {
|
||||
@@ -528,62 +485,65 @@ func (v *Volume) processBatch(currentRequests []*needle.AsyncRequest) {
|
||||
end, _, e = v.DataBackend.GetStat()
|
||||
}
|
||||
if e != nil {
|
||||
for i := 0; i < len(currentRequests); i++ {
|
||||
currentRequests[i].Complete(0, 0, false,
|
||||
v.dataFileAccessLock.Unlock()
|
||||
for i := 0; i < len(run); i++ {
|
||||
run[i].Complete(0, 0, false,
|
||||
fmt.Errorf("cannot read current volume position: %v", e))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
batchSnapshots := make(map[NeedleId]*batchNeedleSnapshot, len(currentRequests))
|
||||
orderedSnapshots := make([]*batchNeedleSnapshot, 0, len(currentRequests))
|
||||
metricRollbacker, _ := v.nm.(batchMetricRollbacker)
|
||||
var batchMetrics batchMapMetricSnapshot
|
||||
if metricRollbacker != nil {
|
||||
batchMetrics = metricRollbacker.snapshotBatchMetrics()
|
||||
}
|
||||
indexEnd := int64(v.nm.IndexFileSize())
|
||||
batchLastAppendAtNs := v.lastAppendAtNs
|
||||
batchLastWriteAppendAtNs := v.lastWriteAppendAtNs
|
||||
batchLastWriteNeedleKey := v.lastWriteNeedleKey
|
||||
batchLastWriteDeleted := v.lastWriteDeleted
|
||||
batchLastModifiedTsSeconds := v.lastModifiedTsSeconds
|
||||
for i := 0; i < len(currentRequests); i++ {
|
||||
needleID := currentRequests[i].N.Id
|
||||
snapshot, found := batchSnapshots[needleID]
|
||||
if !found {
|
||||
snapshot = newBatchNeedleSnapshot(v, needleID)
|
||||
batchSnapshots[needleID] = snapshot
|
||||
orderedSnapshots = append(orderedSnapshots, snapshot)
|
||||
}
|
||||
|
||||
stagedWriteOffsets := make([]uint64, len(run))
|
||||
stagedWriteOk := make([]bool, len(run))
|
||||
stagedDeleteOffsets := make([]uint64, len(run))
|
||||
stagedDeleteOk := make([]bool, len(run))
|
||||
for i := 0; i < len(run); i++ {
|
||||
// Every queued request meets the same refusal it would get sent on
|
||||
// its own: once a durable index update fails the volume stops taking
|
||||
// writes, and a lone write is turned away before it appends.
|
||||
if currentRequests[i].IsWriteRequest {
|
||||
if run[i].IsWriteRequest {
|
||||
if unavailableErr := v.UnavailableError(); unavailableErr != nil {
|
||||
currentRequests[i].UpdateResult(0, 0, false, unavailableErr)
|
||||
run[i].UpdateResult(0, 0, false, unavailableErr)
|
||||
} else if v.IsReadOnly() {
|
||||
currentRequests[i].UpdateResult(0, 0, false, fmt.Errorf("volume %d is read only", v.Id))
|
||||
run[i].UpdateResult(0, 0, false, fmt.Errorf("volume %d is read only", v.Id))
|
||||
} else {
|
||||
offset, size, isUnchanged, err := v.doWriteRequest(currentRequests[i].N, true, true)
|
||||
currentRequests[i].UpdateResult(offset, uint64(size), isUnchanged, err)
|
||||
offset, size, isUnchanged, err := v.appendWriteRequest(run[i].N, true, true)
|
||||
if err == nil && !isUnchanged {
|
||||
stagedWriteOffsets[i] = offset
|
||||
stagedWriteOk[i] = true
|
||||
}
|
||||
run[i].UpdateResult(offset, uint64(size), isUnchanged, err)
|
||||
}
|
||||
} else {
|
||||
if unavailableErr := v.UnavailableError(); unavailableErr != nil {
|
||||
currentRequests[i].UpdateResult(0, 0, false, unavailableErr)
|
||||
run[i].UpdateResult(0, 0, false, unavailableErr)
|
||||
} else if _, noWriteOrDelete, _, _ := v.ReadOnlyReasons(); noWriteOrDelete {
|
||||
currentRequests[i].UpdateResult(0, 0, false, fmt.Errorf("volume %d is read only", v.Id))
|
||||
run[i].UpdateResult(0, 0, false, fmt.Errorf("volume %d is read only", v.Id))
|
||||
} else {
|
||||
size, err := v.doDeleteRequest(currentRequests[i].N)
|
||||
currentRequests[i].UpdateResult(0, uint64(size), false, err)
|
||||
size, offset, tombstoned, err := v.appendDeleteRequest(run[i].N)
|
||||
if err == nil && tombstoned {
|
||||
stagedDeleteOffsets[i] = offset
|
||||
stagedDeleteOk[i] = true
|
||||
}
|
||||
run[i].UpdateResult(0, uint64(size), false, err)
|
||||
}
|
||||
}
|
||||
snapshot.observeCurrent(v)
|
||||
}
|
||||
|
||||
// if sync error the batch is not durable; restore it before another
|
||||
// operation observes the volume
|
||||
if syncErr := v.DataBackend.Sync(); syncErr != nil {
|
||||
// The sync excludes writers and compaction via dataFileSyncLock but not
|
||||
// readers: nothing is published yet, so dropping the access lock here
|
||||
// lets same-volume reads proceed during the fsync.
|
||||
backend := v.DataBackend
|
||||
v.dataFileAccessLock.Unlock()
|
||||
syncErr := backend.Sync()
|
||||
v.dataFileAccessLock.Lock()
|
||||
if syncErr != nil {
|
||||
v.checkReadWriteError(syncErr)
|
||||
v.lastAppendAtNs = batchLastAppendAtNs
|
||||
v.lastWriteAppendAtNs = batchLastWriteAppendAtNs
|
||||
@@ -591,17 +551,45 @@ func (v *Volume) processBatch(currentRequests []*needle.AsyncRequest) {
|
||||
v.lastWriteDeleted = batchLastWriteDeleted
|
||||
v.lastModifiedTsSeconds = batchLastModifiedTsSeconds
|
||||
batchErr := syncErr
|
||||
if recoveryErr := v.rollbackBatch(end, indexEnd, orderedSnapshots, metricRollbacker, batchMetrics); recoveryErr != nil {
|
||||
batchErr = errors.Join(syncErr, recoveryErr)
|
||||
// Nothing was published: truncating the run's bytes is the whole
|
||||
// rollback, and no reader ever resolved them.
|
||||
if te := v.DataBackend.Truncate(end); te != nil {
|
||||
batchErr = errors.Join(syncErr,
|
||||
fmt.Errorf("truncate %s to %d: %w", v.DataBackend.Name(), end, te))
|
||||
v.markIoUnavailable(batchErr)
|
||||
}
|
||||
for i := 0; i < len(currentRequests); i++ {
|
||||
currentRequests[i].UpdateResult(0, 0, false, batchErr)
|
||||
for i := 0; i < len(run); i++ {
|
||||
run[i].UpdateResult(0, 0, false, batchErr)
|
||||
}
|
||||
v.dataFileAccessLock.Unlock()
|
||||
for i := 0; i < len(run); i++ {
|
||||
run[i].Submit()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
for i := 0; i < len(currentRequests); i++ {
|
||||
currentRequests[i].Submit()
|
||||
refused := false
|
||||
for i := 0; i < len(run); i++ {
|
||||
if refused {
|
||||
run[i].UpdateResult(0, 0, false, fmt.Errorf("volume %d is read only", v.Id))
|
||||
continue
|
||||
}
|
||||
if run[i].IsWriteRequest {
|
||||
if stagedWriteOk[i] {
|
||||
if perr := v.publishWriteRequest(run[i].N, stagedWriteOffsets[i], true); perr != nil {
|
||||
run[i].UpdateResult(0, 0, false, perr)
|
||||
refused = true
|
||||
}
|
||||
}
|
||||
} else if stagedDeleteOk[i] {
|
||||
if perr := v.publishDeleteRequest(run[i].N, stagedDeleteOffsets[i]); perr != nil {
|
||||
run[i].UpdateResult(0, 0, false, perr)
|
||||
}
|
||||
}
|
||||
}
|
||||
v.dataFileAccessLock.Unlock()
|
||||
for i := 0; i < len(run); i++ {
|
||||
run[i].Submit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -673,6 +661,8 @@ func (v *Volume) stopWorker() {
|
||||
|
||||
func (v *Volume) WriteNeedleBlob(needleId NeedleId, needleBlob []byte, size Size) error {
|
||||
|
||||
v.dataFileSyncLock.Lock()
|
||||
defer v.dataFileSyncLock.Unlock()
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
|
||||
|
||||
@@ -446,23 +446,26 @@ func TestBatchFsyncRollbackRestoresOriginalValueAfterRepeatedNeedleId(t *testing
|
||||
}
|
||||
v.processBatch(requests)
|
||||
|
||||
for _, request := range requests {
|
||||
_, _, _, err = request.WaitComplete()
|
||||
require.Error(t, err)
|
||||
}
|
||||
// A repeated needle id starts a new batch run, so the second write syncs
|
||||
// on its own: the first run rolls back to "original-value" and the second
|
||||
// write lands as a normal sequential overwrite.
|
||||
_, _, _, err = requests[0].WaitComplete()
|
||||
require.Error(t, err)
|
||||
_, _, _, err = requests[1].WaitComplete()
|
||||
require.NoError(t, err)
|
||||
|
||||
readBack := new(needle.Needle)
|
||||
readBack.Id = kept.Id
|
||||
_, err = v.readNeedle(readBack, nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("original-value"), readBack.Data)
|
||||
require.Equal(t, []byte("second-failed-value"), readBack.Data)
|
||||
|
||||
reloaded := reopenCountingVolume(t, v)
|
||||
readBack = new(needle.Needle)
|
||||
readBack.Id = kept.Id
|
||||
_, err = reloaded.readNeedle(readBack, nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("original-value"), readBack.Data)
|
||||
require.Equal(t, []byte("second-failed-value"), readBack.Data)
|
||||
}
|
||||
|
||||
// Rolling back a first-time write must not leave a tombstoned map entry: the
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package topology
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
func isWritable(t *testing.T, topo *Topology, v storage.VolumeInfo) bool {
|
||||
t.Helper()
|
||||
vl := topo.FindVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, types.ToDiskType(v.DiskType))
|
||||
for _, id := range vl.CloneWritableVolumes() {
|
||||
if id == v.Id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestDuplicateVolumeIdAcrossCollections(t *testing.T) {
|
||||
topo := NewTopology("topo", nil, 128, 3, false)
|
||||
rp, _ := super_block.NewReplicaPlacementFromString("000")
|
||||
|
||||
dn1 := NewDataNode("server1")
|
||||
dn2 := NewDataNode("server2")
|
||||
|
||||
v1 := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL}
|
||||
v2 := storage.VolumeInfo{Id: 7, Collection: "b", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL}
|
||||
|
||||
dn1.UpdateVolumes([]storage.VolumeInfo{v1})
|
||||
dn2.UpdateVolumes([]storage.VolumeInfo{v2})
|
||||
topo.RegisterVolumeLayout(v1, dn1)
|
||||
topo.RegisterVolumeLayout(v2, dn2)
|
||||
topo.flagDuplicateVolumeId(v2, dn2)
|
||||
|
||||
if isWritable(t, topo, v2) {
|
||||
t.Fatal("duplicate newcomer should be quarantined out of the writable list")
|
||||
}
|
||||
if isWritable(t, topo, v1) {
|
||||
t.Fatal("either copy could be the impostor; the earlier copy must be quarantined too")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameLayoutReplicaIsNotDuplicate(t *testing.T) {
|
||||
topo := NewTopology("topo", nil, 128, 3, false)
|
||||
rp, _ := super_block.NewReplicaPlacementFromString("001")
|
||||
|
||||
dn1 := NewDataNode("server1")
|
||||
dn1.Ip = "10.0.0.1"
|
||||
dn1.Port = 8080
|
||||
dn2 := NewDataNode("server2")
|
||||
dn2.Ip = "10.0.0.2"
|
||||
dn2.Port = 8080
|
||||
|
||||
v := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL}
|
||||
dn1.UpdateVolumes([]storage.VolumeInfo{v})
|
||||
dn2.UpdateVolumes([]storage.VolumeInfo{v})
|
||||
topo.RegisterVolumeLayout(v, dn1)
|
||||
topo.RegisterVolumeLayout(v, dn2)
|
||||
topo.flagDuplicateVolumeId(v, dn2)
|
||||
|
||||
if !isWritable(t, topo, v) {
|
||||
t.Fatal("a same-layout replica is a legitimate copy, not a duplicate")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameNodeVolumeMoveIsNotDuplicate(t *testing.T) {
|
||||
topo := NewTopology("topo", nil, 128, 3, false)
|
||||
rp, _ := super_block.NewReplicaPlacementFromString("000")
|
||||
dn := NewDataNode("server1")
|
||||
|
||||
old := storage.VolumeInfo{Id: 7, Collection: "c", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL}
|
||||
moved := storage.VolumeInfo{Id: 7, Collection: "c", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, DiskType: "ssd"}
|
||||
dn.UpdateVolumes([]storage.VolumeInfo{old})
|
||||
topo.RegisterVolumeLayout(old, dn)
|
||||
|
||||
// the move registers the new layout before the old entry is removed
|
||||
dn.UpdateVolumes([]storage.VolumeInfo{moved})
|
||||
topo.RegisterVolumeLayout(moved, dn)
|
||||
topo.flagDuplicateVolumeId(moved, dn)
|
||||
|
||||
if !isWritable(t, topo, moved) {
|
||||
t.Fatal("a same-node disk move is not a duplicate")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuarantineReleasedWhenConflictResolves(t *testing.T) {
|
||||
topo := NewTopology("topo", nil, 128, 3, false)
|
||||
rp, _ := super_block.NewReplicaPlacementFromString("000")
|
||||
|
||||
dn1 := NewDataNode("server1")
|
||||
dn2 := NewDataNode("server2")
|
||||
v1 := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL}
|
||||
v2 := storage.VolumeInfo{Id: 7, Collection: "b", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL}
|
||||
dn1.UpdateVolumes([]storage.VolumeInfo{v1})
|
||||
dn2.UpdateVolumes([]storage.VolumeInfo{v2})
|
||||
topo.RegisterVolumeLayout(v1, dn1)
|
||||
topo.RegisterVolumeLayout(v2, dn2)
|
||||
topo.flagDuplicateVolumeId(v2, dn2)
|
||||
|
||||
topo.UnRegisterVolumeLayout(v2, dn2)
|
||||
|
||||
if !isWritable(t, topo, v1) {
|
||||
t.Fatal("the surviving copy must be released once the conflict is gone")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuarantineSurvivesResync(t *testing.T) {
|
||||
topo := NewTopology("topo", nil, 128, 3, false)
|
||||
rp, _ := super_block.NewReplicaPlacementFromString("000")
|
||||
|
||||
dn1 := NewDataNode("server1")
|
||||
dn2 := NewDataNode("server2")
|
||||
v1 := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL}
|
||||
v2 := storage.VolumeInfo{Id: 7, Collection: "b", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL}
|
||||
dn1.UpdateVolumes([]storage.VolumeInfo{v1})
|
||||
dn2.UpdateVolumes([]storage.VolumeInfo{v2})
|
||||
topo.RegisterVolumeLayout(v1, dn1)
|
||||
topo.RegisterVolumeLayout(v2, dn2)
|
||||
topo.flagDuplicateVolumeId(v2, dn2)
|
||||
|
||||
// a resync from the same server re-reports the volume as writable;
|
||||
// the quarantine must keep it out of the writable list
|
||||
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{{
|
||||
Id: 7, Collection: "b", ReplicaPlacement: 0, Version: 3,
|
||||
}}, dn2)
|
||||
|
||||
if isWritable(t, topo, v2) {
|
||||
t.Fatal("resync must not clear the quarantine")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplicationChangeIsNotDuplicate(t *testing.T) {
|
||||
topo := NewTopology("topo", nil, 128, 3, false)
|
||||
rpOld, _ := super_block.NewReplicaPlacementFromString("000")
|
||||
rpNew, _ := super_block.NewReplicaPlacementFromString("001")
|
||||
|
||||
dn1 := NewDataNode("server1")
|
||||
dn1.Ip = "10.0.0.1"
|
||||
dn1.Port = 8080
|
||||
dn2 := NewDataNode("server2")
|
||||
dn2.Ip = "10.0.0.2"
|
||||
dn2.Port = 8080
|
||||
|
||||
vOld := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rpOld, Ttl: needle.EMPTY_TTL}
|
||||
vNew := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rpNew, Ttl: needle.EMPTY_TTL}
|
||||
|
||||
dn1.UpdateVolumes([]storage.VolumeInfo{vOld})
|
||||
dn2.UpdateVolumes([]storage.VolumeInfo{vNew})
|
||||
topo.RegisterVolumeLayout(vOld, dn1)
|
||||
topo.RegisterVolumeLayout(vNew, dn2)
|
||||
topo.flagDuplicateVolumeId(vNew, dn2)
|
||||
|
||||
if topo.isQuarantined(dn2, vNew.Id) || topo.isQuarantined(dn1, vOld.Id) {
|
||||
t.Fatal("an rp-only layout difference is a replication change in flight, not a duplicate")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDuplicateVolumeIdAcrossTtls(t *testing.T) {
|
||||
topo := NewTopology("topo", nil, 128, 3, false)
|
||||
rp, _ := super_block.NewReplicaPlacementFromString("000")
|
||||
ttl, _ := needle.ReadTTL("3d")
|
||||
|
||||
dn1 := NewDataNode("server1")
|
||||
dn1.Ip = "10.0.0.1"
|
||||
dn1.Port = 8080
|
||||
dn2 := NewDataNode("server2")
|
||||
dn2.Ip = "10.0.0.2"
|
||||
dn2.Port = 8080
|
||||
|
||||
v1 := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL}
|
||||
v2 := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: ttl}
|
||||
|
||||
dn1.UpdateVolumes([]storage.VolumeInfo{v1})
|
||||
dn2.UpdateVolumes([]storage.VolumeInfo{v2})
|
||||
topo.RegisterVolumeLayout(v1, dn1)
|
||||
topo.RegisterVolumeLayout(v2, dn2)
|
||||
topo.flagDuplicateVolumeId(v2, dn2)
|
||||
|
||||
if !topo.isQuarantined(dn2, v2.Id) || !topo.isQuarantined(dn1, v1.Id) {
|
||||
t.Fatal("same collection with a different ttl is still a reused volume id")
|
||||
}
|
||||
}
|
||||
+224
-4
@@ -9,6 +9,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -99,6 +100,55 @@ type Topology struct {
|
||||
|
||||
reportedTopologyIdsLock sync.Mutex
|
||||
pendingReportedTopologyIds map[string]struct{}
|
||||
|
||||
// quarantinedVolumeIds are (node, vid) pairs force-read-only because the
|
||||
// vid collided across layouts. Kept separate from the reported flag so
|
||||
// later heartbeats from the same server cannot quietly undo it.
|
||||
quarantinedVolumeIds sync.Map
|
||||
|
||||
// QuarantineVolumeFn pushes the quarantine onto the volume server itself
|
||||
// (VolumeMarkReadonly/VolumeMarkWritable). nil keeps quarantine at the
|
||||
// layout level only.
|
||||
QuarantineVolumeFn func(dn *DataNode, vid needle.VolumeId, readOnly bool) error
|
||||
}
|
||||
|
||||
type quarantinedVolume struct {
|
||||
dnId NodeId
|
||||
vid needle.VolumeId
|
||||
}
|
||||
|
||||
type quarantinedVolumeState struct {
|
||||
reported bool
|
||||
enforced bool
|
||||
}
|
||||
|
||||
func (t *Topology) isQuarantined(dn *DataNode, vid needle.VolumeId) bool {
|
||||
_, ok := t.quarantinedVolumeIds.Load(quarantinedVolume{dn.Id(), vid})
|
||||
return ok
|
||||
}
|
||||
|
||||
// enforceQuarantine keeps the latest reported read-only flag for a quarantined
|
||||
// copy so a later release restores the server's true state. The stored report
|
||||
// keeps the server's flag: quarantine lives at the layout level, and folding
|
||||
// it into the record here would make the master's volume digest permanently
|
||||
// disagree with the server's and force a full volume list on every heartbeat.
|
||||
func (t *Topology) enforceQuarantine(dn *DataNode, vi storage.VolumeInfo) storage.VolumeInfo {
|
||||
q := quarantinedVolume{dn.Id(), vi.Id}
|
||||
if v, ok := t.quarantinedVolumeIds.Load(q); ok {
|
||||
state := v.(quarantinedVolumeState)
|
||||
if !state.enforced {
|
||||
state.reported = vi.ReadOnly
|
||||
}
|
||||
if t.QuarantineVolumeFn != nil && (!state.enforced || !vi.ReadOnly) {
|
||||
// The mark never landed, or the server lost it (restart, manual
|
||||
// unquarantine); push it while the conflict stands.
|
||||
if t.QuarantineVolumeFn(dn, vi.Id, true) == nil {
|
||||
state.enforced = true
|
||||
}
|
||||
}
|
||||
t.quarantinedVolumeIds.Store(q, state)
|
||||
}
|
||||
return vi
|
||||
}
|
||||
|
||||
func NewTopology(id string, seq sequence.Sequencer, volumeSizeLimit uint64, pulse int, replicationAsMin bool) *Topology {
|
||||
@@ -591,9 +641,15 @@ func (t *Topology) DeleteCollection(collectionName string) {
|
||||
if !found {
|
||||
return
|
||||
}
|
||||
var vids []needle.VolumeId
|
||||
for _, vl := range collection.(*Collection).GetAllVolumeLayouts() {
|
||||
vids = append(vids, vl.ListVids()...)
|
||||
vl.releaseLookupOwnership()
|
||||
}
|
||||
// a vid colliding with a copy in this collection is no longer a duplicate
|
||||
for _, vid := range vids {
|
||||
t.releaseResolvedQuarantine(vid)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Topology) DeleteLayout(collectionName string, rp *super_block.ReplicaPlacement, ttl *needle.TTL, diskType types.DiskType) {
|
||||
@@ -612,15 +668,172 @@ func (t *Topology) RegisterVolumeLayout(v storage.VolumeInfo, dn *DataNode) {
|
||||
for {
|
||||
vl := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, diskType)
|
||||
if vl.RegisterVolume(&v, dn) {
|
||||
if t.isQuarantined(dn, v.Id) {
|
||||
vl.SetVolumeQuarantined(dn, v.Id)
|
||||
}
|
||||
vl.EnsureCorrectWritables(&v)
|
||||
go t.flagDuplicateVolumeId(v, dn)
|
||||
return
|
||||
}
|
||||
// Dropped with its collection; the next lookup creates a fresh one.
|
||||
}
|
||||
}
|
||||
|
||||
// flagDuplicateVolumeId reports and quarantines v.Id when another data node
|
||||
// already serves it under a different layout key. It runs after registration
|
||||
// so a legitimate same-node move (disk type or collection change) settles
|
||||
// first and does not trip it. Every copy across the conflicting layouts is
|
||||
// quarantined: either could be the impostor, and arrival order must not
|
||||
// decide which copy stays writable.
|
||||
func (t *Topology) flagDuplicateVolumeId(v storage.VolumeInfo, dn *DataNode) {
|
||||
hits := t.findDuplicateVolumeLayouts(v, dn)
|
||||
if len(hits) == 0 {
|
||||
return
|
||||
}
|
||||
// A conflict could resolve between the scan above and the marks below;
|
||||
// re-run the release so a stale quarantine is cleared instead of kept.
|
||||
defer t.releaseResolvedQuarantine(v.Id)
|
||||
stats.MasterDuplicateVolumeIds.WithLabelValues(v.Collection, v.Id.String()).Inc()
|
||||
var otherKeys []string
|
||||
for _, h := range hits {
|
||||
otherKeys = append(otherKeys, h.layoutKey())
|
||||
}
|
||||
glog.Errorf("duplicate volume id %d: %s reports it under %s but other data nodes also serve it under %s; marking all copies read-only", v.Id, dn.Id(), volumeLayoutKey(v.Collection, v.ReplicaPlacement, v.Ttl, types.ToDiskType(v.DiskType)), strings.Join(otherKeys, ", "))
|
||||
quarantine := func(n *DataNode, vl *VolumeLayout) {
|
||||
q := quarantinedVolume{n.Id(), v.Id}
|
||||
reported := false
|
||||
if vi, err := n.GetVolumesById(v.Id); err == nil {
|
||||
reported = vi.ReadOnly
|
||||
}
|
||||
t.quarantinedVolumeIds.LoadOrStore(q, quarantinedVolumeState{reported: reported})
|
||||
if vl != nil {
|
||||
vl.SetVolumeQuarantined(n, v.Id)
|
||||
}
|
||||
if t.QuarantineVolumeFn != nil && t.QuarantineVolumeFn(n, v.Id, true) == nil {
|
||||
if val, ok := t.quarantinedVolumeIds.Load(q); ok {
|
||||
state := val.(quarantinedVolumeState)
|
||||
state.enforced = true
|
||||
t.quarantinedVolumeIds.Store(q, state)
|
||||
}
|
||||
}
|
||||
}
|
||||
quarantine(dn, t.FindVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, types.ToDiskType(v.DiskType)))
|
||||
for _, h := range hits {
|
||||
for _, n := range h.nodes {
|
||||
quarantine(n, h.vl)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// releaseResolvedQuarantine lifts read-only marks once the conflicting copy
|
||||
// is gone, so a finished move does not leave the surviving copy quarantined.
|
||||
func (t *Topology) releaseResolvedQuarantine(vid needle.VolumeId) {
|
||||
t.quarantinedVolumeIds.Range(func(key, val any) bool {
|
||||
q := key.(quarantinedVolume)
|
||||
if q.vid != vid {
|
||||
return true
|
||||
}
|
||||
dn, vl, vi := t.findQuarantinedVolume(q.dnId, vid)
|
||||
if dn == nil {
|
||||
t.quarantinedVolumeIds.Delete(key)
|
||||
return true
|
||||
}
|
||||
if hits := t.findDuplicateVolumeLayouts(vi, dn); len(hits) > 0 {
|
||||
return true
|
||||
}
|
||||
state, _ := val.(quarantinedVolumeState)
|
||||
if state.reported {
|
||||
dn.SetVolumeReadOnly(vid, true)
|
||||
vl.SetReplicaReadOnlyFlag(dn, vid, true)
|
||||
} else {
|
||||
vl.SetVolumeWritable(dn, vid)
|
||||
if state.enforced && t.QuarantineVolumeFn != nil {
|
||||
if err := t.QuarantineVolumeFn(dn, vid, false); err != nil {
|
||||
// The server still rejects writes; keep the mark so a
|
||||
// later release pass retries the writable push.
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
t.quarantinedVolumeIds.Delete(key)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func (t *Topology) findQuarantinedVolume(dnId NodeId, vid needle.VolumeId) (*DataNode, *VolumeLayout, storage.VolumeInfo) {
|
||||
for _, item := range t.collectionMap.Items() {
|
||||
for _, vl := range item.(*Collection).GetAllVolumeLayouts() {
|
||||
for _, n := range vl.Lookup(vid) {
|
||||
if n.Id() == dnId {
|
||||
vi, _ := n.GetVolumesById(vid)
|
||||
return n, vl, vi
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, nil, storage.VolumeInfo{}
|
||||
}
|
||||
|
||||
// duplicateHit is one layout that holds v.Id on data nodes other than the
|
||||
// reporter's.
|
||||
type duplicateHit struct {
|
||||
collection string
|
||||
vl *VolumeLayout
|
||||
nodes []*DataNode
|
||||
}
|
||||
|
||||
func (h duplicateHit) layoutKey() string {
|
||||
return volumeLayoutKey(h.collection, h.vl.rp, h.vl.ttl, h.vl.diskType)
|
||||
}
|
||||
|
||||
func volumeLayoutKey(collection string, rp *super_block.ReplicaPlacement, ttl *needle.TTL, diskType types.DiskType) string {
|
||||
return fmt.Sprintf("collection=%q rp=%s ttl=%s disk=%s", collection, rp, ttl, diskType)
|
||||
}
|
||||
|
||||
func ttlEqual(a, b *needle.TTL) bool {
|
||||
if a == nil || b == nil {
|
||||
return a == b
|
||||
}
|
||||
return a.ToUint32() == b.ToUint32()
|
||||
}
|
||||
|
||||
|
||||
// findDuplicateVolumeLayouts reports every layout that already holds v.Id on
|
||||
// data nodes other than dn. Volume ids are global, so the same id held by two
|
||||
// nodes under two layouts means the allocator reused an id.
|
||||
func (t *Topology) findDuplicateVolumeLayouts(v storage.VolumeInfo, dn *DataNode) []duplicateHit {
|
||||
if v.ReplicaPlacement == nil {
|
||||
return nil
|
||||
}
|
||||
diskType := types.ToDiskType(v.DiskType)
|
||||
var hits []duplicateHit
|
||||
for _, item := range t.collectionMap.Items() {
|
||||
c := item.(*Collection)
|
||||
for _, vl := range c.GetAllVolumeLayouts() {
|
||||
if c.Name == v.Collection && vl.diskType == diskType && ttlEqual(vl.ttl, v.Ttl) {
|
||||
// The reporter's own layout, or an rp-only difference:
|
||||
// a replication change rolls through the nodes one at a
|
||||
// time, so the same volume legitimately reports the old
|
||||
// and new rp while it settles.
|
||||
continue
|
||||
}
|
||||
var others []*DataNode
|
||||
for _, n := range vl.Lookup(v.Id) {
|
||||
if n != dn {
|
||||
others = append(others, n)
|
||||
}
|
||||
}
|
||||
if len(others) > 0 {
|
||||
hits = append(hits, duplicateHit{collection: c.Name, vl: vl, nodes: others})
|
||||
}
|
||||
}
|
||||
}
|
||||
return hits
|
||||
}
|
||||
|
||||
func (t *Topology) UnRegisterVolumeLayout(v storage.VolumeInfo, dn *DataNode) {
|
||||
glog.Infof("removing volume info: %+v from %v", v, dn.id)
|
||||
defer t.releaseResolvedQuarantine(v.Id)
|
||||
diskType := types.ToDiskType(v.DiskType)
|
||||
volumeLayout := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, diskType)
|
||||
volumeLayout.UnRegisterVolume(&v, dn)
|
||||
@@ -745,6 +958,9 @@ func (t *Topology) SyncDataNodeRegistration(volumes []*master_pb.VolumeInformati
|
||||
glog.V(0).Infof("Fail to convert joined volume information: %v", err)
|
||||
}
|
||||
}
|
||||
for i := range volumeInfos {
|
||||
volumeInfos[i] = t.enforceQuarantine(dn, volumeInfos[i])
|
||||
}
|
||||
// find out the delta volumes
|
||||
newVolumes, deletedVolumes, changedVolumes = dn.UpdateVolumes(volumeInfos)
|
||||
for _, v := range newVolumes {
|
||||
@@ -757,7 +973,7 @@ func (t *Topology) SyncDataNodeRegistration(volumes []*master_pb.VolumeInformati
|
||||
if v.ReplicaPlacement == nil {
|
||||
continue
|
||||
}
|
||||
t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, types.ToDiskType(v.DiskType)).SetReplicaReadOnlyFlag(dn, v.Id, v.ReadOnly)
|
||||
t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, types.ToDiskType(v.DiskType)).SetReplicaReadOnlyFlag(dn, v.Id, v.ReadOnly || t.isQuarantined(dn, v.Id))
|
||||
}
|
||||
// Update effective sizes for all reported volumes (decay pending estimates).
|
||||
// If decay brings a volume eagerly removed by RecordAssign back under the
|
||||
@@ -781,6 +997,7 @@ func (t *Topology) SyncDataNodeRegistration(volumes []*master_pb.VolumeInformati
|
||||
// one, which the calls below must use too.
|
||||
vl = t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, diskType)
|
||||
}
|
||||
go t.flagDuplicateVolumeId(v, dn)
|
||||
// Volumes new to the disk map were registered above, so reaching
|
||||
// here means only the lookup index had lost it. Clients were told
|
||||
// it went when the node dropped out, so the repair has to tell them
|
||||
@@ -804,7 +1021,7 @@ func (t *Topology) IncrementalSyncDataNodeRegistration(newVolumes, deletedVolume
|
||||
glog.V(0).Infof("NewVolumeInfoFromShort %v: %v", v, err)
|
||||
continue
|
||||
}
|
||||
newVis = append(newVis, vi)
|
||||
newVis = append(newVis, t.enforceQuarantine(dn, vi))
|
||||
}
|
||||
for _, v := range deletedVolumes {
|
||||
vi, err := storage.NewVolumeInfoFromShort(v)
|
||||
@@ -865,7 +1082,7 @@ func (t *Topology) ApplyVolumeChanges(changed []*master_pb.VolumeInformationMess
|
||||
glog.V(0).Infof("Fail to convert changed volume information: %v", err)
|
||||
continue
|
||||
}
|
||||
volumeInfos = append(volumeInfos, vi)
|
||||
volumeInfos = append(volumeInfos, t.enforceQuarantine(dn, vi))
|
||||
}
|
||||
|
||||
for _, vi := range volumeInfos {
|
||||
@@ -885,11 +1102,14 @@ func (t *Topology) ApplyVolumeChanges(changed []*master_pb.VolumeInformationMess
|
||||
// Dropped with its collection; the next lookup creates a fresh one.
|
||||
vl = t.GetVolumeLayout(vi.Collection, vi.ReplicaPlacement, vi.Ttl, types.ToDiskType(vi.DiskType))
|
||||
}
|
||||
if becameServable {
|
||||
go t.flagDuplicateVolumeId(vi, dn)
|
||||
}
|
||||
if isNew || becameServable || tierTransition || isChanged {
|
||||
newVolumes = append(newVolumes, vi)
|
||||
}
|
||||
if isChanged {
|
||||
vl.SetReplicaReadOnlyFlag(dn, vi.Id, vi.ReadOnly)
|
||||
vl.SetReplicaReadOnlyFlag(dn, vi.Id, vi.ReadOnly || t.isQuarantined(dn, vi.Id))
|
||||
}
|
||||
vl.UpdateOversizedState(&vi, dn)
|
||||
if vl.UpdateVolumeSize(vi.Id, vi.Size, vi.CompactRevision, true) {
|
||||
|
||||
@@ -118,6 +118,8 @@ func (t *Topology) UnRegisterDataNode(dn *DataNode) {
|
||||
diskType := types.ToDiskType(v.DiskType)
|
||||
vl := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, diskType)
|
||||
vl.SetVolumeUnavailable(dn, v.Id)
|
||||
// this node may have been the conflicting copy pinning a quarantine
|
||||
defer t.releaseResolvedQuarantine(v.Id)
|
||||
}
|
||||
|
||||
// unregister ec shards when volume server disconnected
|
||||
|
||||
@@ -411,6 +411,9 @@ func (vl *VolumeLayout) ensureCorrectWritables(vid needle.VolumeId) {
|
||||
// or one on a server in maintenance mode, holds the whole volume out.
|
||||
func (vl *VolumeLayout) isAllWritable(vid needle.VolumeId) bool {
|
||||
if location, ok := vl.vid2location[vid]; ok {
|
||||
if location.AnyReadOnly() {
|
||||
return false
|
||||
}
|
||||
for _, dn := range location.list {
|
||||
if dn.InMaintenanceMode() {
|
||||
return false
|
||||
@@ -586,12 +589,21 @@ func (vl *VolumeLayout) isEmpty() bool {
|
||||
return len(vl.vid2location) == 0
|
||||
}
|
||||
|
||||
func (vl *VolumeLayout) ListVids() (vids []needle.VolumeId) {
|
||||
vl.accessLock.RLock()
|
||||
defer vl.accessLock.RUnlock()
|
||||
for vid := range vl.vid2location {
|
||||
vids = append(vids, vid)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (vl *VolumeLayout) Lookup(vid needle.VolumeId) []*DataNode {
|
||||
vl.accessLock.RLock()
|
||||
defer vl.accessLock.RUnlock()
|
||||
|
||||
if location := vl.vid2location[vid]; location != nil {
|
||||
return location.list
|
||||
return append([]*DataNode(nil), location.list...)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1021,6 +1033,19 @@ func (vl *VolumeLayout) SetVolumeWritable(dn *DataNode, vid needle.VolumeId) boo
|
||||
return false
|
||||
}
|
||||
|
||||
// SetVolumeQuarantined marks dn's replica read-only at the layout level only.
|
||||
// The node's stored report is left untouched so the volume digest still tracks
|
||||
// what the server reports and quarantined copies do not force endless full
|
||||
// heartbeats.
|
||||
func (vl *VolumeLayout) SetVolumeQuarantined(dn *DataNode, vid needle.VolumeId) {
|
||||
vl.accessLock.Lock()
|
||||
defer vl.accessLock.Unlock()
|
||||
if location, ok := vl.vid2location[vid]; ok {
|
||||
location.SetReadOnly(dn, true)
|
||||
}
|
||||
vl.removeFromWritable(vid)
|
||||
}
|
||||
|
||||
// SetReplicaReadOnlyFlag records what dn's latest heartbeat said about its
|
||||
// replica of vid, and nothing more: the writable list is left to
|
||||
// EnsureCorrectWritables and its capacity guards. Until now the flag only moved
|
||||
|
||||
@@ -962,7 +962,7 @@ func readEqualityDeleteFile(
|
||||
reader := parquet.NewReader(bytes.NewReader(data))
|
||||
defer reader.Close()
|
||||
|
||||
colIndices, err := resolveEqualityColIndices(reader.Schema(), fieldIDs, icebergSchema)
|
||||
colIndices, err := resolveEqualityColIndices(reader.Schema(), fieldIDs, icebergSchema, false)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve columns in %s: %w", filePath, err)
|
||||
}
|
||||
@@ -993,24 +993,37 @@ func readEqualityDeleteFile(
|
||||
// buildEqualityKey builds a composite string key from specific column values
|
||||
// in a row. Each value is serialized as "kind:length:value" to avoid ambiguity
|
||||
// between types (e.g., int 123 vs string "123") and to prevent collisions from
|
||||
// values containing separator characters.
|
||||
// values containing separator characters. A negative column index is a field
|
||||
// the file lacks: the value there is null.
|
||||
func buildEqualityKey(row parquet.Row, colIndices []int) string {
|
||||
if len(colIndices) == 1 {
|
||||
v := row[colIndices[0]]
|
||||
v := equalityKeyValue(row, colIndices[0])
|
||||
s := v.String()
|
||||
return fmt.Sprintf("%d:%d:%s", v.Kind(), len(s), s)
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, idx := range colIndices {
|
||||
v := row[idx]
|
||||
v := equalityKeyValue(row, idx)
|
||||
s := v.String()
|
||||
fmt.Fprintf(&b, "%d:%d:%s", v.Kind(), len(s), s)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func equalityKeyValue(row parquet.Row, idx int) parquet.Value {
|
||||
if idx < 0 {
|
||||
return parquet.NullValue()
|
||||
}
|
||||
return row[idx]
|
||||
}
|
||||
|
||||
// resolveEqualityColIndices maps Iceberg field IDs to Parquet column indices.
|
||||
func resolveEqualityColIndices(pqSchema *parquet.Schema, fieldIDs []int, icebergSchema *iceberg.Schema) ([]int, error) {
|
||||
// A file carrying field ids resolves by id, so a column renamed since the
|
||||
// file was written still matches; one without ids falls back to the Iceberg
|
||||
// name. allowMissing reads a column the file lacks as null (-1 marks it in
|
||||
// the key): for data files only — an equality-delete file always carries
|
||||
// its equality columns, so a missing one stays an error there.
|
||||
func resolveEqualityColIndices(pqSchema *parquet.Schema, fieldIDs []int, icebergSchema *iceberg.Schema, allowMissing bool) ([]int, error) {
|
||||
if len(fieldIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -1019,6 +1032,14 @@ func resolveEqualityColIndices(pqSchema *parquet.Schema, fieldIDs []int, iceberg
|
||||
for i, col := range pqSchema.Columns() {
|
||||
colNameToIdx[strings.Join(col, ".")] = i
|
||||
}
|
||||
idToIdx := make(map[int]int)
|
||||
for _, f := range pqSchema.Fields() {
|
||||
if f.Leaf() && f.ID() > 0 {
|
||||
if idx, ok := colNameToIdx[f.Name()]; ok {
|
||||
idToIdx[f.ID()] = idx
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
indices := make([]int, len(fieldIDs))
|
||||
for i, fid := range fieldIDs {
|
||||
@@ -1026,8 +1047,17 @@ func resolveEqualityColIndices(pqSchema *parquet.Schema, fieldIDs []int, iceberg
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("field ID %d not found in iceberg schema", fid)
|
||||
}
|
||||
idx, ok := colNameToIdx[field.Name]
|
||||
idx, ok := idToIdx[fid]
|
||||
if !ok && len(idToIdx) == 0 {
|
||||
idx, ok = colNameToIdx[field.Name]
|
||||
}
|
||||
if !ok {
|
||||
// An optional column added to the table after this file was
|
||||
// written reads as null there (-1 marks it in the key).
|
||||
if allowMissing && !field.Required {
|
||||
indices[i] = -1
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("column %q (field ID %d) not found in parquet schema", field.Name, fid)
|
||||
}
|
||||
indices[i] = idx
|
||||
@@ -1089,6 +1119,86 @@ func mergeParquetFiles(
|
||||
icebergSchema *iceberg.Schema,
|
||||
rowGroupRows int64,
|
||||
lineage bool,
|
||||
) ([]byte, int64, error) {
|
||||
// On a v1/v2 table the writer's schema is chosen before any row is
|
||||
// written: the union of the bin's file schemas by field id, so a bin of
|
||||
// progressively wider files merges in one pass instead of restarting
|
||||
// (and rewriting every earlier file) on each wider one. The v3 merge
|
||||
// keeps the first file's columns plus the lineage columns.
|
||||
var target *parquet.Schema
|
||||
if !lineage {
|
||||
var err error
|
||||
if target, err = binWriterSchema(ctx, filerClient, bucketName, dataPath, entries); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
}
|
||||
for attempt := 0; ; attempt++ {
|
||||
out, rows, err := mergeParquetFilesInto(ctx, filerClient, bucketName, dataPath, entries, positionDeletes,
|
||||
eqDeleteGroups, icebergSchema, rowGroupRows, lineage, target)
|
||||
var wider *widerSchemaError
|
||||
if errors.As(err, &wider) && attempt < len(entries) {
|
||||
target = wider.schema
|
||||
continue
|
||||
}
|
||||
return out, rows, err
|
||||
}
|
||||
}
|
||||
|
||||
// binWriterSchema is the writer schema for a v1/v2 bin-pack merge: the union
|
||||
// of the files' schemas by field id. Only each file's footer is read to learn
|
||||
// its schema; the merge then downloads each file once. Files whose schemas
|
||||
// cannot union (no field ids, nested or repeated columns, a field id or name
|
||||
// carrying different types) merge only under the old rule — every file's
|
||||
// schema equal to the first — and the bin is refused as before otherwise.
|
||||
func binWriterSchema(
|
||||
ctx context.Context,
|
||||
filerClient filer_pb.SeaweedFilerClient,
|
||||
bucketName, dataPath string,
|
||||
entries []iceberg.ManifestEntry,
|
||||
) (*parquet.Schema, error) {
|
||||
var union schemaUnion
|
||||
var first *parquet.Schema
|
||||
unionable, allEqual := true, true
|
||||
for _, entry := range entries {
|
||||
source := entry.DataFile().FilePath()
|
||||
schema, err := parquetSchemaByIcebergPath(ctx, filerClient, bucketName, dataPath, source)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("schema of %s: %w", source, err)
|
||||
}
|
||||
if schema == nil {
|
||||
return nil, fmt.Errorf("no parquet schema found in %s", source)
|
||||
}
|
||||
if first == nil {
|
||||
first = schema
|
||||
} else if !schemasEqual(first, schema) {
|
||||
allEqual = false
|
||||
}
|
||||
if unionable {
|
||||
unionable = union.fold(schema, source) == nil
|
||||
}
|
||||
if !unionable && !allEqual {
|
||||
return nil, fmt.Errorf("schema mismatch in %s: cannot merge files with different schemas", source)
|
||||
}
|
||||
}
|
||||
if !unionable || first == nil {
|
||||
return nil, nil // every file spells the first file's schema
|
||||
}
|
||||
return union.schema(first.Name(), first), nil
|
||||
}
|
||||
|
||||
// mergeParquetFilesInto merges with target as the writer's schema on a v1/v2
|
||||
// table (nil: the first file's).
|
||||
func mergeParquetFilesInto(
|
||||
ctx context.Context,
|
||||
filerClient filer_pb.SeaweedFilerClient,
|
||||
bucketName, dataPath string,
|
||||
entries []iceberg.ManifestEntry,
|
||||
positionDeletes map[string][]int64,
|
||||
eqDeleteGroups []equalityDeleteGroup,
|
||||
icebergSchema *iceberg.Schema,
|
||||
rowGroupRows int64,
|
||||
lineage bool,
|
||||
target *parquet.Schema,
|
||||
) ([]byte, int64, error) {
|
||||
if len(entries) == 0 {
|
||||
return nil, 0, fmt.Errorf("no entries to merge")
|
||||
@@ -1122,6 +1232,30 @@ func mergeParquetFiles(
|
||||
return nil, 0, fmt.Errorf("schema of %s: %w", entries[0].DataFile().FilePath(), err)
|
||||
}
|
||||
outputSchema = layout.schema
|
||||
} else if target != nil {
|
||||
outputSchema = target
|
||||
}
|
||||
|
||||
// joins is how one file enters the merge on a v1/v2 table: converted into
|
||||
// the writer's schema when that covers it, with its equality-delete
|
||||
// columns resolved on its own schema.
|
||||
joins := func(reader *parquet.Reader, entry iceberg.ManifestEntry) (parquet.Conversion, []resolvedEqDeleteGroup, error) {
|
||||
if layout != nil {
|
||||
return nil, resolvedEqGroups, nil // a v3 merge matches files with their lineage columns set aside
|
||||
}
|
||||
source := entry.DataFile().FilePath()
|
||||
conv, err := evolvedFileConversion(outputSchema, reader.Schema(), source)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if schemasEqual(parquetSchema, reader.Schema()) {
|
||||
return conv, resolvedEqGroups, nil
|
||||
}
|
||||
groups, err := resolveEqualityDeleteGroupsForSchema(reader.Schema(), eqDeleteGroups, icebergSchema)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("resolve equality columns in %s: %w", source, err)
|
||||
}
|
||||
return conv, groups, nil
|
||||
}
|
||||
|
||||
var outputBuf bytes.Buffer
|
||||
@@ -1129,7 +1263,17 @@ func mergeParquetFiles(
|
||||
|
||||
drainReader := func(reader *parquet.Reader, entry iceberg.ManifestEntry) (int64, error) {
|
||||
source := entry.DataFile().FilePath()
|
||||
return copyFileRows(ctx, reader, entry, layout, bucketName, dataPath, positionDeletes, resolvedEqGroups, eqDeleteGroups, icebergSchema, func(filtered []parquet.Row) error {
|
||||
conv, groups, err := joins(reader, entry)
|
||||
if err != nil {
|
||||
reader.Close()
|
||||
return 0, err
|
||||
}
|
||||
return copyFileRows(ctx, reader, entry, layout, bucketName, dataPath, positionDeletes, groups, eqDeleteGroups, icebergSchema, func(filtered []parquet.Row) error {
|
||||
if conv != nil {
|
||||
if _, err := conv.Convert(filtered); err != nil {
|
||||
return fmt.Errorf("convert rows from %s: %w", source, err)
|
||||
}
|
||||
}
|
||||
if _, err := writer.WriteRows(filtered); err != nil {
|
||||
return fmt.Errorf("write rows from %s: %w", source, err)
|
||||
}
|
||||
@@ -1161,13 +1305,6 @@ func mergeParquetFiles(
|
||||
}
|
||||
|
||||
reader := parquet.NewReader(bytes.NewReader(data))
|
||||
// A v3 merge matches files with their lineage columns set aside.
|
||||
if layout == nil && !schemasEqual(parquetSchema, reader.Schema()) {
|
||||
reader.Close()
|
||||
writer.Close()
|
||||
return nil, 0, fmt.Errorf("schema mismatch in %s: cannot merge files with different schemas", entry.DataFile().FilePath())
|
||||
}
|
||||
|
||||
rowsWritten, err := drainReader(reader, entry)
|
||||
if err != nil {
|
||||
writer.Close()
|
||||
@@ -1200,7 +1337,7 @@ func resolveEqualityDeleteGroupsForSchema(
|
||||
|
||||
resolved := make([]resolvedEqDeleteGroup, 0, len(eqDeleteGroups))
|
||||
for _, g := range eqDeleteGroups {
|
||||
indices, err := resolveEqualityColIndices(parquetSchema, g.FieldIDs, icebergSchema)
|
||||
indices, err := resolveEqualityColIndices(parquetSchema, g.FieldIDs, icebergSchema, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1429,7 +1566,8 @@ func compactRandomSuffix() string {
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// schemasEqual compares two parquet schemas structurally.
|
||||
// schemasEqual compares two parquet schemas structurally, and their Iceberg
|
||||
// field ids wherever both carry them.
|
||||
func schemasEqual(a, b *parquet.Schema) bool {
|
||||
if a == b {
|
||||
return true
|
||||
@@ -1437,7 +1575,32 @@ func schemasEqual(a, b *parquet.Schema) bool {
|
||||
if a == nil || b == nil {
|
||||
return false
|
||||
}
|
||||
return parquet.EqualNodes(a, b)
|
||||
return parquet.EqualNodes(a, b) && fieldIDsAgree(a, b)
|
||||
}
|
||||
|
||||
// fieldIDsAgree reports whether two structurally equal nodes carry the same
|
||||
// Iceberg field id at every position where both carry one. parquet-go's
|
||||
// EqualNodes ignores field ids, so a column dropped and re-added under the
|
||||
// same name and type (a new field id) looked like the old one, and a merge
|
||||
// filed the old values under the new field, or the live values under the
|
||||
// dropped one.
|
||||
func fieldIDsAgree(a, b parquet.Node) bool {
|
||||
if a.ID() > 0 && b.ID() > 0 && a.ID() != b.ID() {
|
||||
return false
|
||||
}
|
||||
if a.Leaf() || b.Leaf() {
|
||||
return a.Leaf() == b.Leaf()
|
||||
}
|
||||
fa, fb := a.Fields(), b.Fields()
|
||||
if len(fa) != len(fb) {
|
||||
return false
|
||||
}
|
||||
for i := range fa {
|
||||
if fa[i].Name() != fb[i].Name() || !fieldIDsAgree(fa[i], fb[i]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ensureFilerDir ensures a directory exists in the filer.
|
||||
|
||||
@@ -0,0 +1,644 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/apache/iceberg-go"
|
||||
"github.com/parquet-go/parquet-go"
|
||||
|
||||
filer_pb "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
// Files of one Iceberg table may spell its schema differently in Parquet:
|
||||
// a column added by schema evolution, or the same schema written REQUIRED
|
||||
// by one engine and OPTIONAL by another (PyIceberg writes REQUIRED, DuckDB
|
||||
// OPTIONAL). The bin-pack merge joins such files by Iceberg field id,
|
||||
// reading a column a file lacks as null, and refuses files whose same-name
|
||||
// columns carry different field ids (a column dropped and re-added).
|
||||
|
||||
type narrowSchemaRow struct { // id REQUIRED id=1, name OPTIONAL id=2
|
||||
ID int64 `parquet:"id,id(1)"`
|
||||
Name string `parquet:"name,id(2),optional"`
|
||||
}
|
||||
|
||||
type wideSchemaRow struct { // plus extra OPTIONAL id=3
|
||||
ID int64 `parquet:"id,id(1)"`
|
||||
Name string `parquet:"name,id(2),optional"`
|
||||
Extra string `parquet:"extra,id(3),optional"`
|
||||
}
|
||||
|
||||
type reorderedSchemaRow struct { // the wide schema's columns in another order
|
||||
Extra string `parquet:"extra,id(3),optional"`
|
||||
ID int64 `parquet:"id,id(1)"`
|
||||
Name string `parquet:"name,id(2),optional"`
|
||||
}
|
||||
|
||||
type optionalIDSchemaRow struct { // id OPTIONAL id=1
|
||||
ID int64 `parquet:"id,id(1),optional"`
|
||||
Name string `parquet:"name,id(2),optional"`
|
||||
}
|
||||
|
||||
type readdedNameSchemaRow struct { // name re-added under field id 3
|
||||
ID int64 `parquet:"id,id(1)"`
|
||||
Name string `parquet:"name,id(3),optional"`
|
||||
}
|
||||
|
||||
type nullableExtraSchemaRow struct { // the wide schema, extra writable as null
|
||||
ID int64 `parquet:"id,id(1)"`
|
||||
Name string `parquet:"name,id(2),optional"`
|
||||
Extra *string `parquet:"extra,id(3),optional"`
|
||||
}
|
||||
|
||||
func newAddedColumnSchema() *iceberg.Schema { // newTestSchema plus extra id=3
|
||||
return iceberg.NewSchema(0,
|
||||
iceberg.NestedField{ID: 1, Type: iceberg.PrimitiveTypes.Int64, Name: "id", Required: true},
|
||||
iceberg.NestedField{ID: 2, Type: iceberg.PrimitiveTypes.String, Name: "name", Required: false},
|
||||
iceberg.NestedField{ID: 3, Type: iceberg.PrimitiveTypes.String, Name: "extra", Required: false},
|
||||
)
|
||||
}
|
||||
|
||||
func schemaFileEntry(t *testing.T, path string, recordCount int64) iceberg.ManifestEntry {
|
||||
t.Helper()
|
||||
dfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentData,
|
||||
path, iceberg.ParquetFile, map[int]any{}, nil, nil, recordCount, 1024)
|
||||
if err != nil {
|
||||
t.Fatalf("build data file: %v", err)
|
||||
}
|
||||
snapID := int64(1)
|
||||
return iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dfb.Build())
|
||||
}
|
||||
|
||||
func mergeNamedFiles(t *testing.T, client filer_pb.SeaweedFilerClient, names []string, counts map[string]int64,
|
||||
eqGroups []equalityDeleteGroup, schema *iceberg.Schema, lineage bool) ([]byte, int64, error) {
|
||||
t.Helper()
|
||||
var entries []iceberg.ManifestEntry
|
||||
for _, name := range names {
|
||||
entries = append(entries, schemaFileEntry(t, "data/"+name, counts[name]))
|
||||
}
|
||||
return mergeParquetFiles(context.Background(), client, "test-bucket", "ns/tbl",
|
||||
entries, nil, eqGroups, schema, 0, lineage)
|
||||
}
|
||||
|
||||
// mergedValues returns the merged file's schema and each row's leaf values
|
||||
// in column order (nil for nulls).
|
||||
func mergedValues(t *testing.T, data []byte) (*parquet.Schema, [][]any) {
|
||||
t.Helper()
|
||||
f, err := parquet.OpenFile(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
t.Fatalf("open merged: %v", err)
|
||||
}
|
||||
var out [][]any
|
||||
for _, rg := range f.RowGroups() {
|
||||
rows := rg.Rows()
|
||||
buf := make([]parquet.Row, 16)
|
||||
for {
|
||||
n, err := rows.ReadRows(buf)
|
||||
for _, r := range buf[:n] {
|
||||
vals := make([]any, len(r))
|
||||
for i, v := range r {
|
||||
if v.IsNull() {
|
||||
continue
|
||||
}
|
||||
if v.Kind() == parquet.Int64 {
|
||||
vals[i] = v.Int64()
|
||||
} else {
|
||||
vals[i] = v.String()
|
||||
}
|
||||
}
|
||||
out = append(out, vals)
|
||||
}
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("read merged rows: %v", err)
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
}
|
||||
return f.Schema(), out
|
||||
}
|
||||
|
||||
func checkMergedRows(t *testing.T, data []byte, want [][]any) *parquet.Schema {
|
||||
t.Helper()
|
||||
schema, got := mergedValues(t, data)
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("merged rows = %v, want %v", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if len(got[i]) != len(want[i]) {
|
||||
t.Fatalf("row %d = %v, want %v", i, got[i], want[i])
|
||||
}
|
||||
for j := range want[i] {
|
||||
if got[i][j] != want[i][j] {
|
||||
t.Fatalf("row %d column %d = %v, want %v (row %v)", i, j, got[i][j], want[i][j], got[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
return schema
|
||||
}
|
||||
|
||||
// A column added to the table after some files were written: the merge
|
||||
// joins the files by field id and reads the new column as null for the
|
||||
// old file's rows, whichever file leads the bin.
|
||||
func TestMergeParquetFilesAddedColumn(t *testing.T) {
|
||||
put := func(fs *fakeFilerServer) map[string]int64 {
|
||||
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}, {2, "b"}, {3, "c"}})
|
||||
putDataFileRows(t, fs, "wide.parquet", []wideSchemaRow{{4, "d", "e4"}, {5, "e", "e5"}})
|
||||
return map[string]int64{"narrow.parquet": 3, "wide.parquet": 2}
|
||||
}
|
||||
checkFields := func(t *testing.T, schema *parquet.Schema) {
|
||||
fields := schema.Fields()
|
||||
if len(fields) != 3 {
|
||||
t.Fatalf("merged fields = %d, want 3", len(fields))
|
||||
}
|
||||
names := []string{fields[0].Name(), fields[1].Name(), fields[2].Name()}
|
||||
if names[0] != "id" || names[1] != "name" || names[2] != "extra" {
|
||||
t.Fatalf("merged fields = %v, want [id name extra]", names)
|
||||
}
|
||||
if fields[2].ID() != 3 {
|
||||
t.Fatalf("extra field id = %d, want 3", fields[2].ID())
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("narrow first", func(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
counts := put(fs)
|
||||
merged, count, err := mergeNamedFiles(t, client,
|
||||
[]string{"narrow.parquet", "wide.parquet"}, counts, nil, nil, false)
|
||||
if err != nil {
|
||||
t.Fatalf("mergeParquetFiles: %v", err)
|
||||
}
|
||||
if count != 5 {
|
||||
t.Fatalf("merged %d rows, want 5", count)
|
||||
}
|
||||
checkFields(t, checkMergedRows(t, merged, [][]any{
|
||||
{int64(1), "a", nil},
|
||||
{int64(2), "b", nil},
|
||||
{int64(3), "c", nil},
|
||||
{int64(4), "d", "e4"},
|
||||
{int64(5), "e", "e5"},
|
||||
}))
|
||||
})
|
||||
|
||||
t.Run("wide first", func(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
counts := put(fs)
|
||||
merged, count, err := mergeNamedFiles(t, client,
|
||||
[]string{"wide.parquet", "narrow.parquet"}, counts, nil, nil, false)
|
||||
if err != nil {
|
||||
t.Fatalf("mergeParquetFiles: %v", err)
|
||||
}
|
||||
if count != 5 {
|
||||
t.Fatalf("merged %d rows, want 5", count)
|
||||
}
|
||||
checkFields(t, checkMergedRows(t, merged, [][]any{
|
||||
{int64(4), "d", "e4"},
|
||||
{int64(5), "e", "e5"},
|
||||
{int64(1), "a", nil},
|
||||
{int64(2), "b", nil},
|
||||
{int64(3), "c", nil},
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
// The same Iceberg schema written REQUIRED by one engine and OPTIONAL by
|
||||
// another merges; the writer keeps the wider, optional, repetition.
|
||||
func TestMergeParquetFilesRequiredVsOptional(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
putDataFileRows(t, fs, "required.parquet", []narrowSchemaRow{{1, "a"}, {2, "b"}})
|
||||
putDataFileRows(t, fs, "optional.parquet", []optionalIDSchemaRow{{3, "c"}, {4, "d"}})
|
||||
|
||||
merged, count, err := mergeNamedFiles(t, client,
|
||||
[]string{"required.parquet", "optional.parquet"},
|
||||
map[string]int64{"required.parquet": 2, "optional.parquet": 2}, nil, nil, false)
|
||||
if err != nil {
|
||||
t.Fatalf("mergeParquetFiles: %v", err)
|
||||
}
|
||||
if count != 4 {
|
||||
t.Fatalf("merged %d rows, want 4", count)
|
||||
}
|
||||
schema := checkMergedRows(t, merged, [][]any{
|
||||
{int64(1), "a"},
|
||||
{int64(2), "b"},
|
||||
{int64(3), "c"},
|
||||
{int64(4), "d"},
|
||||
})
|
||||
if !schema.Fields()[0].Optional() {
|
||||
t.Error("merged id column is REQUIRED, want OPTIONAL")
|
||||
}
|
||||
}
|
||||
|
||||
// A column dropped and re-added under the same name and type has a new
|
||||
// field id; merging its file with an old one would file the new column's
|
||||
// values under the dropped field id, so the bin is refused.
|
||||
func TestMergeParquetFilesReaddedColumn(t *testing.T) {
|
||||
for _, names := range [][]string{
|
||||
{"narrow.parquet", "re-added.parquet"},
|
||||
{"re-added.parquet", "narrow.parquet"},
|
||||
} {
|
||||
fs, client := startFakeFiler(t)
|
||||
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}})
|
||||
putDataFileRows(t, fs, "re-added.parquet", []readdedNameSchemaRow{{2, "new-2"}})
|
||||
|
||||
_, _, err := mergeNamedFiles(t, client, names,
|
||||
map[string]int64{"narrow.parquet": 1, "re-added.parquet": 1}, nil, nil, false)
|
||||
if err == nil || !strings.Contains(err.Error(), "cannot merge files with different schemas") {
|
||||
t.Errorf("merge of %v: %v, want schema mismatch", names, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type disjointColumnsRow struct { // id id=1, extra id=3: no name
|
||||
ID int64 `parquet:"id,id(1)"`
|
||||
Extra string `parquet:"extra,id(3),optional"`
|
||||
}
|
||||
|
||||
type requiredExtraSchemaRow struct { // extra REQUIRED id=3
|
||||
ID int64 `parquet:"id,id(1)"`
|
||||
Name string `parquet:"name,id(2),optional"`
|
||||
Extra string `parquet:"extra,id(3)"`
|
||||
}
|
||||
|
||||
// Differences field-id matching does not cover stay refused: a rename, a
|
||||
// type change, files without field ids; and a control pair still compacts.
|
||||
func TestMergeParquetFilesSchemaRefusals(t *testing.T) {
|
||||
type renamedSchemaRow struct {
|
||||
ID int64 `parquet:"id,id(1)"`
|
||||
Other string `parquet:"other,id(2),optional"`
|
||||
}
|
||||
type widenedSchemaRow struct {
|
||||
ID int32 `parquet:"id,id(1)"`
|
||||
Name string `parquet:"name,id(2),optional"`
|
||||
}
|
||||
type noIDExtraRow struct {
|
||||
ID int64 `parquet:"id"`
|
||||
Name string `parquet:"name,optional"`
|
||||
Extra string `parquet:"extra,optional"`
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
writeFile func(fs *fakeFilerServer, name string)
|
||||
}{
|
||||
{"rename", func(fs *fakeFilerServer, name string) {
|
||||
putDataFileRows(t, fs, name, []renamedSchemaRow{{5, "e"}})
|
||||
}},
|
||||
{"type change", func(fs *fakeFilerServer, name string) {
|
||||
putDataFileRows(t, fs, name, []widenedSchemaRow{{5, "e"}})
|
||||
}},
|
||||
{"no field ids", func(fs *fakeFilerServer, name string) {
|
||||
putDataFileRows(t, fs, name, []noIDExtraRow{{5, "e", "x"}})
|
||||
}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}})
|
||||
tc.writeFile(fs, "other.parquet")
|
||||
|
||||
_, _, err := mergeNamedFiles(t, client,
|
||||
[]string{"narrow.parquet", "other.parquet"},
|
||||
map[string]int64{"narrow.parquet": 1, "other.parquet": 1}, nil, nil, false)
|
||||
if err == nil || !strings.Contains(err.Error(), "cannot merge files with different schemas") {
|
||||
t.Errorf("merge: %v, want schema mismatch", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("control", func(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
putDataFileRows(t, fs, "a.parquet", []narrowSchemaRow{{1, "a"}})
|
||||
putDataFileRows(t, fs, "b.parquet", []narrowSchemaRow{{2, "b"}})
|
||||
if _, _, err := mergeNamedFiles(t, client, []string{"a.parquet", "b.parquet"},
|
||||
map[string]int64{"a.parquet": 1, "b.parquet": 1}, nil, nil, false); err != nil {
|
||||
t.Errorf("control merge: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// An equality-delete column can sit at a different position in an older
|
||||
// file: it is resolved on each file's own schema.
|
||||
func TestMergeParquetFilesEvolvedSchemaEqualityDelete(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}, {2, "b"}, {3, "c"}})
|
||||
putDataFileRows(t, fs, "reordered.parquet", []reorderedSchemaRow{
|
||||
{"e4", 4, "d"}, {"e5", 5, "e"},
|
||||
})
|
||||
|
||||
// An equality delete on name (field id 2) for "b" (index 1 in the
|
||||
// narrow file) and "e" (index 2 in the reordered file).
|
||||
type eqDeleteRow struct {
|
||||
Name string `parquet:"name"`
|
||||
}
|
||||
var eqBuf bytes.Buffer
|
||||
eqWriter := parquet.NewWriter(&eqBuf, parquet.SchemaOf(new(eqDeleteRow)))
|
||||
for _, r := range []eqDeleteRow{{"b"}, {"e"}} {
|
||||
if err := eqWriter.Write(&r); err != nil {
|
||||
t.Fatalf("write eq delete: %v", err)
|
||||
}
|
||||
}
|
||||
if err := eqWriter.Close(); err != nil {
|
||||
t.Fatalf("close eq writer: %v", err)
|
||||
}
|
||||
fs.putEntry("/buckets/test-bucket/ns/tbl/data", "eq-del.parquet", &filer_pb.Entry{
|
||||
Name: "eq-del.parquet", Content: eqBuf.Bytes(),
|
||||
})
|
||||
|
||||
eqDfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentEqDeletes,
|
||||
"data/eq-del.parquet", iceberg.ParquetFile, map[int]any{}, nil, nil, 2, int64(eqBuf.Len()))
|
||||
if err != nil {
|
||||
t.Fatalf("build eq delete: %v", err)
|
||||
}
|
||||
eqDfb.EqualityFieldIDs([]int{2})
|
||||
snapID := int64(1)
|
||||
eqEntry := iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, eqDfb.Build())
|
||||
|
||||
eqGroups, err := collectEqualityDeletes(context.Background(), client, "test-bucket", "ns/tbl",
|
||||
[]iceberg.ManifestEntry{eqEntry}, newTestSchema())
|
||||
if err != nil {
|
||||
t.Fatalf("collectEqualityDeletes: %v", err)
|
||||
}
|
||||
|
||||
merged, count, err := mergeNamedFiles(t, client,
|
||||
[]string{"narrow.parquet", "reordered.parquet"},
|
||||
map[string]int64{"narrow.parquet": 3, "reordered.parquet": 2}, eqGroups, newTestSchema(), false)
|
||||
if err != nil {
|
||||
t.Fatalf("mergeParquetFiles: %v", err)
|
||||
}
|
||||
if count != 3 {
|
||||
t.Fatalf("merged %d rows, want 3", count)
|
||||
}
|
||||
// The union schema (id, name, extra) is the writer's.
|
||||
checkMergedRows(t, merged, [][]any{
|
||||
{int64(1), "a", nil},
|
||||
{int64(3), "c", nil},
|
||||
{int64(4), "d", "e4"},
|
||||
})
|
||||
}
|
||||
|
||||
// File pairs where neither schema covers the other merge under the union
|
||||
// writer schema: a REQUIRED/OPTIONAL difference plus an added column, a
|
||||
// column each side lacks the other's of, and an added REQUIRED column
|
||||
// (demoted to OPTIONAL: the files without it read null).
|
||||
func TestMergeParquetFilesUnionWriterSchema(t *testing.T) {
|
||||
t.Run("added column and repetition differ", func(t *testing.T) {
|
||||
for _, names := range [][]string{
|
||||
{"wide.parquet", "optional.parquet"},
|
||||
{"optional.parquet", "wide.parquet"},
|
||||
} {
|
||||
fs, client := startFakeFiler(t)
|
||||
putDataFileRows(t, fs, "wide.parquet", []wideSchemaRow{{4, "d", "e4"}, {5, "e", "e5"}})
|
||||
putDataFileRows(t, fs, "optional.parquet", []optionalIDSchemaRow{{1, "a"}, {2, "b"}})
|
||||
|
||||
merged, count, err := mergeNamedFiles(t, client, names,
|
||||
map[string]int64{"wide.parquet": 2, "optional.parquet": 2}, nil, nil, false)
|
||||
if err != nil {
|
||||
t.Fatalf("merge of %v: %v", names, err)
|
||||
}
|
||||
if count != 4 {
|
||||
t.Fatalf("merged %d rows, want 4", count)
|
||||
}
|
||||
var want [][]any
|
||||
if names[0] == "wide.parquet" {
|
||||
want = [][]any{{int64(4), "d", "e4"}, {int64(5), "e", "e5"}, {int64(1), "a", nil}, {int64(2), "b", nil}}
|
||||
} else {
|
||||
want = [][]any{{int64(1), "a", nil}, {int64(2), "b", nil}, {int64(4), "d", "e4"}, {int64(5), "e", "e5"}}
|
||||
}
|
||||
schema := checkMergedRows(t, merged, want)
|
||||
if !schema.Fields()[0].Optional() {
|
||||
t.Errorf("merged id column is REQUIRED, want OPTIONAL")
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("disjoint columns", func(t *testing.T) {
|
||||
for _, names := range [][]string{
|
||||
{"narrow.parquet", "disjoint.parquet"},
|
||||
{"disjoint.parquet", "narrow.parquet"},
|
||||
} {
|
||||
fs, client := startFakeFiler(t)
|
||||
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}})
|
||||
putDataFileRows(t, fs, "disjoint.parquet", []disjointColumnsRow{{5, "e"}})
|
||||
|
||||
merged, count, err := mergeNamedFiles(t, client, names,
|
||||
map[string]int64{"narrow.parquet": 1, "disjoint.parquet": 1}, nil, nil, false)
|
||||
if err != nil {
|
||||
t.Fatalf("merge of %v: %v", names, err)
|
||||
}
|
||||
if count != 2 {
|
||||
t.Fatalf("merged %d rows, want 2", count)
|
||||
}
|
||||
var want [][]any
|
||||
if names[0] == "narrow.parquet" { // union (id, name, extra)
|
||||
want = [][]any{{int64(1), "a", nil}, {int64(5), nil, "e"}}
|
||||
} else { // union (id, extra, name)
|
||||
want = [][]any{{int64(5), "e", nil}, {int64(1), nil, "a"}}
|
||||
}
|
||||
checkMergedRows(t, merged, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("added required column", func(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}})
|
||||
putDataFileRows(t, fs, "required-extra.parquet", []requiredExtraSchemaRow{{5, "e", "x"}})
|
||||
|
||||
merged, count, err := mergeNamedFiles(t, client,
|
||||
[]string{"narrow.parquet", "required-extra.parquet"},
|
||||
map[string]int64{"narrow.parquet": 1, "required-extra.parquet": 1}, nil, nil, false)
|
||||
if err != nil {
|
||||
t.Fatalf("mergeParquetFiles: %v", err)
|
||||
}
|
||||
if count != 2 {
|
||||
t.Fatalf("merged %d rows, want 2", count)
|
||||
}
|
||||
schema := checkMergedRows(t, merged, [][]any{
|
||||
{int64(1), "a", nil},
|
||||
{int64(5), "e", "x"},
|
||||
})
|
||||
if !schema.Fields()[2].Optional() {
|
||||
t.Error("merged extra column is REQUIRED, want OPTIONAL")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// An equality delete naming a column added after some files were written:
|
||||
// the files that lack it read the delete key's column as null, so a real
|
||||
// key does not match their rows and a null key deletes them all.
|
||||
func TestMergeParquetFilesEqualityDeleteAddedColumn(t *testing.T) {
|
||||
strPtr := func(s string) *string { return &s }
|
||||
put := func(fs *fakeFilerServer) map[string]int64 {
|
||||
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}, {2, "b"}, {3, "c"}})
|
||||
putDataFileRows(t, fs, "wide.parquet", []nullableExtraSchemaRow{{4, "d", strPtr("e4")}, {5, "e", nil}})
|
||||
return map[string]int64{"narrow.parquet": 3, "wide.parquet": 2}
|
||||
}
|
||||
eqGroups := func(keys ...parquet.Value) []equalityDeleteGroup {
|
||||
set := make(map[string]struct{}, len(keys))
|
||||
for _, k := range keys {
|
||||
set[buildEqualityKey(parquet.Row{k}, []int{0})] = struct{}{}
|
||||
}
|
||||
return []equalityDeleteGroup{{FieldIDs: []int{3}, Keys: set}}
|
||||
}
|
||||
schema := newAddedColumnSchema()
|
||||
|
||||
t.Run("key matches no null", func(t *testing.T) {
|
||||
for _, names := range [][]string{
|
||||
{"narrow.parquet", "wide.parquet"},
|
||||
{"wide.parquet", "narrow.parquet"},
|
||||
} {
|
||||
fs, client := startFakeFiler(t)
|
||||
counts := put(fs)
|
||||
merged, count, err := mergeNamedFiles(t, client, names, counts,
|
||||
eqGroups(parquet.ValueOf("e4")), schema, false)
|
||||
if err != nil {
|
||||
t.Fatalf("merge of %v: %v", names, err)
|
||||
}
|
||||
if count != 4 {
|
||||
t.Fatalf("merged %d rows, want 4", count)
|
||||
}
|
||||
var want [][]any
|
||||
if names[0] == "narrow.parquet" {
|
||||
want = [][]any{{int64(1), "a", nil}, {int64(2), "b", nil}, {int64(3), "c", nil}, {int64(5), "e", nil}}
|
||||
} else {
|
||||
want = [][]any{{int64(5), "e", nil}, {int64(1), "a", nil}, {int64(2), "b", nil}, {int64(3), "c", nil}}
|
||||
}
|
||||
checkMergedRows(t, merged, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("null key deletes nulls", func(t *testing.T) {
|
||||
for _, names := range [][]string{
|
||||
{"narrow.parquet", "wide.parquet"},
|
||||
{"wide.parquet", "narrow.parquet"},
|
||||
} {
|
||||
fs, client := startFakeFiler(t)
|
||||
counts := put(fs)
|
||||
merged, count, err := mergeNamedFiles(t, client, names, counts,
|
||||
eqGroups(parquet.NullValue()), schema, false)
|
||||
if err != nil {
|
||||
t.Fatalf("merge of %v: %v", names, err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("merged %d rows, want 1", count)
|
||||
}
|
||||
checkMergedRows(t, merged, [][]any{{int64(4), "d", "e4"}})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A column renamed after its files were written still carries its field id,
|
||||
// so an equality delete on it resolves the column by id and removes only the
|
||||
// rows it names — the old name looking absent must not turn every key null.
|
||||
func TestMergeParquetFilesEqualityDeleteRenamedColumn(t *testing.T) {
|
||||
// The table renamed name (field id 2) to label; every file still spells
|
||||
// the old name.
|
||||
schema := iceberg.NewSchema(0,
|
||||
iceberg.NestedField{ID: 1, Type: iceberg.PrimitiveTypes.Int64, Name: "id", Required: true},
|
||||
iceberg.NestedField{ID: 2, Type: iceberg.PrimitiveTypes.String, Name: "label", Required: false},
|
||||
)
|
||||
type eqDeleteRow struct {
|
||||
Name string `parquet:"name,id(2)"`
|
||||
}
|
||||
|
||||
fs, client := startFakeFiler(t)
|
||||
putDataFileRows(t, fs, "a.parquet", []narrowSchemaRow{{1, "a"}, {2, "b"}, {3, "c"}})
|
||||
putDataFileRows(t, fs, "b.parquet", []narrowSchemaRow{{4, "d"}})
|
||||
|
||||
var eqBuf bytes.Buffer
|
||||
eqWriter := parquet.NewWriter(&eqBuf, parquet.SchemaOf(new(eqDeleteRow)))
|
||||
if err := eqWriter.Write(&eqDeleteRow{"b"}); err != nil {
|
||||
t.Fatalf("write eq delete: %v", err)
|
||||
}
|
||||
if err := eqWriter.Close(); err != nil {
|
||||
t.Fatalf("close eq writer: %v", err)
|
||||
}
|
||||
fs.putEntry("/buckets/test-bucket/ns/tbl/data", "eq-del.parquet", &filer_pb.Entry{
|
||||
Name: "eq-del.parquet", Content: eqBuf.Bytes(),
|
||||
})
|
||||
|
||||
eqDfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentEqDeletes,
|
||||
"data/eq-del.parquet", iceberg.ParquetFile, map[int]any{}, nil, nil, 1, int64(eqBuf.Len()))
|
||||
if err != nil {
|
||||
t.Fatalf("build eq delete: %v", err)
|
||||
}
|
||||
eqDfb.EqualityFieldIDs([]int{2})
|
||||
snapID := int64(1)
|
||||
eqEntry := iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, eqDfb.Build())
|
||||
|
||||
eqGroups, err := collectEqualityDeletes(context.Background(), client, "test-bucket", "ns/tbl",
|
||||
[]iceberg.ManifestEntry{eqEntry}, schema)
|
||||
if err != nil {
|
||||
t.Fatalf("collectEqualityDeletes: %v", err)
|
||||
}
|
||||
|
||||
merged, count, err := mergeNamedFiles(t, client,
|
||||
[]string{"a.parquet", "b.parquet"},
|
||||
map[string]int64{"a.parquet": 3, "b.parquet": 1}, eqGroups, schema, false)
|
||||
if err != nil {
|
||||
t.Fatalf("mergeParquetFiles: %v", err)
|
||||
}
|
||||
if count != 3 {
|
||||
t.Fatalf("merged %d rows, want 3", count)
|
||||
}
|
||||
checkMergedRows(t, merged, [][]any{
|
||||
{int64(1), "a"},
|
||||
{int64(3), "c"},
|
||||
{int64(4), "d"},
|
||||
})
|
||||
}
|
||||
|
||||
// An equality-delete file that lacks its equality column is refused rather
|
||||
// than read as null keys: the spec requires equality deletes to carry the
|
||||
// columns they name, so the missing-column fallback is for data files only.
|
||||
func TestEqualityDeleteFileMissingColumn(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
type otherRow struct {
|
||||
Other string `parquet:"other,id(9)"`
|
||||
}
|
||||
var eqBuf bytes.Buffer
|
||||
eqWriter := parquet.NewWriter(&eqBuf, parquet.SchemaOf(new(otherRow)))
|
||||
if err := eqWriter.Write(&otherRow{"x"}); err != nil {
|
||||
t.Fatalf("write eq delete: %v", err)
|
||||
}
|
||||
if err := eqWriter.Close(); err != nil {
|
||||
t.Fatalf("close eq writer: %v", err)
|
||||
}
|
||||
fs.putEntry("/buckets/test-bucket/ns/tbl/data", "eq-del.parquet", &filer_pb.Entry{
|
||||
Name: "eq-del.parquet", Content: eqBuf.Bytes(),
|
||||
})
|
||||
|
||||
eqDfb, err := iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentEqDeletes,
|
||||
"data/eq-del.parquet", iceberg.ParquetFile, map[int]any{}, nil, nil, 1, int64(eqBuf.Len()))
|
||||
if err != nil {
|
||||
t.Fatalf("build eq delete: %v", err)
|
||||
}
|
||||
eqDfb.EqualityFieldIDs([]int{2})
|
||||
snapID := int64(1)
|
||||
eqEntry := iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, eqDfb.Build())
|
||||
|
||||
_, err = collectEqualityDeletes(context.Background(), client, "test-bucket", "ns/tbl",
|
||||
[]iceberg.ManifestEntry{eqEntry}, newAddedColumnSchema())
|
||||
if err == nil {
|
||||
t.Fatal("collectEqualityDeletes: want an error for a missing equality column")
|
||||
}
|
||||
}
|
||||
|
||||
// The v3 merge matches files on the first file's columns; the re-added
|
||||
// column is refused there too.
|
||||
func TestMergeParquetFilesV3ReaddedColumn(t *testing.T) {
|
||||
fs, client := startFakeFiler(t)
|
||||
putDataFileRows(t, fs, "narrow.parquet", []narrowSchemaRow{{1, "a"}})
|
||||
putDataFileRows(t, fs, "re-added.parquet", []readdedNameSchemaRow{{2, "new-2"}})
|
||||
|
||||
_, _, err := mergeNamedFiles(t, client,
|
||||
[]string{"narrow.parquet", "re-added.parquet"},
|
||||
map[string]int64{"narrow.parquet": 1, "re-added.parquet": 1}, nil, nil, true)
|
||||
if err == nil || !strings.Contains(err.Error(), "cannot merge files with different schemas") {
|
||||
t.Fatalf("merge: %v, want schema mismatch", err)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/parquet-go/parquet-go"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
@@ -160,9 +162,9 @@ func loadCurrentMetadata(ctx context.Context, client filer_pb.SeaweedFilerClient
|
||||
return state, nil
|
||||
}
|
||||
|
||||
// loadFileByIcebergPath loads a file from the filer given an Iceberg-style path.
|
||||
// dataPath is the bucket-relative directory the table's files live in.
|
||||
func loadFileByIcebergPath(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketName, dataPath, icebergPath string) ([]byte, error) {
|
||||
// lookupFileByIcebergPath returns the filer entry holding an Iceberg-style
|
||||
// path. dataPath is the bucket-relative directory the table's files live in.
|
||||
func lookupFileByIcebergPath(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketName, dataPath, icebergPath string) (*filer_pb.Entry, error) {
|
||||
fullPath, err := icebergFilerPath(bucketName, dataPath, icebergPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -179,23 +181,65 @@ func loadFileByIcebergPath(ctx context.Context, client filer_pb.SeaweedFilerClie
|
||||
if resp == nil || resp.Entry == nil {
|
||||
return nil, fmt.Errorf("file not found: %s/%s", dir, fileName)
|
||||
}
|
||||
return resp.Entry, nil
|
||||
}
|
||||
|
||||
if len(resp.Entry.Content) > 0 || len(resp.Entry.Chunks) == 0 {
|
||||
return resp.Entry.Content, nil
|
||||
// loadFileByIcebergPath loads a file from the filer given an Iceberg-style path.
|
||||
func loadFileByIcebergPath(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketName, dataPath, icebergPath string) ([]byte, error) {
|
||||
entry, err := lookupFileByIcebergPath(ctx, client, bucketName, dataPath, icebergPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(entry.Content) > 0 || len(entry.Chunks) == 0 {
|
||||
return entry.Content, nil
|
||||
}
|
||||
|
||||
initGlobalHTTPClientOnce.Do(util_http.InitGlobalHttpClient)
|
||||
reader := filer.NewFileReader(singleFilerClient{client: client}, resp.Entry)
|
||||
reader := filer.NewFileReader(singleFilerClient{client: client}, entry)
|
||||
if closer, ok := reader.(io.Closer); ok {
|
||||
defer closer.Close()
|
||||
}
|
||||
data, err := io.ReadAll(reader)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read chunked file %s/%s: %w", dir, fileName, err)
|
||||
return nil, fmt.Errorf("read chunked file %s: %w", icebergPath, err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// parquetSchemaByIcebergPath reads a file's parquet schema from its footer,
|
||||
// so the file's body is never fetched: a chunked file's ReadAt pulls only the
|
||||
// chunks the footer spans.
|
||||
func parquetSchemaByIcebergPath(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketName, dataPath, icebergPath string) (*parquet.Schema, error) {
|
||||
entry, err := lookupFileByIcebergPath(ctx, client, bucketName, dataPath, icebergPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var readerAt io.ReaderAt
|
||||
size := int64(entry.GetAttributes().GetFileSize())
|
||||
if len(entry.Content) > 0 || len(entry.Chunks) == 0 {
|
||||
readerAt = bytes.NewReader(entry.Content)
|
||||
size = int64(len(entry.Content))
|
||||
} else {
|
||||
initGlobalHTTPClientOnce.Do(util_http.InitGlobalHttpClient)
|
||||
reader := filer.NewChunkStreamReader(singleFilerClient{client: client}, entry.Chunks)
|
||||
defer reader.Close()
|
||||
readerAt = reader
|
||||
if size <= 0 {
|
||||
if size, err = reader.Seek(0, io.SeekEnd); err != nil {
|
||||
return nil, fmt.Errorf("size of %s: %w", icebergPath, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
f, err := parquet.OpenFile(readerAt, size)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open parquet file %s: %w", icebergPath, err)
|
||||
}
|
||||
return f.Schema(), nil
|
||||
}
|
||||
|
||||
// normalizeIcebergPath converts an Iceberg path (an S3 URL, an absolute filer
|
||||
// path, or a path relative to the table root) into a path relative to the
|
||||
// bucket root, e.g. "ns/table/metadata/snap-1.avro". Absolute references are
|
||||
|
||||
@@ -342,6 +342,9 @@ func collectOrphanCandidates(
|
||||
}
|
||||
|
||||
referencedFiles[path.Join("metadata", metadataFileName)] = struct{}{}
|
||||
// Table-root readers (DuckDB iceberg_scan, Hadoop tables) open this to find
|
||||
// the current metadata; nothing in the metadata references it.
|
||||
referencedFiles[path.Join("metadata", "version-hint.text")] = struct{}{}
|
||||
for mle := range meta.PreviousFiles() {
|
||||
referencedFiles[mle.MetadataFile] = struct{}{}
|
||||
}
|
||||
|
||||
@@ -210,7 +210,8 @@ func (l *lineageLayout) mapperFor(input *parquet.Schema, src lineageSource) (*li
|
||||
next++
|
||||
continue
|
||||
}
|
||||
if base >= len(l.baseFields) || f.Name() != l.baseFields[base].Name() || !parquet.EqualNodes(f, l.baseFields[base]) {
|
||||
if base >= len(l.baseFields) || f.Name() != l.baseFields[base].Name() || !parquet.EqualNodes(f, l.baseFields[base]) ||
|
||||
!fieldIDsAgree(f, l.baseFields[base]) {
|
||||
return nil, fmt.Errorf("cannot merge files with different schemas")
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
package iceberg
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"github.com/parquet-go/parquet-go"
|
||||
)
|
||||
|
||||
// The bin-pack merge of a v1/v2 table whose data files spell its schema
|
||||
// differently. A bin used to take the first file's Parquet schema as the
|
||||
// writer's and refuse every file whose schema was not structurally identical
|
||||
// ("cannot merge files with different schemas"). That refused:
|
||||
// - schema evolution: a column added to the table after some files were
|
||||
// written;
|
||||
// - one Iceberg schema written REQUIRED by one engine and OPTIONAL by another.
|
||||
//
|
||||
// The writer's schema is now the union of the bin's files' schemas, matched
|
||||
// by Iceberg field id and computed before any row is written (schemaUnion),
|
||||
// so every file converts into it in a single pass:
|
||||
// - the same field id carries the same name and type;
|
||||
// - the writer's column may be optional where the file's is required, never
|
||||
// the reverse;
|
||||
// - a writer column the file lacks must be optional, and reads as null.
|
||||
//
|
||||
// Anything else (a rename, a type change, the same name under different field
|
||||
// ids, nested columns, no field ids) is refused as before.
|
||||
|
||||
// flatColumnsByFieldID is the schema's columns by Iceberg field id when every
|
||||
// column is a top-level, non-repeated leaf with a field id of its own; ok is
|
||||
// false otherwise.
|
||||
func flatColumnsByFieldID(s *parquet.Schema) (map[int]parquet.Field, bool) {
|
||||
if s == nil {
|
||||
return nil, false
|
||||
}
|
||||
out := make(map[int]parquet.Field)
|
||||
for _, f := range s.Fields() {
|
||||
if !f.Leaf() || f.Repeated() || f.ID() <= 0 {
|
||||
return nil, false
|
||||
}
|
||||
if _, dup := out[f.ID()]; dup {
|
||||
return nil, false
|
||||
}
|
||||
out[f.ID()] = f
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
// schemaCovers reports whether every row of a file written in source converts
|
||||
// to target without losing or inventing a value (the rules above).
|
||||
func schemaCovers(target, source *parquet.Schema) bool {
|
||||
targetCols, ok := flatColumnsByFieldID(target)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
sourceCols, ok := flatColumnsByFieldID(source)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
for id, s := range sourceCols {
|
||||
t, ok := targetCols[id]
|
||||
if !ok || t.Name() != s.Name() || !parquet.EqualTypes(t.Type(), s.Type()) {
|
||||
return false
|
||||
}
|
||||
if t.Required() && !s.Required() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for id, t := range targetCols {
|
||||
if _, ok := sourceCols[id]; !ok && !t.Optional() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// schemaUnion folds a bin's file schemas into the writer schema the merge
|
||||
// needs: every field id any file carries, in the order first seen, under the
|
||||
// name and type all of its files agree on. A column is REQUIRED only when
|
||||
// every file has it and spells it so; a file that lacks it or spells it
|
||||
// optional reads and writes nulls there. A shared field id with a different
|
||||
// name or type, or the same name under different field ids (a column dropped
|
||||
// and re-added), is a conflict the merge refuses.
|
||||
type schemaUnion struct {
|
||||
fields []unionField
|
||||
byID map[int]int
|
||||
byName map[string]int
|
||||
folds int
|
||||
}
|
||||
|
||||
type unionField struct {
|
||||
field parquet.Field // the field as first seen
|
||||
required bool // required in every file that carries it
|
||||
presentInAll bool // present in every file folded so far
|
||||
}
|
||||
|
||||
func (u *schemaUnion) fold(s *parquet.Schema, path string) error {
|
||||
cols, ok := flatColumnsByFieldID(s)
|
||||
if !ok {
|
||||
return fmt.Errorf("schema of %s does not key flat columns by field id", path)
|
||||
}
|
||||
if u.byID == nil {
|
||||
u.byID, u.byName = make(map[int]int), make(map[string]int)
|
||||
}
|
||||
for _, f := range s.Fields() {
|
||||
id, name := f.ID(), f.Name()
|
||||
if j, ok := u.byID[id]; ok {
|
||||
e := &u.fields[j]
|
||||
if e.field.Name() != name || !parquet.EqualTypes(e.field.Type(), f.Type()) {
|
||||
return fmt.Errorf("field id %d is %q in one file but %q in %s", id, e.field.Name(), name, path)
|
||||
}
|
||||
e.required = e.required && f.Required()
|
||||
continue
|
||||
}
|
||||
if _, ok := u.byName[name]; ok {
|
||||
return fmt.Errorf("column %q carries different field ids in %s", name, path)
|
||||
}
|
||||
u.byID[id], u.byName[name] = len(u.fields), id
|
||||
// A field folded in after the first schema is absent from every
|
||||
// file seen before it.
|
||||
u.fields = append(u.fields, unionField{field: f, required: f.Required(), presentInAll: u.folds == 0})
|
||||
}
|
||||
for i := range u.fields {
|
||||
if _, ok := cols[u.fields[i].field.ID()]; !ok {
|
||||
u.fields[i].presentInAll = false
|
||||
}
|
||||
}
|
||||
u.folds++
|
||||
return nil
|
||||
}
|
||||
|
||||
// schema is the union as a writer schema; name and group give the root node
|
||||
// (their Go type is never read: the merge writes parquet.Row values).
|
||||
func (u *schemaUnion) schema(name string, group parquet.Node) *parquet.Schema {
|
||||
fields := make([]parquet.Field, len(u.fields))
|
||||
for i, e := range u.fields {
|
||||
fields[i] = e.field
|
||||
if !e.field.Optional() && !(e.required && e.presentInAll) {
|
||||
fields[i] = unionOptionalField{Node: parquet.Optional(e.field), name: e.field.Name()}
|
||||
}
|
||||
}
|
||||
return parquet.NewSchema(name, &orderedGroup{Node: group, fields: fields})
|
||||
}
|
||||
|
||||
// unionOptionalField spells a field optional in the union schema when the
|
||||
// file it came from wrote it required.
|
||||
type unionOptionalField struct {
|
||||
parquet.Node
|
||||
name string
|
||||
}
|
||||
|
||||
func (f unionOptionalField) Name() string { return f.name }
|
||||
func (f unionOptionalField) Value(base reflect.Value) reflect.Value { return reflect.Value{} }
|
||||
|
||||
// widerSchemaError stops a merge that met a file whose schema covers the
|
||||
// writer's: the bin is merged again with it.
|
||||
type widerSchemaError struct {
|
||||
schema *parquet.Schema
|
||||
path string
|
||||
}
|
||||
|
||||
func (e *widerSchemaError) Error() string {
|
||||
return fmt.Sprintf("schema of %s is wider than the bin's writer schema", e.path)
|
||||
}
|
||||
|
||||
// evolvedFileConversion is how a file of schema source joins a merge written
|
||||
// in target: nil when they are equal, a conversion when target covers it, a
|
||||
// *widerSchemaError when it covers target, else the merge's mismatch error.
|
||||
func evolvedFileConversion(target, source *parquet.Schema, path string) (parquet.Conversion, error) {
|
||||
if schemasEqual(target, source) {
|
||||
return nil, nil
|
||||
}
|
||||
if schemaCovers(target, source) {
|
||||
conv, err := parquet.Convert(target, source)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("schema of %s: %w", path, err)
|
||||
}
|
||||
return conv, nil
|
||||
}
|
||||
if schemaCovers(source, target) {
|
||||
return nil, &widerSchemaError{schema: source, path: path}
|
||||
}
|
||||
return nil, fmt.Errorf("schema mismatch in %s: cannot merge files with different schemas", path)
|
||||
}
|
||||
@@ -57,6 +57,7 @@ func TestOrphanCleanupKeepsStatisticsFiles(t *testing.T) {
|
||||
filer.PutFile(metaDir, "stats-1.puffin", old)
|
||||
filer.PutFile(metaDir, "partition-stats-1.parquet", old)
|
||||
filer.PutFile(metaDir, "stats-0.puffin", old) // superseded: a real orphan
|
||||
filer.PutFile(metaDir, "version-hint.text", old)
|
||||
|
||||
candidates, err := collectOrphanCandidates(context.Background(), filer.Client, bucket, path.Join(namespace, tbl),
|
||||
meta, "v1.metadata.json", 1)
|
||||
@@ -70,7 +71,7 @@ func TestOrphanCleanupKeepsStatisticsFiles(t *testing.T) {
|
||||
if !doomed["stats-0.puffin"] {
|
||||
t.Fatalf("expected the unreferenced stats-0.puffin to be an orphan, got %v", doomed)
|
||||
}
|
||||
for _, name := range []string{"stats-1.puffin", "partition-stats-1.parquet", "v1.metadata.json"} {
|
||||
for _, name := range []string{"stats-1.puffin", "partition-stats-1.parquet", "v1.metadata.json", "version-hint.text"} {
|
||||
if doomed[name] {
|
||||
t.Errorf("%s is referenced by the table metadata and must not be an orphan", name)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user