From 64a64ca75bd1fc98976a63e69ecab6215d05903b Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Sun, 22 Nov 2026 16:02:01 -0800 Subject: [PATCH] volume, seaweed-volume: an EC shard copy can require a disk type (#12901) * volume_server.proto: let an EC shard copy name the target disk type Co-Authored-By: Claude Opus 5.5 * volume: an EC shard copy that names a disk type lands only on that medium With disk_id 0 the copy auto-selects a disk, and the disk that already holds the volume or its index wins regardless of medium. A move onto an empty disk of another medium therefore landed beside the existing copy. Co-Authored-By: Claude Opus 5.5 * ec: EC shard moves pass the target disk type to the copy ec.balance and the ec_balance worker plan a move onto disks of one type, but the copy only named a disk id, and the master reports 0 (auto-select) for a disk that holds nothing yet. Co-Authored-By: Claude Opus 5.5 * seaweed-volume: an EC shard copy that names a disk type lands only on that medium Co-Authored-By: Claude Opus 5.5 * volume: an EC blob delete records on every local copy of the volume A volume mounted on several disks of one server has one runtime per disk, each with its own deletion set, and a shard read checks the runtime of the disk holding the shard. The delete stopped at the first runtime, so a read of a shard on another disk still returned the deleted needle. Co-Authored-By: Claude Opus 5.5 * seaweed-volume: an EC blob delete records on every local copy of the volume Mirrors the Go handler: each disk's runtime of the volume keeps its own deletion set, so the delete is journaled on every runtime, not the first. Co-Authored-By: Claude Opus 5.5 * volume: a typed EC shard copy yields to the shard's file on another medium The mount walks disks in order and loads the first file of the shard it finds, so a copy placed on the requested medium while another disk still holds an unmounted file of that shard could leave the old file mounted. Co-Authored-By: Claude Opus 5.5 * seaweed-volume: a typed EC shard copy yields to the shard's file on another medium Mirrors the Go selector. Co-Authored-By: Claude Opus 5.5 * ec: a typed shard move refused by its pinned disk lets the server pick Balancers pin the destination disk from the medium its mounted shards report, which can differ from the disk's own medium after encoding spilled onto another one. The server refuses such a disk before copying anything, so the move now retries once with the server picking a disk of the type. Co-Authored-By: Claude Opus 5.5 * seaweed-volume: name the requested disk type in a pinned-disk refusal Same wording as the Go server, which movers match to retry with a server-picked disk. Co-Authored-By: Claude Opus 5.5 * volume: an EC blob delete records on the first local copy last A retry on this server resolves the volume through its first copy, so a delete that fails on another copy left the first one tombstoned and the retry stopped there. Locate the needle on every copy first, then journal the others before the first. Co-Authored-By: Claude Opus 5.5 * seaweed-volume: an EC blob delete records on the first local copy last Mirrors the Go handler: a retry on this server resolves the volume through its first runtime, so that runtime journals after the others and a failure on any other leaves it live for the retry. Co-Authored-By: Claude Opus 5.5 * seaweed-volume: a local EC delete records on every local copy When this server holds the shard, the distributed delete journals locally instead of calling VolumeEcBlobDelete on itself, and that path journaled only the first runtime. Record on every runtime, the first last, as the handler does. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- seaweed-volume/proto/volume_server.proto | 1 + seaweed-volume/src/server/grpc_server.rs | 219 ++++++++++++++++-- seaweed-volume/src/server/store_ec.rs | 46 ++-- .../src/storage/erasure_coding/ec_volume.rs | 6 + seaweed-volume/src/storage/store.rs | 97 ++++++-- weed/ec/ec_common.go | 15 +- weed/operation/volume_move/ec_move.go | 21 +- weed/operation/volume_move/ec_move_test.go | 41 +++- .../operation/volume_move/fake_client_test.go | 6 + .../operation/volume_move/volume_move_test.go | 2 +- weed/pb/volume_server.proto | 1 + weed/pb/volume_server_pb/volume_server.pb.go | 13 +- weed/server/volume_grpc_copy.go | 2 +- weed/server/volume_grpc_erasure_coding.go | 54 +++-- ...me_grpc_erasure_coding_blob_delete_test.go | 89 +++++++ ...grpc_erasure_coding_copy_disk_type_test.go | 97 ++++++++ weed/storage/store_ec.go | 27 ++- weed/storage/store_ec_target_location_test.go | 53 ++++- .../tasks/ec_balance/ec_balance_task.go | 13 +- .../tasks/ec_balance/ec_balance_task_test.go | 9 +- .../ec_balance/fake_ec_volume_server_test.go | 6 +- 21 files changed, 705 insertions(+), 113 deletions(-) create mode 100644 weed/server/volume_grpc_erasure_coding_blob_delete_test.go create mode 100644 weed/server/volume_grpc_erasure_coding_copy_disk_type_test.go diff --git a/seaweed-volume/proto/volume_server.proto b/seaweed-volume/proto/volume_server.proto index 2faea41a85..52f9655dbe 100644 --- a/seaweed-volume/proto/volume_server.proto +++ b/seaweed-volume/proto/volume_server.proto @@ -482,6 +482,7 @@ message VolumeEcShardsCopyRequest { bool copy_vif_file = 7; uint32 disk_id = 8; // Target disk ID for storing EC shards bool copy_ecsum_file = 9; // copy the bitrot checksum sidecar (.ecsum) when present; tolerant of a missing source (no-op), since this non-2PC path has no Prepare backstop + string disk_type = 11; // with disk_id 0, pick only among disks of this type; empty means any } message VolumeEcShardsCopyResponse { } diff --git a/seaweed-volume/src/server/grpc_server.rs b/seaweed-volume/src/server/grpc_server.rs index 0af0f56c6a..b5eb4b4ff7 100644 --- a/seaweed-volume/src/server/grpc_server.rs +++ b/seaweed-volume/src/server/grpc_server.rs @@ -2708,6 +2708,7 @@ impl VolumeServer for VolumeGrpcService { &info.collection, vid, data_shards, + "", &[], ) .map(|i| store.locations[i].directory.clone()) @@ -4356,37 +4357,40 @@ impl VolumeServer for VolumeGrpcService { // stalls deletes of this volume, not every store reader. The decode // tail is checked under that journal lock (see journal_delete_local). loop { - let appender = { + let appenders = { let store = self.state.store.read().unwrap(); - // Go's handler locates the needle first: absent fails the RPC - // so the caller moves to the next holder; an existing - // tombstone is a no-op. - let Some(ec_vol) = store.find_ec_volume(vid) else { - // If EC volume not mounted, it's a no-op (matching Go behavior) - return Ok(Response::new( - volume_server_pb::VolumeEcBlobDeleteResponse {}, - )); - }; - match ec_vol.find_needle_from_ecx(needle_id) { - Ok(Some((_, size))) if size.is_deleted() => { - return Ok(Response::new( - volume_server_pb::VolumeEcBlobDeleteResponse {}, - )); + // Each disk holding shards of the volume mounts its own runtime + // with its own deletion set, and a shard read checks the runtime + // of the disk that holds the shard, so every runtime records the + // delete. Go's handler locates the needle first: absent from the + // first runtime fails the RPC so the caller moves to the next + // holder; an existing tombstone is a no-op. An unmounted volume + // is a no-op too. A retry on this server resolves the volume + // through the first runtime, so it records last: a failure on + // any other leaves it live and the retry fans out again. + let mut appenders = Vec::new(); + for (i, ec_vol) in store.find_all_ec_volumes(vid).into_iter().enumerate() { + match ec_vol.find_needle_from_ecx(needle_id) { + Ok(Some((_, size))) if size.is_deleted() => continue, + Ok(None) if i > 0 => continue, + Ok(None) => { + return Err(Status::not_found(format!( + "needle {} not in ec volume {}", + needle_id, req.volume_id + ))); + } + Ok(Some(_)) => {} + Err(e) => return Err(Status::internal(e.to_string())), } - Ok(None) => { - return Err(Status::not_found(format!( - "needle {} not in ec volume {}", - needle_id, req.volume_id - ))); - } - Ok(Some(_)) => {} - Err(e) => return Err(Status::internal(e.to_string())), + appenders.push(ec_vol.journal_appender()); } - ec_vol.journal_appender() + appenders }; let state = self.state.clone(); let committed = tokio::task::spawn_blocking(move || { - appender.journal_delete(needle_id, || ec_decode_tail_contains(&state, vid)) + appenders.iter().rev().try_for_each(|appender| { + appender.journal_delete(needle_id, || ec_decode_tail_contains(&state, vid)) + }) }) .await .map_err(|e| Status::internal(e.to_string()))?; @@ -6300,6 +6304,16 @@ impl VolumeGrpcService { ))); } let loc = &store.locations[req.disk_id as usize]; + if !req.disk_type.is_empty() + && loc.disk_type != DiskType::from_string(&req.disk_type) + { + return Err(Status::invalid_argument(format!( + "disk {} is {}, not the requested disk type {}", + req.disk_id, + loc.disk_type.readable_string(), + req.disk_type + ))); + } (loc.directory.clone(), loc.idx_directory.clone()) } else { // A batch whose requested shards are already owned by @@ -6323,12 +6337,19 @@ impl VolumeGrpcService { &req.collection, vid, data_shards, + &req.disk_type, &shard_ids, ) { Some(i) => { let loc = &store.locations[i]; (loc.directory.clone(), loc.idx_directory.clone()) } + None if !req.disk_type.is_empty() => { + return Err(Status::resource_exhausted(format!( + "no space left on a {} disk, or a disk of another type holds the shards", + req.disk_type + ))); + } None => { return Err(Status::internal("no space left".to_string())); } @@ -10405,6 +10426,79 @@ mod tests { assert_eq!(std::fs::read(format!("{}/57.ec05", dir)).unwrap(), ec05); } + // A copy naming a disk type must land on that medium even when the volume's + // index already sits on another disk of the server, which auto-select prefers. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn test_ec_shards_copy_disk_type_picks_that_medium() { + let (source_service, source_tmp) = make_local_service_with_volume("", None); + let src = source_tmp.path().to_str().unwrap().to_string(); + let ecx = vec![1u8; NEEDLE_MAP_ENTRY_SIZE as usize]; + for vid in 61..=63 { + std::fs::write(format!("{}/{}.ecx", src, vid), &ecx).unwrap(); + std::fs::write(format!("{}/{}.ec02", src, vid), vec![2u8; 4096]).unwrap(); + } + let (port, _shutdown) = serve_source(source_service).await; + + let (dest, _dest_tmp, hdd_dir) = ec_copy_destination().await; + let ht_tmp = TempDir::new().unwrap(); + let ht_dir = ht_tmp.path().to_str().unwrap().to_string(); + { + let mut store = dest.state.store.write().unwrap(); + store + .add_location( + &ht_dir, + &ht_dir, + 100, + DiskType::from_string("hdd_ht"), + MinFreeSpace::Percent(0.0), + Vec::new(), + ) + .unwrap(); + for loc in &store.locations { + loc.check_disk_space(); + } + } + for vid in 61..=63 { + std::fs::write(format!("{}/{}.ecx", hdd_dir, vid), &ecx).unwrap(); + } + let copy = |vid: u32, disk_id: u32, disk_type: &str| { + dest.volume_ec_shards_copy(Request::new(volume_server_pb::VolumeEcShardsCopyRequest { + volume_id: vid, + shard_ids: vec![2], + copy_ecx_file: true, + source_data_node: format!("127.0.0.1:1.{}", port), + disk_id, + disk_type: disk_type.to_string(), + ..Default::default() + })) + }; + let landed = + |dir: &str, vid: u32| std::path::Path::new(&format!("{}/{}.ec02", dir, vid)).exists(); + + copy(61, 0, "").await.expect("copy without a disk type"); + assert!( + landed(&hdd_dir, 61), + "without a disk type the shard should follow the index" + ); + + copy(62, 0, "hdd_ht").await.expect("copy to hdd_ht"); + assert!( + landed(&ht_dir, 62) && !landed(&hdd_dir, 62), + "a hdd_ht copy landed off the hdd_ht disk" + ); + + let err = copy(63, 1, "ssd").await.expect_err("disk 1 is hdd_ht"); + assert_eq!(err.code(), tonic::Code::InvalidArgument, "{}", err); + // Movers match this wording to let the server pick a disk of the type. + assert!( + err.message().contains("not the requested disk type"), + "{}", + err + ); + let err = copy(63, 0, "ssd").await.expect_err("no ssd disk"); + assert_eq!(err.code(), tonic::Code::ResourceExhausted, "{}", err); + } + // A copy failing after some shards landed removes exactly those shards and // keeps the ones the destination held before the call, its index included. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] @@ -15793,6 +15887,81 @@ mod tests { ); } + // A volume mounted on two disks keeps a deletion set per disk, and a read + // checks the set of the disk holding the shard, so a delete must reach + // every local copy. + #[tokio::test] + async fn test_volume_ec_blob_delete_records_on_every_local_copy() { + let (service, _tmp) = make_service_with_two_disk_complete_ec_volume(7064); + let vid = VolumeId(7064); + let store = service.state.store.read().unwrap(); + assert_eq!(store.find_all_ec_volumes(vid).len(), 2); + drop(store); + service + .volume_ec_blob_delete(Request::new(volume_server_pb::VolumeEcBlobDeleteRequest { + volume_id: 7064, + collection: String::new(), + file_key: 3, + version: 3, + })) + .await + .unwrap(); + let store = service.state.store.read().unwrap(); + for (i, ec_vol) in store.find_all_ec_volumes(vid).into_iter().enumerate() { + assert!( + ec_vol.is_needle_deleted(NeedleId(3)), + "copy {} still serves the deleted needle", + i + ); + } + } + + // A retry on this server resolves the volume through its first copy, so a + // delete that fails on another copy must leave the first one live. + #[tokio::test] + async fn test_volume_ec_blob_delete_failed_copy_leaves_first_live() { + let (service, _tmp) = make_service_with_two_disk_complete_ec_volume(7065); + let vid = VolumeId(7065); + let store = service.state.store.read().unwrap(); + let copies = store.find_all_ec_volumes(vid); + assert_eq!(copies.len(), 2); + copies[1].journal_appender().drop_journal_file(); + drop(store); + service + .volume_ec_blob_delete(Request::new(volume_server_pb::VolumeEcBlobDeleteRequest { + volume_id: 7065, + collection: String::new(), + file_key: 3, + version: 3, + })) + .await + .unwrap_err(); + let store = service.state.store.read().unwrap(); + assert!( + !store.find_all_ec_volumes(vid)[0].is_needle_deleted(NeedleId(3)), + "the first copy recorded a delete another copy failed" + ); + } + + // The distributed delete journals on this server without the RPC when it + // holds the shard, so it too must reach every local copy. + #[tokio::test] + async fn test_local_ec_delete_records_on_every_local_copy() { + let (service, _tmp) = make_service_with_two_disk_complete_ec_volume(7066); + let vid = VolumeId(7066); + crate::server::store_ec::journal_delete_local(&service.state, vid, NeedleId(3)) + .await + .unwrap(); + let store = service.state.store.read().unwrap(); + for (i, ec_vol) in store.find_all_ec_volumes(vid).into_iter().enumerate() { + assert!( + ec_vol.is_needle_deleted(NeedleId(3)), + "copy {} still serves the deleted needle", + i + ); + } + } + #[tokio::test] async fn volume_delete_reports_absent_volume_as_not_found() { let (service, _tmp) = make_service_with_seed_masters(&[]); diff --git a/seaweed-volume/src/server/store_ec.rs b/seaweed-volume/src/server/store_ec.rs index db4bbb41bf..f0d8020a48 100644 --- a/seaweed-volume/src/server/store_ec.rs +++ b/seaweed-volume/src/server/store_ec.rs @@ -531,38 +531,48 @@ async fn delete_on_remote_ec_shard( /// no-op: `journal_delete` would accept it silently, but here it means the /// volume remounted as a different generation mid-delete and the tombstone /// should go to a replica that still has the needle. -async fn journal_delete_local( +pub(crate) async fn journal_delete_local( state: &Arc, vid: VolumeId, needle_id: NeedleId, ) -> io::Result<()> { - let appender = { + // Every local runtime records the delete, the first last, as in the + // VolumeEcBlobDelete handler. + let appenders = { let store = state.store.read().unwrap(); - let ecv = store.find_ec_volume(vid).ok_or_else(|| { - io::Error::new( + let ec_vols = store.find_all_ec_volumes(vid); + if ec_vols.is_empty() { + return Err(io::Error::new( io::ErrorKind::NotFound, format!("ec volume {} unmounted", vid.0), - ) - })?; - match ecv.find_needle_from_ecx(needle_id)? { - None => { - return Err(io::Error::new( - io::ErrorKind::NotFound, - format!("needle {} not in local ecx", needle_id), - )); - } - Some((_, size)) if size.is_deleted() => return Ok(()), - Some(_) => {} + )); } - ecv.journal_appender() + let mut appenders = Vec::new(); + for (i, ecv) in ec_vols.into_iter().enumerate() { + match ecv.find_needle_from_ecx(needle_id)? { + None if i > 0 => continue, + None => { + return Err(io::Error::new( + io::ErrorKind::NotFound, + format!("needle {} not in local ecx", needle_id), + )); + } + Some((_, size)) if size.is_deleted() => continue, + Some(_) => {} + } + appenders.push(ecv.journal_appender()); + } + appenders }; // Membership is read under the journal lock: a decode claims the // publishing tail before it takes that lock for its catch-up, so a check // taken earlier would be stale by commit time. let state = state.clone(); tokio::task::spawn_blocking(move || { - appender.journal_delete(needle_id, || { - crate::server::grpc_server::ec_decode_tail_contains(&state, vid) + appenders.iter().rev().try_for_each(|appender| { + appender.journal_delete(needle_id, || { + crate::server::grpc_server::ec_decode_tail_contains(&state, vid) + }) }) }) .await diff --git a/seaweed-volume/src/storage/erasure_coding/ec_volume.rs b/seaweed-volume/src/storage/erasure_coding/ec_volume.rs index 9c8448a3e7..09a2c41b27 100644 --- a/seaweed-volume/src/storage/erasure_coding/ec_volume.rs +++ b/seaweed-volume/src/storage/erasure_coding/ec_volume.rs @@ -325,6 +325,12 @@ impl EcJournalAppender { pub(crate) fn lock_journal(&self) -> MutexGuard<'_, EcJournal> { self.ecj.lock().unwrap() } + + /// Drops the journal file, so every later append fails. + #[cfg(test)] + pub(crate) fn drop_journal_file(&self) { + self.ecj.lock().unwrap().file = None; + } } /// The encode run a holder reports when its disks serve shards of more than diff --git a/seaweed-volume/src/storage/store.rs b/seaweed-volume/src/storage/store.rs index 0f9d1c648f..c9fb7b2865 100644 --- a/seaweed-volume/src/storage/store.rs +++ b/seaweed-volume/src/storage/store.rs @@ -478,6 +478,10 @@ impl Store { /// their index files across disks of the same node and lose them at /// startup. See seaweedfs/seaweedfs#9212. /// + /// A non-empty `required_disk_type` limits every step to disks of that + /// type, so a copy meant for one medium never lands beside the volume's + /// copy on another. + /// /// `data_shard_count` is taken as a parameter rather than read from /// `DATA_SHARDS_COUNT` so custom-ratio builds can swap the default /// without touching this helper. @@ -491,6 +495,7 @@ impl Store { collection: &str, vid: VolumeId, data_shard_count: u32, + required_disk_type: &str, shard_ids: &[ShardId], ) -> Option { const TIER_ANY_DISK: u8 = 1; @@ -499,14 +504,21 @@ impl Store { const TIER_MOUNTED: u8 = 4; const TIER_OWNS_SHARD: u8 = 5; + let required = + (!required_disk_type.is_empty()).then(|| DiskType::from_string(required_disk_type)); // (index, tier, owned shard count, free shard slots) let mut best: Option<(usize, u8, usize, i64)> = None; for (i, loc) in self.locations.iter().enumerate() { let owned = owned_ec_shard_count(loc, vid, shard_ids); - if loc.read_only_mount { - // A read-only owner still owns the shard: placing another - // copy on a writable sibling would register it on two disks. - if owned > 0 { + if loc.read_only_mount || required.as_ref().is_some_and(|t| loc.disk_type != *t) { + // An owner that cannot take the copy still owns the shard: + // placing another copy on a sibling would register it on two disks. + // A typed copy also yields to an unmounted file of the shard there, + // which a later mount would pick ahead of the copy. + if owned > 0 + || (required.is_some() + && has_ec_shard_file_on_disk(loc, collection, vid, shard_ids)) + { return None; } continue; @@ -2100,6 +2112,19 @@ fn ec_free_shard_count(loc: &DiskLocation, data_shard_count: u32) -> i64 { free } +/// Whether `loc` holds a file for one of `shard_ids` of `vid`, mounted or not. +fn has_ec_shard_file_on_disk( + loc: &DiskLocation, + collection: &str, + vid: VolumeId, + shard_ids: &[ShardId], +) -> bool { + let base = crate::storage::volume::volume_file_name(&loc.directory, collection, vid); + shard_ids + .iter() + .any(|shard_id| std::path::Path::new(&format!("{}.ec{:02}", base, shard_id)).exists()) +} + /// Reports how many of `shard_ids` this disk already claims for `vid`, per /// the in-memory registration the read path and heartbeats use. /// @@ -3934,7 +3959,7 @@ mod tests { let base = volume_file_name(&store.locations[2].idx_directory, collection, vid); std::fs::write(format!("{}.ecx", base), vec![0u8; 20]).unwrap(); - let got = store.find_ec_shard_target_location(collection, vid, 10, &[]); + let got = store.find_ec_shard_target_location(collection, vid, 10, "", &[]); assert_eq!( got, Some(2), @@ -4144,7 +4169,7 @@ mod tests { let base = volume_file_name(&store.locations[2].idx_directory, collection, vid); std::fs::write(format!("{}.ecx", base), vec![0u8; 20]).unwrap(); - let got = store.find_ec_shard_target_location(collection, vid, 10, &[]); + let got = store.find_ec_shard_target_location(collection, vid, 10, "", &[]); assert_eq!( got, Some(1), @@ -4158,7 +4183,7 @@ mod tests { #[test] fn test_find_ec_shard_target_location_falls_through_to_hdd_when_nothing_matches() { let (store, _tmp) = make_ec_target_test_store(2); - let got = store.find_ec_shard_target_location("grafana-loki", VolumeId(3333), 10, &[]); + let got = store.find_ec_shard_target_location("grafana-loki", VolumeId(3333), 10, "", &[]); assert!(got.is_some(), "expected an HDD fallback"); assert_eq!(store.locations[got.unwrap()].disk_type, DiskType::HardDrive); } @@ -4174,7 +4199,7 @@ mod tests { .max_volume_count .store(0, Ordering::Relaxed); - let got = store.find_ec_shard_target_location("grafana-loki", VolumeId(4444), 10, &[]); + let got = store.find_ec_shard_target_location("grafana-loki", VolumeId(4444), 10, "", &[]); assert_eq!( got, Some(0), @@ -4223,7 +4248,7 @@ mod tests { .mount_ec_shards(vid, collection, &[0], "") .unwrap(); - let got = store.find_ec_shard_target_location(collection, vid, 10, &[]); + let got = store.find_ec_shard_target_location(collection, vid, 10, "", &[]); assert_eq!( got, Some(1), @@ -4265,24 +4290,68 @@ mod tests { .unwrap(); assert_eq!( - store.find_ec_shard_target_location(collection, vid, 10, &[0]), + store.find_ec_shard_target_location(collection, vid, 10, "", &[0]), Some(0), "a copy of shard 0 left its owning disk", ); assert_eq!( - store.find_ec_shard_target_location(collection, vid, 10, &[2]), + store.find_ec_shard_target_location(collection, vid, 10, "", &[2]), Some(1), "a copy of shard 2 left its owning disk", ); // A shard no disk owns yet is placed by the unchanged waterfall: both // disks have it mounted, so the emptier one wins. assert_eq!( - store.find_ec_shard_target_location(collection, vid, 10, &[7]), + store.find_ec_shard_target_location(collection, vid, 10, "", &[7]), Some(1), "placement of an unclaimed shard changed", ); } + /// A copy that names a disk type skips the other medium even when that + /// disk has the EC volume mounted, and refuses rather than split a shard + /// another medium already owns. + #[test] + fn test_find_ec_shard_target_location_required_disk_type() { + let (mut store, _tmp) = make_ec_target_test_store(2); + store.locations[0].disk_type = DiskType::Ssd; + store.locations[1].disk_type = DiskType::from_string("hdd_ht"); + let collection = "grafana-loki"; + let vid = VolumeId(5555); + let base0 = volume_file_name(&store.locations[0].directory, collection, vid); + std::fs::write(format!("{}.ec00", base0), b"x").unwrap(); + std::fs::write(format!("{}.ec01", base0), b"x").unwrap(); + std::fs::write(format!("{}.ecx", base0), vec![0u8; 20]).unwrap(); + store.locations[0] + .mount_ec_shards(vid, collection, &[0, 1], "") + .unwrap(); + + assert_eq!( + store.find_ec_shard_target_location(collection, vid, 10, "", &[2]), + Some(0) + ); + assert_eq!( + store.find_ec_shard_target_location(collection, vid, 10, "hdd_ht", &[2]), + Some(1), + "a hdd_ht copy landed off the hdd_ht disk", + ); + assert_eq!( + store.find_ec_shard_target_location(collection, vid, 10, "hdd_ht", &[1]), + None, + "a shard the ssd disk owns must not get a second claim on hdd_ht", + ); + assert_eq!( + store.find_ec_shard_target_location(collection, vid, 10, "hdd", &[2]), + None + ); + std::fs::write(format!("{}.ec03", base0), b"x").unwrap(); + assert_eq!( + store.find_ec_shard_target_location(collection, vid, 10, "hdd_ht", &[3]), + None, + "an unmounted shard file on ssd would be mounted ahead of a hdd_ht copy", + ); + } + /// The second half of the invariant: a disk with no free shard slots /// still wins for a shard it already owns. Re-copying that shard /// overwrites bytes the disk is already accounted for, while routing to a @@ -4317,13 +4386,13 @@ mod tests { .unwrap(); assert_eq!( - store.find_ec_shard_target_location(collection, vid, 10, &[0]), + store.find_ec_shard_target_location(collection, vid, 10, "", &[0]), Some(0), "a copy of shard 0 left its owning disk when the disk was full", ); // A shard it does not own still respects the space filter. assert_eq!( - store.find_ec_shard_target_location(collection, vid, 10, &[7]), + store.find_ec_shard_target_location(collection, vid, 10, "", &[7]), Some(1), "an unclaimed shard should go to the disk with free slots", ); diff --git a/weed/ec/ec_common.go b/weed/ec/ec_common.go index 8c6c86a086..1226e217f1 100644 --- a/weed/ec/ec_common.go +++ b/weed/ec/ec_common.go @@ -312,7 +312,7 @@ func OneServerCopyAndMountEcShardsFromSource(grpcDialOption grpc.DialOption, fmt.Printf("allocate %d.%v %s => %s\n", volumeId, shardIdsToCopy, existingLocation, targetServer.Info.Id) targetAddress := pb.NewServerAddressFromDataNode(targetServer.Info) - err = volume_move.NewMover(grpcDialOption).CopyAndMountEcShards(context.Background(), volumeId, collection, shardIdsToCopy, existingLocation, targetAddress, destDiskId, 0, os.Stdout) + err = volume_move.NewMover(grpcDialOption).CopyAndMountEcShards(context.Background(), volumeId, collection, shardIdsToCopy, existingLocation, targetAddress, destDiskId, "", 0, os.Stdout) if err != nil { return } @@ -1440,12 +1440,13 @@ func (ecb *ecBalancer) applyShardMoveRPC(src, dst *EcNode, collection string, vi return nil } return volume_move.NewMover(ecb.env.GrpcDialOption).MoveEcShards(context.Background(), volume_move.EcShardMove{ - VolumeId: vid, - Collection: collection, - ShardIds: []erasure_coding.ShardId{shardId}, - Source: srcAddr, - Target: dstAddr, - TargetDisk: destDiskId, + VolumeId: vid, + Collection: collection, + ShardIds: []erasure_coding.ShardId{shardId}, + Source: srcAddr, + Target: dstAddr, + TargetDisk: destDiskId, + TargetDiskType: ecb.diskType.String(), }, volume_move.EcMoveOptions{IoBytePerSecond: ecb.ioBytePerSecond, Writer: os.Stdout}) } diff --git a/weed/operation/volume_move/ec_move.go b/weed/operation/volume_move/ec_move.go index 7ad0d11975..7c82bda10a 100644 --- a/weed/operation/volume_move/ec_move.go +++ b/weed/operation/volume_move/ec_move.go @@ -21,6 +21,8 @@ type EcShardMove struct { Target pb.ServerAddress // TargetDisk picks the destination disk (0 lets the server pick). TargetDisk uint32 + // TargetDiskType limits the server's pick to disks of this type. + TargetDiskType string } // EcMoveOptions control MoveEcShards. @@ -58,7 +60,15 @@ func (m *Mover) MoveEcShards(ctx context.Context, move EcShardMove, opts EcMoveO } progress(10, fmt.Sprintf("copying EC shard(s) %d.%v from %s to %s", move.VolumeId, move.ShardIds, move.Source, move.Target)) - if err := m.CopyAndMountEcShards(ctx, move.VolumeId, move.Collection, move.ShardIds, move.Source, move.Target, move.TargetDisk, opts.IoBytePerSecond, writer); err != nil { + err := m.CopyAndMountEcShards(ctx, move.VolumeId, move.Collection, move.ShardIds, move.Source, move.Target, move.TargetDisk, move.TargetDiskType, opts.IoBytePerSecond, writer) + // A disk pinned from the medium its shards report can be another physical + // medium; the server refuses it before copying, so let it pick a disk of + // the requested type instead. + if err != nil && move.TargetDisk > 0 && IsDiskTypeMismatchError(err) { + fmt.Fprintf(writer, "%s disk %d is not %s, letting the server pick\n", move.Target, move.TargetDisk, move.TargetDiskType) + err = m.CopyAndMountEcShards(ctx, move.VolumeId, move.Collection, move.ShardIds, move.Source, move.Target, 0, move.TargetDiskType, opts.IoBytePerSecond, writer) + } + if err != nil { return err } @@ -87,7 +97,7 @@ func (m *Mover) MoveEcShards(ctx context.Context, move EcShardMove, opts EcMoveO // .vif/.ecsum sidecars) from source and mount them. A same-address call skips // the copy and just mounts — ec.encode uses that to bring freshly generated // shards online in place. -func (m *Mover) CopyAndMountEcShards(ctx context.Context, volumeId needle.VolumeId, collection string, shardIds []erasure_coding.ShardId, source, target pb.ServerAddress, targetDisk uint32, ioBytePerSecond int64, writer io.Writer) error { +func (m *Mover) CopyAndMountEcShards(ctx context.Context, volumeId needle.VolumeId, collection string, shardIds []erasure_coding.ShardId, source, target pb.ServerAddress, targetDisk uint32, targetDiskType string, ioBytePerSecond int64, writer io.Writer) error { if writer == nil { writer = io.Discard } @@ -111,6 +121,7 @@ func (m *Mover) CopyAndMountEcShards(ctx context.Context, volumeId needle.Volume CopyEcsumFile: true, // propagate the bitrot sidecar with the shards (no-op if the source has none) SourceDataNode: string(source), DiskId: targetDisk, + DiskType: targetDiskType, IoBytePerSecond: ioBytePerSecond, }) if copyErr != nil { @@ -211,6 +222,12 @@ func IsNoSpaceLeftError(err error) bool { return err != nil && strings.Contains(err.Error(), "no space left") } +// IsDiskTypeMismatchError matches the volume server's refusal of a pinned disk +// that is not the requested disk type. +func IsDiskTypeMismatchError(err error) bool { + return err != nil && strings.Contains(err.Error(), "not the requested disk type") +} + // RemoveEcShards unmounts then deletes shards in place — the dedup path for a // shard that already has a copy elsewhere. func (m *Mover) RemoveEcShards(ctx context.Context, volumeId needle.VolumeId, collection string, server pb.ServerAddress, shardIds []erasure_coding.ShardId) error { diff --git a/weed/operation/volume_move/ec_move_test.go b/weed/operation/volume_move/ec_move_test.go index 2e4756ff62..7cea5bbd58 100644 --- a/weed/operation/volume_move/ec_move_test.go +++ b/weed/operation/volume_move/ec_move_test.go @@ -5,6 +5,9 @@ import ( "strings" "testing" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb" "github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding" @@ -55,6 +58,42 @@ func TestMoveEcShardsSequence(t *testing.T) { } } +// A pinned disk can be another medium than the shards it holds report, so a +// typed move refused there lets the server pick a disk of that type. +func TestMoveEcShardsWrongTypePinnedDiskLetsServerPick(t *testing.T) { + cluster := newFakeCluster() + cluster.ecShards[string(dstAddr)] = dstShards(3) + cluster.wrongTypeDisk = map[string]uint32{string(dstAddr): 2} + move := ecMove(3) + move.TargetDiskType = "ssd" + + if err := cluster.mover().MoveEcShards(context.Background(), move, EcMoveOptions{}); err != nil { + t.Fatalf("MoveEcShards: %v", err) + } + if len(cluster.ecCopyReqs) != 2 { + t.Fatalf("want the refused copy and one retry, got %d copies", len(cluster.ecCopyReqs)) + } + if retry := cluster.ecCopyReqs[1]; retry.DiskId != 0 || retry.DiskType != "ssd" { + t.Errorf("retry should let the server pick an ssd disk: %+v", retry) + } + + // An untyped refusal is not a type mismatch and is not retried. + cluster = newFakeCluster() + cluster.errs[string(dstAddr)+" VolumeEcShardsCopy"] = status.Error(codes.InvalidArgument, "invalid disk_id 2") + if err := cluster.mover().MoveEcShards(context.Background(), ecMove(3), EcMoveOptions{}); err == nil { + t.Fatal("expected the copy refusal") + } + copies := 0 + for _, call := range cluster.callList() { + if call == string(dstAddr)+" VolumeEcShardsCopy" { + copies++ + } + } + if copies != 1 { + t.Errorf("an untyped refusal was retried: %v", cluster.callList()) + } +} + func TestMoveEcShardsVerifyFailureKeepsSource(t *testing.T) { cluster := newFakeCluster() cluster.ecShards[string(dstAddr)] = dstShards(3) // shard 4 didn't register @@ -126,7 +165,7 @@ func TestRemoveEcShards(t *testing.T) { func TestCopyAndMountEcShardsSameAddressMountsOnly(t *testing.T) { cluster := newFakeCluster() - err := cluster.mover().CopyAndMountEcShards(context.Background(), 7, "c1", []erasure_coding.ShardId{3}, srcAddr, srcAddr, 0, 0, nil) + err := cluster.mover().CopyAndMountEcShards(context.Background(), 7, "c1", []erasure_coding.ShardId{3}, srcAddr, srcAddr, 0, "", 0, nil) if err != nil { t.Fatalf("CopyAndMountEcShards: %v", err) } diff --git a/weed/operation/volume_move/fake_client_test.go b/weed/operation/volume_move/fake_client_test.go index fceac21086..d0e15cd52b 100644 --- a/weed/operation/volume_move/fake_client_test.go +++ b/weed/operation/volume_move/fake_client_test.go @@ -44,6 +44,8 @@ type fakeCluster struct { readonlyReqs []*volume_server_pb.VolumeMarkReadonlyRequest deleteReqs []*volume_server_pb.VolumeDeleteRequest ecCopyReqs []*volume_server_pb.VolumeEcShardsCopyRequest + // wrongTypeDisk is a disk of each server that refuses typed EC copies. + wrongTypeDisk map[string]uint32 } func newFakeCluster() *fakeCluster { @@ -186,7 +188,11 @@ func (f *fakeClient) VolumeEcShardsCopy(ctx context.Context, req *volume_server_ } f.cluster.mu.Lock() f.cluster.ecCopyReqs = append(f.cluster.ecCopyReqs, req) + wrongType, hasWrongType := f.cluster.wrongTypeDisk[f.addr] f.cluster.mu.Unlock() + if hasWrongType && req.DiskType != "" && req.DiskId == wrongType { + return nil, status.Errorf(codes.InvalidArgument, "disk %d is hdd, not the requested disk type %s", req.DiskId, req.DiskType) + } return &volume_server_pb.VolumeEcShardsCopyResponse{}, nil } diff --git a/weed/operation/volume_move/volume_move_test.go b/weed/operation/volume_move/volume_move_test.go index b4285a277e..263ad81717 100644 --- a/weed/operation/volume_move/volume_move_test.go +++ b/weed/operation/volume_move/volume_move_test.go @@ -86,7 +86,7 @@ func TestEmbeddedSourceAddressValidated(t *testing.T) { return m.TailVolume(context.Background(), 7, bad, dstAddr, 0, time.Second) }, "CopyAndMountEcShards": func(m *Mover) error { - return m.CopyAndMountEcShards(context.Background(), 7, "c1", []erasure_coding.ShardId{3}, bad, dstAddr, 0, 0, nil) + return m.CopyAndMountEcShards(context.Background(), 7, "c1", []erasure_coding.ShardId{3}, bad, dstAddr, 0, "", 0, nil) }, "MoveEcShards": func(m *Mover) error { move := ecMove(3) diff --git a/weed/pb/volume_server.proto b/weed/pb/volume_server.proto index e56b324bc8..e8b082db88 100644 --- a/weed/pb/volume_server.proto +++ b/weed/pb/volume_server.proto @@ -483,6 +483,7 @@ message VolumeEcShardsCopyRequest { uint32 disk_id = 8; // Target disk ID for storing EC shards bool copy_ecsum_file = 9; // copy the bitrot checksum sidecar (.ecsum) when present; tolerant of a missing source (no-op), since this non-2PC path has no Prepare backstop int64 io_byte_per_second = 10; // limit the copy rate; 0 falls back to the server's maintenance rate + string disk_type = 11; // with disk_id 0, pick only among disks of this type; empty means any } message VolumeEcShardsCopyResponse { } diff --git a/weed/pb/volume_server_pb/volume_server.pb.go b/weed/pb/volume_server_pb/volume_server.pb.go index d3d485f009..38c049dd5e 100644 --- a/weed/pb/volume_server_pb/volume_server.pb.go +++ b/weed/pb/volume_server_pb/volume_server.pb.go @@ -3664,6 +3664,7 @@ type VolumeEcShardsCopyRequest struct { DiskId uint32 `protobuf:"varint,8,opt,name=disk_id,json=diskId,proto3" json:"disk_id,omitempty"` // Target disk ID for storing EC shards CopyEcsumFile bool `protobuf:"varint,9,opt,name=copy_ecsum_file,json=copyEcsumFile,proto3" json:"copy_ecsum_file,omitempty"` // copy the bitrot checksum sidecar (.ecsum) when present; tolerant of a missing source (no-op), since this non-2PC path has no Prepare backstop IoBytePerSecond int64 `protobuf:"varint,10,opt,name=io_byte_per_second,json=ioBytePerSecond,proto3" json:"io_byte_per_second,omitempty"` // limit the copy rate; 0 falls back to the server's maintenance rate + DiskType string `protobuf:"bytes,11,opt,name=disk_type,json=diskType,proto3" json:"disk_type,omitempty"` // with disk_id 0, pick only among disks of this type; empty means any unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -3768,6 +3769,13 @@ func (x *VolumeEcShardsCopyRequest) GetIoBytePerSecond() int64 { return 0 } +func (x *VolumeEcShardsCopyRequest) GetDiskType() string { + if x != nil { + return x.DiskType + } + return "" +} + type VolumeEcShardsCopyResponse struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields @@ -7589,7 +7597,7 @@ const file_volume_server_proto_rawDesc = "" + "collection\x122\n" + "\x15unsafe_ignore_sidecar\x18\x03 \x01(\bR\x13unsafeIgnoreSidecar\"K\n" + "\x1dVolumeEcShardsRebuildResponse\x12*\n" + - "\x11rebuilt_shard_ids\x18\x01 \x03(\rR\x0frebuiltShardIds\"\xf9\x02\n" + + "\x11rebuilt_shard_ids\x18\x01 \x03(\rR\x0frebuiltShardIds\"\x96\x03\n" + "\x19VolumeEcShardsCopyRequest\x12\x1b\n" + "\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x1e\n" + "\n" + @@ -7603,7 +7611,8 @@ const file_volume_server_proto_rawDesc = "" + "\adisk_id\x18\b \x01(\rR\x06diskId\x12&\n" + "\x0fcopy_ecsum_file\x18\t \x01(\bR\rcopyEcsumFile\x12+\n" + "\x12io_byte_per_second\x18\n" + - " \x01(\x03R\x0fioBytePerSecond\"\x1c\n" + + " \x01(\x03R\x0fioBytePerSecond\x12\x1b\n" + + "\tdisk_type\x18\v \x01(\tR\bdiskType\"\x1c\n" + "\x1aVolumeEcShardsCopyResponse\"\x81\x02\n" + "\x1bVolumeEcShardsDeleteRequest\x12\x1b\n" + "\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x1e\n" + diff --git a/weed/server/volume_grpc_copy.go b/weed/server/volume_grpc_copy.go index 7cd7ad3b39..421b04782e 100644 --- a/weed/server/volume_grpc_copy.go +++ b/weed/server/volume_grpc_copy.go @@ -1215,7 +1215,7 @@ func (vs *VolumeServer) ReceiveFile(stream volume_server_pb.VolumeServer_Receive // Pass the build's default data-shard count for the helper's // free-slot maths; it's a parameter so custom-ratio builds // (e.g. enterprise) can swap it without touching this file. - targetLocation = vs.store.FindEcShardTargetLocation(fileInfo.Collection, needle.VolumeId(fileInfo.VolumeId), erasure_coding.DataShardsCount) + targetLocation = vs.store.FindEcShardTargetLocation(fileInfo.Collection, needle.VolumeId(fileInfo.VolumeId), erasure_coding.DataShardsCount, "") } if targetLocation == nil { glog.Errorf("ReceiveFile: no storage location available") diff --git a/weed/server/volume_grpc_erasure_coding.go b/weed/server/volume_grpc_erasure_coding.go index 14bd0cd32a..b80c7dba3e 100644 --- a/weed/server/volume_grpc_erasure_coding.go +++ b/weed/server/volume_grpc_erasure_coding.go @@ -439,6 +439,9 @@ func (vs *VolumeServer) VolumeEcShardsCopy(ctx context.Context, req *volume_serv // Use the specific disk location location = vs.store.Locations[req.DiskId] + if req.DiskType != "" && location.DiskType != types.ToDiskType(req.DiskType) { + return nil, status.Errorf(codes.InvalidArgument, "disk %d is %s, not the requested disk type %s", req.DiskId, location.DiskType.ReadableString(), req.DiskType) + } glog.V(1).Infof("Using disk %d for EC shard copy: %s", req.DiskId, location.Directory) } else { // Auto-select the target disk: prefer a disk that already owns one @@ -467,8 +470,11 @@ func (vs *VolumeServer) VolumeEcShardsCopy(ctx context.Context, req *volume_serv } return nil, fmt.Errorf("volume %d shards %v are already owned by multiple local disks %v: no single destination; copy per shard or pass disk_id", req.VolumeId, req.ShardIds, dirs) } - location = vs.store.FindEcShardTargetLocation(req.Collection, needle.VolumeId(req.VolumeId), erasure_coding.DataShardsCount, shardIds...) + location = vs.store.FindEcShardTargetLocation(req.Collection, needle.VolumeId(req.VolumeId), erasure_coding.DataShardsCount, req.DiskType, shardIds...) if location == nil { + if req.DiskType != "" { + return nil, status.Errorf(codes.ResourceExhausted, "no space left on a %s disk, or a disk of another type holds the shards", req.DiskType) + } return nil, status.Error(codes.ResourceExhausted, "no space left") } } @@ -1394,29 +1400,41 @@ func (vs *VolumeServer) VolumeEcBlobDelete(ctx context.Context, req *volume_serv resp := &volume_server_pb.VolumeEcBlobDeleteResponse{} - for _, location := range vs.store.Locations { - if localEcVolume, found := location.FindEcVolume(needle.VolumeId(req.VolumeId)); found { - - _, size, _, err := localEcVolume.LocateEcShardNeedle(types.NeedleId(req.FileKey), needle.Version(req.Version)) - if err != nil { - return nil, fmt.Errorf("locate in local ec volume: %w", err) - } - if size.IsDeleted() { - return resp, nil - } - - err = localEcVolume.DeleteNeedleFromEcx(types.NeedleId(req.FileKey)) - if err != nil { - return nil, err - } - - break + // Each disk holding shards of the volume mounts its own runtime with its + // own deletion set, and a shard read checks the runtime of the disk that + // holds the shard, so every runtime records the delete. A retry on this + // server resolves the volume through the first runtime, so it records + // last: a failure on any other leaves it live and the retry fans out again. + var pending []*erasure_coding.EcVolume + for i, localEcVolume := range vs.store.FindAllEcVolumes(needle.VolumeId(req.VolumeId)) { + live, err := isLiveInLocalEcVolume(localEcVolume, req, i > 0) + if err != nil { + return nil, err + } + if live { + pending = append(pending, localEcVolume) + } + } + for i := len(pending) - 1; i >= 0; i-- { + if err := pending[i].DeleteNeedleFromEcx(types.NeedleId(req.FileKey)); err != nil { + return nil, err } } return resp, nil } +func isLiveInLocalEcVolume(localEcVolume *erasure_coding.EcVolume, req *volume_server_pb.VolumeEcBlobDeleteRequest, sibling bool) (bool, error) { + _, size, _, err := localEcVolume.LocateEcShardNeedle(types.NeedleId(req.FileKey), needle.Version(req.Version)) + if err != nil { + if sibling && errors.Is(err, erasure_coding.NotFoundError) { + return false, nil + } + return false, fmt.Errorf("locate in local ec volume: %w", err) + } + return !size.IsDeleted(), nil +} + // VolumeEcShardsToVolume generates the .idx, .dat files from .ecx, .ecj and .ec01 ~ .ec14 files func (vs *VolumeServer) VolumeEcShardsToVolume(ctx context.Context, req *volume_server_pb.VolumeEcShardsToVolumeRequest) (*volume_server_pb.VolumeEcShardsToVolumeResponse, error) { if err := vs.checkGrpcAdminAuth(ctx); err != nil { diff --git a/weed/server/volume_grpc_erasure_coding_blob_delete_test.go b/weed/server/volume_grpc_erasure_coding_blob_delete_test.go new file mode 100644 index 0000000000..c549437c01 --- /dev/null +++ b/weed/server/volume_grpc_erasure_coding_blob_delete_test.go @@ -0,0 +1,89 @@ +package weed_server + +import ( + "context" + "os" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb" + "github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding" + "github.com/seaweedfs/seaweedfs/weed/storage/needle" + "github.com/seaweedfs/seaweedfs/weed/storage/needle_map" + "github.com/seaweedfs/seaweedfs/weed/storage/types" +) + +// A volume mounted on two disks of one server keeps a deletion set per disk, +// and a read checks the set of the disk holding the shard, so a delete must +// reach every local copy. +func TestVolumeEcBlobDelete_RecordsOnEveryLocalCopy(t *testing.T) { + diskA, diskB := t.TempDir(), t.TempDir() + store := newMultiDiskEcScrubStore(t, diskA, diskB) + const ( + vid = needle.VolumeId(902) + collection = "split" + fileKey = types.NeedleId(5) + ) + entry := needle_map.ToBytes(fileKey, types.ToOffset(8), 100) + for i, dir := range []string{diskA, diskB} { + seedEcShardOnDisk(t, store, vid, collection, dir, i, 0, 10, 4, 0) + base := erasure_coding.EcShardFileName(collection, dir, int(vid)) + require.NoError(t, os.WriteFile(base+".ecx", entry, 0o644)) + require.NoError(t, os.WriteFile(base+erasure_coding.ToExt(i), make([]byte, 4096), 0o644)) + } + copies := store.FindAllEcVolumes(vid) + require.Len(t, copies, 2) + + vs := &VolumeServer{store: store} + _, err := vs.VolumeEcBlobDelete(context.Background(), &volume_server_pb.VolumeEcBlobDeleteRequest{ + VolumeId: uint32(vid), + Collection: collection, + FileKey: uint64(fileKey), + Version: uint32(needle.Version3), + }) + require.NoError(t, err) + for i, ev := range copies { + require.True(t, ev.IsNeedleDeleted(fileKey), "copy %d still serves the deleted needle", i) + } +} + +// A retry on this server resolves the volume through its first copy, so a +// delete that fails on another copy must leave the first one live. +func TestVolumeEcBlobDelete_FailedCopyLeavesFirstLive(t *testing.T) { + diskA, diskB := t.TempDir(), t.TempDir() + store := newMultiDiskEcScrubStore(t, diskA, diskB) + const ( + vid = needle.VolumeId(903) + collection = "split" + fileKey = types.NeedleId(5) + ) + entry := needle_map.ToBytes(fileKey, types.ToOffset(8), 100) + for i, dir := range []string{diskA, diskB} { + seedEcShardOnDisk(t, store, vid, collection, dir, i, 0, 10, 4, 0) + base := erasure_coding.EcShardFileName(collection, dir, int(vid)) + require.NoError(t, os.WriteFile(base+".ecx", entry, 0o644)) + require.NoError(t, os.WriteFile(base+erasure_coding.ToExt(i), make([]byte, 4096), 0o644)) + } + copies := store.FindAllEcVolumes(vid) + require.Len(t, copies, 2) + + // A directory in place of the journal makes the reopen fail and every + // later append on that copy error out. + broken := copies[1] + unlock := broken.LockDeletionJournal() + require.NoError(t, os.Remove(broken.FileName(".ecj"))) + require.NoError(t, os.Mkdir(broken.FileName(".ecj"), 0o755)) + require.Error(t, broken.ReopenDeletionJournal()) + unlock() + + vs := &VolumeServer{store: store} + _, err := vs.VolumeEcBlobDelete(context.Background(), &volume_server_pb.VolumeEcBlobDeleteRequest{ + VolumeId: uint32(vid), + Collection: collection, + FileKey: uint64(fileKey), + Version: uint32(needle.Version3), + }) + require.Error(t, err) + require.False(t, copies[0].IsNeedleDeleted(fileKey), "the first copy recorded a delete another copy failed") +} diff --git a/weed/server/volume_grpc_erasure_coding_copy_disk_type_test.go b/weed/server/volume_grpc_erasure_coding_copy_disk_type_test.go new file mode 100644 index 0000000000..a33cb16368 --- /dev/null +++ b/weed/server/volume_grpc_erasure_coding_copy_disk_type_test.go @@ -0,0 +1,97 @@ +package weed_server + +import ( + "bytes" + "context" + "os" + "path/filepath" + "testing" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + + "github.com/seaweedfs/seaweedfs/weed/operation/volume_move" + "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb" + "github.com/seaweedfs/seaweedfs/weed/stats" + "github.com/seaweedfs/seaweedfs/weed/storage" + "github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding" + "github.com/seaweedfs/seaweedfs/weed/storage/needle" + "github.com/seaweedfs/seaweedfs/weed/storage/types" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// A copy naming a disk type must land on that medium even when the volume's +// index already sits on another disk of the server, which auto-select prefers. +func TestVolumeEcShardsCopy_DiskTypePicksThatMedium(t *testing.T) { + const collection = "col" + srcDir := filepath.Join(t.TempDir(), "src") + source := startEcCopySource(t, srcDir) + + root := t.TempDir() + ssdDir, hddHtDir := filepath.Join(root, "ssd"), filepath.Join(root, "hdd_ht") + for _, d := range []string{ssdDir, hddHtDir} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + store := storage.NewStore(nil, "localhost", 8080, 18080, "http://localhost:8080", "store-id", + []string{ssdDir, hddHtDir}, []int32{100, 100}, []util.MinFreeSpace{{}, {}}, "", + storage.NeedleMapInMemory, []types.DiskType{types.SsdType, types.ToDiskType("hdd_ht")}, nil, 3, stats.DefaultDiskIOProbeConfig()) + t.Cleanup(store.Close) + receiver := &VolumeServer{ + store: store, + grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + AllowUntrustedRemoteEndpoints: true, + } + + seed := func(vid needle.VolumeId) { + ecx := make([]byte, types.NeedleMapEntrySize) + ecx[0] = 1 + srcBase := erasure_coding.EcShardFileName(collection, srcDir, int(vid)) + writeFile(t, srcBase+".ecx", ecx) + writeFile(t, srcBase+".ec02", bytes.Repeat([]byte{2}, 4096)) + writeFile(t, erasure_coding.EcShardFileName(collection, ssdDir, int(vid))+".ecx", ecx) + } + copyShard := func(vid needle.VolumeId, diskId uint32, diskType string) error { + _, err := receiver.VolumeEcShardsCopy(context.Background(), &volume_server_pb.VolumeEcShardsCopyRequest{ + VolumeId: uint32(vid), + Collection: collection, + ShardIds: []uint32{2}, + CopyEcxFile: true, + SourceDataNode: source, + DiskId: diskId, + DiskType: diskType, + }) + return err + } + landed := func(dir string, vid needle.VolumeId) bool { + _, err := os.Stat(erasure_coding.EcShardFileName(collection, dir, int(vid)) + ".ec02") + return err == nil + } + + seed(1) + if err := copyShard(1, 0, ""); err != nil { + t.Fatalf("copy without a disk type: %v", err) + } + if !landed(ssdDir, 1) { + t.Fatalf("without a disk type the shard should follow the index onto ssd") + } + + seed(2) + if err := copyShard(2, 0, "hdd_ht"); err != nil { + t.Fatalf("copy to hdd_ht: %v", err) + } + if !landed(hddHtDir, 2) || landed(ssdDir, 2) { + t.Fatalf("hdd_ht copy: on hdd_ht=%v, on ssd=%v; want only hdd_ht", landed(hddHtDir, 2), landed(ssdDir, 2)) + } + + seed(3) + if err := copyShard(3, 1, "ssd"); status.Code(err) != codes.InvalidArgument || !volume_move.IsDiskTypeMismatchError(err) { + t.Fatalf("disk 1 is hdd_ht, a copy naming ssd: err = %v, want an InvalidArgument disk type mismatch", err) + } + if err := copyShard(3, 0, "hdd"); status.Code(err) != codes.ResourceExhausted { + t.Fatalf("no hdd disk: err = %v, want ResourceExhausted", err) + } +} diff --git a/weed/storage/store_ec.go b/weed/storage/store_ec.go index fbbed214fe..f12af00555 100644 --- a/weed/storage/store_ec.go +++ b/weed/storage/store_ec.go @@ -63,6 +63,9 @@ var errShardNotLocal = errors.New("ec shard not on this server") // and lose them at startup. See issue #9212 and the orphan-shard // reconciliation in #9244. // +// A non-empty requiredDiskType limits every step to disks of that type, so a +// copy meant for one medium never lands beside the volume's copy on another. +// // dataShardCount is the data-shard count for this volume's EC layout (10 // for the OSS default, but custom ratios are supported via .vif). Callers // pass it explicitly so this helper stays free of package-level constants @@ -73,7 +76,7 @@ var errShardNotLocal = errors.New("ec shard not on this server") // across four FindFreeLocation passes was equivalent but acquired // volumesLock and ecVolumesLock RLocks (via VolumesLen / EcShardCount) up // to four times per disk per call. -func (s *Store) FindEcShardTargetLocation(collection string, vid needle.VolumeId, dataShardCount int, shardIds ...erasure_coding.ShardId) *DiskLocation { +func (s *Store) FindEcShardTargetLocation(collection string, vid needle.VolumeId, dataShardCount int, requiredDiskType string, shardIds ...erasure_coding.ShardId) *DiskLocation { const ( tierAnyDisk = iota + 1 tierHDD @@ -90,10 +93,12 @@ func (s *Store) FindEcShardTargetLocation(collection string, vid needle.VolumeId ) for _, loc := range s.Locations { owned := ownedEcShardCount(loc, vid, shardIds) - if loc.readOnlyMount { - // A read-only owner still owns the shard: placing another copy - // on a writable sibling would register it on two disks. - if owned > 0 { + if loc.readOnlyMount || (requiredDiskType != "" && loc.DiskType != types.ToDiskType(requiredDiskType)) { + // An owner that cannot take the copy still owns the shard: + // placing another copy on a sibling would register it on two disks. + // A typed copy also yields to an unmounted file of the shard there, + // which a later mount would pick ahead of the copy. + if owned > 0 || (requiredDiskType != "" && hasEcShardFileOnDisk(loc, collection, vid, shardIds)) { return nil } continue @@ -176,6 +181,18 @@ func ownedEcShardCount(loc *DiskLocation, vid needle.VolumeId, shardIds []erasur return owned } +// hasEcShardFileOnDisk reports whether loc holds a file for one of shardIds of +// vid, mounted or not. +func hasEcShardFileOnDisk(loc *DiskLocation, collection string, vid needle.VolumeId, shardIds []erasure_coding.ShardId) bool { + base := erasure_coding.EcShardFileName(collection, loc.Directory, int(vid)) + for _, shardId := range shardIds { + if _, err := os.Stat(base + erasure_coding.ToExt(int(shardId))); err == nil { + return true + } + } + return false +} + // ecFreeShardCount returns the free EC shard capacity of loc, expressed // in shard slots (not volume-equivalent slots). dataShardCount is the // data-shard count of the EC layout being placed — see diff --git a/weed/storage/store_ec_target_location_test.go b/weed/storage/store_ec_target_location_test.go index cf88d86709..92d8a876b5 100644 --- a/weed/storage/store_ec_target_location_test.go +++ b/weed/storage/store_ec_target_location_test.go @@ -41,7 +41,7 @@ func TestFindEcShardTargetLocation_PinsToEcxOnDisk(t *testing.T) { t.Fatalf("seed .ecx on disk 2: %v", err) } - got := store.FindEcShardTargetLocation(collection, vid, dataShardCount) + got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, "") if got == nil { t.Fatalf("FindEcShardTargetLocation returned nil; expected disk 2") } @@ -72,7 +72,7 @@ func TestFindEcShardTargetLocation_PrefersMountedOverEcx(t *testing.T) { t.Fatalf("seed .ecx on disk 2: %v", err) } - got := store.FindEcShardTargetLocation(collection, vid, dataShardCount) + got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, "") if got != loc1 { t.Errorf("placement should follow mounted EC volume on disk 1, got %v", got) } @@ -86,7 +86,7 @@ func TestFindEcShardTargetLocation_FallsThroughToHddWhenNothingMatches(t *testin collection := "grafana-loki" vid := needle.VolumeId(3333) - got := store.FindEcShardTargetLocation(collection, vid, dataShardCount) + got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, "") if got == nil { t.Fatalf("FindEcShardTargetLocation returned nil; expected an HDD fallback") } @@ -104,7 +104,7 @@ func TestFindEcShardTargetLocation_HonoursUnlimitedDisk(t *testing.T) { store := newEcTargetTestStore(t, 1) store.Locations[0].MaxVolumeCount = 0 // unlimited - got := store.FindEcShardTargetLocation("grafana-loki", needle.VolumeId(4444), dataShardCount) + got := store.FindEcShardTargetLocation("grafana-loki", needle.VolumeId(4444), dataShardCount, "") if got == nil { t.Fatalf("FindEcShardTargetLocation returned nil for an unlimited (MaxVolumeCount=0) disk") } @@ -142,7 +142,7 @@ func TestFindEcShardTargetLocation_TightProvisioningKeepsEcxDisk(t *testing.T) { } loc1.ecVolumesLock.Unlock() - got := store.FindEcShardTargetLocation(collection, vid, dataShardCount) + got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, "") if got != loc1 { t.Errorf("expected the .ecx-owning disk (1 shard placed, 9 free shard slots) to be picked; got %v", got) } @@ -168,16 +168,16 @@ func TestFindEcShardTargetLocation_PinsToTheDiskOwningTheShard(t *testing.T) { mountEcShards(store.Locations[0], collection, vid, 0, 1) mountEcShards(store.Locations[1], collection, vid, 2) - if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, 0); got != store.Locations[0] { + if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, "", 0); got != store.Locations[0] { t.Errorf("a copy of shard 0 left its owning disk: got %v, want %s", got, store.Locations[0].Directory) } - if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, 2); got != store.Locations[1] { + if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, "", 2); got != store.Locations[1] { t.Errorf("a copy of shard 2 left its owning disk: got %v, want %s", got, store.Locations[1].Directory) } // A shard no disk owns yet is placed by the unchanged waterfall: both // disks have it mounted, so the emptier one wins. - if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, 7); got != store.Locations[1] { + if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, "", 7); got != store.Locations[1] { t.Errorf("placement of an unclaimed shard changed: got %v, want the emptier mounted disk", got) } } @@ -202,11 +202,11 @@ func TestFindEcShardTargetLocation_OwningDiskWinsWhenFull(t *testing.T) { } mountEcShards(store.Locations[0], collection, filler, fillerShards...) - if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, 0); got != store.Locations[0] { + if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, "", 0); got != store.Locations[0] { t.Errorf("a copy of shard 0 left its owning disk when the disk was full: got %v", got) } // A shard it does not own still respects the space filter. - if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, 7); got != store.Locations[1] { + if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, "", 7); got != store.Locations[1] { t.Errorf("an unclaimed shard should go to the disk with free slots: got %v", got) } } @@ -294,3 +294,36 @@ func newEcTargetTestStore(t *testing.T, numDirs int) *Store { }) return store } + +// TestFindEcShardTargetLocation_RequiredDiskType pins the strict medium filter: +// a copy that names a disk type skips the other medium even when that disk has +// the EC volume mounted, and refuses rather than split a shard another medium +// already owns. +func TestFindEcShardTargetLocation_RequiredDiskType(t *testing.T) { + store := newEcTargetTestStore(t, 2) + store.Locations[0].DiskType = types.SsdType + store.Locations[1].DiskType = types.ToDiskType("hdd_ht") + collection := "grafana-loki" + vid := needle.VolumeId(5555) + mountEcShards(store.Locations[0], collection, vid, 0, 1) + + if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, "", 2); got != store.Locations[0] { + t.Errorf("without a disk type the mounted disk should win: got %v", got) + } + if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, "hdd_ht", 2); got != store.Locations[1] { + t.Errorf("a hdd_ht copy landed off the hdd_ht disk: got %v", got) + } + if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, "hdd_ht", 1); got != nil { + t.Errorf("a shard the ssd disk owns must not get a second claim on hdd_ht: got %s", got.Directory) + } + if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, "hdd", 2); got != nil { + t.Errorf("no hdd disk exists, want nil: got %s", got.Directory) + } + ssdBase := erasure_coding.EcShardFileName(collection, store.Locations[0].Directory, int(vid)) + if err := os.WriteFile(ssdBase+erasure_coding.ToExt(3), []byte("s"), 0o644); err != nil { + t.Fatal(err) + } + if got := store.FindEcShardTargetLocation(collection, vid, dataShardCount, "hdd_ht", 3); got != nil { + t.Errorf("an unmounted shard file on ssd would be mounted ahead of a hdd_ht copy: got %s", got.Directory) + } +} diff --git a/weed/worker/tasks/ec_balance/ec_balance_task.go b/weed/worker/tasks/ec_balance/ec_balance_task.go index 206c412a0a..276e16cd4e 100644 --- a/weed/worker/tasks/ec_balance/ec_balance_task.go +++ b/weed/worker/tasks/ec_balance/ec_balance_task.go @@ -117,12 +117,13 @@ func (t *ECBalanceTask) Execute(ctx context.Context, params *worker_pb.TaskParam } move := volume_move.EcShardMove{ - VolumeId: needle.VolumeId(params.VolumeId), - Collection: params.Collection, - ShardIds: shardIds, - Source: sourceAddr, - Target: targetAddr, - TargetDisk: target.DiskId, + VolumeId: needle.VolumeId(params.VolumeId), + Collection: params.Collection, + ShardIds: shardIds, + Source: sourceAddr, + Target: targetAddr, + TargetDisk: target.DiskId, + TargetDiskType: ecParams.GetDiskType(), } opts := volume_move.EcMoveOptions{ IoBytePerSecond: ecParams.GetIoBytePerSecond(), diff --git a/weed/worker/tasks/ec_balance/ec_balance_task_test.go b/weed/worker/tasks/ec_balance/ec_balance_task_test.go index 00caa33168..c9cb6a7904 100644 --- a/weed/worker/tasks/ec_balance/ec_balance_task_test.go +++ b/weed/worker/tasks/ec_balance/ec_balance_task_test.go @@ -29,7 +29,8 @@ func TestECBalanceTaskRejectsOutOfRangeShardIds(t *testing.T) { } // A refusal against the pinned disk convicts only that disk, not the node: -// the task retries once letting the server pick a disk, and the move completes. +// the task retries once letting the server pick a disk of the same type, and +// the move completes. func TestECBalanceTaskRetriesServerPickOnPinnedDiskRefusal(t *testing.T) { source := startFakeEcVolumeServer(t, 7, 5) target := startFakeEcVolumeServer(t, 7) @@ -41,6 +42,9 @@ func TestECBalanceTaskRetriesServerPickOnPinnedDiskRefusal(t *testing.T) { VolumeId: 7, Sources: []*worker_pb.TaskSource{{Node: source.address(), ShardIds: []uint32{5}}}, Targets: []*worker_pb.TaskTarget{{Node: target.address(), DiskId: 2, ShardIds: []uint32{5}}}, + TaskParams: &worker_pb.TaskParams_EcBalanceParams{ + EcBalanceParams: &worker_pb.EcBalanceTaskParams{DiskType: "ssd"}, + }, } if err := task.Execute(context.Background(), params); err != nil { @@ -49,6 +53,9 @@ func TestECBalanceTaskRetriesServerPickOnPinnedDiskRefusal(t *testing.T) { if got := target.copyDiskIds; len(got) != 2 || got[0] != 2 || got[1] != 0 { t.Fatalf("expected copies to disk 2 then server-picked 0, got %v", got) } + if got := target.copyDiskTypes; len(got) != 2 || got[0] != "ssd" || got[1] != "ssd" { + t.Fatalf("expected both copies to name disk type ssd, got %v", got) + } if source.has(7, 5) { t.Fatalf("source still holds shard 5") } diff --git a/weed/worker/tasks/ec_balance/fake_ec_volume_server_test.go b/weed/worker/tasks/ec_balance/fake_ec_volume_server_test.go index b3fddd887d..818bddf349 100644 --- a/weed/worker/tasks/ec_balance/fake_ec_volume_server_test.go +++ b/weed/worker/tasks/ec_balance/fake_ec_volume_server_test.go @@ -36,8 +36,9 @@ type fakeEcVolumeServer struct { // pinning that disk id with "no space left" — a full disk; a request with // DiskId 0 (server picks) still succeeds. refuseCopyOnDisk uint32 - // copyDiskIds records the DiskId each copy request carried. - copyDiskIds []uint32 + // copyDiskIds and copyDiskTypes record what each copy request carried. + copyDiskIds []uint32 + copyDiskTypes []string // grpcAddr is host:port; the code under test dials by address string. grpcAddr string stop func() @@ -64,6 +65,7 @@ func (f *fakeEcVolumeServer) VolumeEcShardsCopy(ctx context.Context, req *volume f.mu.Lock() defer f.mu.Unlock() f.copyDiskIds = append(f.copyDiskIds, req.DiskId) + f.copyDiskTypes = append(f.copyDiskTypes, req.DiskType) if f.refuseCopyOnDisk != 0 && req.DiskId == f.refuseCopyOnDisk { return nil, fmt.Errorf("disk %d: no space left", req.DiskId) }