mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a98c9e2718 | ||
|
|
1e98014713 | ||
|
|
23e8412e5c | ||
|
|
64a64ca75b | ||
|
|
15488c1af6 | ||
|
|
c967ba4a7a | ||
|
|
c46dea9b6a | ||
|
|
a2df801e6d | ||
|
|
907c46fe47 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.54"
|
||||
appVersion: "4.55"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.54.0
|
||||
version: 4.55.0
|
||||
+1019
-1020
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 53 KiB |
@@ -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 {
|
||||
}
|
||||
|
||||
@@ -1178,6 +1178,14 @@ impl VolumeServer for VolumeGrpcService {
|
||||
n.id,
|
||||
)
|
||||
.await;
|
||||
if matches!(read, Ok(Err(EcMiss::Deleted))) {
|
||||
crate::server::store_ec::forward_ec_delete_of_deleted_needle(
|
||||
&self.state,
|
||||
file_id.volume_id,
|
||||
n.id,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let error = match read {
|
||||
Ok(Ok(ec_needle)) => {
|
||||
n = ec_needle;
|
||||
@@ -2708,6 +2716,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&info.collection,
|
||||
vid,
|
||||
data_shards,
|
||||
"",
|
||||
&[],
|
||||
)
|
||||
.map(|i| store.locations[i].directory.clone())
|
||||
@@ -4356,37 +4365,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 +6312,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 +6345,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 +10434,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)]
|
||||
@@ -14027,17 +14129,13 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Leaves `service` holding `local_shards` of EC volume 1, with shard 0 (the
|
||||
/// one with needle 11's bytes) also served by a peer; `peer_deletes`
|
||||
/// journals the needle's delete on the peer alone.
|
||||
async fn put_ec_1_needle_shard_on_a_peer(
|
||||
service: &VolumeGrpcService,
|
||||
/// Serves `shard_ids` of the EC volume 1 generated in `tmp` from a new peer;
|
||||
/// `deletes` journals needle 11's delete on that peer alone.
|
||||
async fn serve_ec_1_shards_from_a_peer(
|
||||
tmp: &TempDir,
|
||||
local_shards: Vec<u32>,
|
||||
peer_deletes: bool,
|
||||
) -> (TempDir, tokio::sync::oneshot::Sender<()>) {
|
||||
generate_and_mount_ec_1(service, local_shards).await;
|
||||
|
||||
shard_ids: Vec<u32>,
|
||||
deletes: bool,
|
||||
) -> (String, TempDir, tokio::sync::oneshot::Sender<()>) {
|
||||
let (peer, peer_tmp) = make_local_service_with_volume("", None);
|
||||
peer.state
|
||||
.store
|
||||
@@ -14051,8 +14149,8 @@ mod tests {
|
||||
std::fs::copy(tmp.path().join(&name), peer_tmp.path().join(&name)).unwrap();
|
||||
}
|
||||
}
|
||||
mount_ec_1(&peer, vec![0]).await;
|
||||
if peer_deletes {
|
||||
mount_ec_1(&peer, shard_ids).await;
|
||||
if deletes {
|
||||
peer.state
|
||||
.store
|
||||
.write()
|
||||
@@ -14063,6 +14161,21 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
let (port, shutdown) = serve_source(peer).await;
|
||||
(format!("127.0.0.1:{port}.{port}"), peer_tmp, shutdown)
|
||||
}
|
||||
|
||||
/// Leaves `service` holding `local_shards` of EC volume 1, with shard 0 (the
|
||||
/// one with needle 11's bytes) also served by a peer; `peer_deletes`
|
||||
/// journals the needle's delete on the peer alone.
|
||||
async fn put_ec_1_needle_shard_on_a_peer(
|
||||
service: &VolumeGrpcService,
|
||||
tmp: &TempDir,
|
||||
local_shards: Vec<u32>,
|
||||
peer_deletes: bool,
|
||||
) -> (TempDir, tokio::sync::oneshot::Sender<()>) {
|
||||
generate_and_mount_ec_1(service, local_shards).await;
|
||||
let (peer_addr, peer_tmp, shutdown) =
|
||||
serve_ec_1_shards_from_a_peer(tmp, vec![0], peer_deletes).await;
|
||||
|
||||
{
|
||||
let mut store = service.state.store.write().unwrap();
|
||||
@@ -14074,7 +14187,7 @@ mod tests {
|
||||
(0u8..14)
|
||||
.map(|sid| {
|
||||
let addr = if sid == 0 {
|
||||
format!("127.0.0.1:{port}.{port}")
|
||||
peer_addr.clone()
|
||||
} else {
|
||||
"127.0.0.1:255.1".to_string()
|
||||
};
|
||||
@@ -14112,6 +14225,165 @@ mod tests {
|
||||
assert_eq!(err.message(), "already deleted");
|
||||
}
|
||||
|
||||
/// A complete lookup places shard 0 nowhere and every other shard on an
|
||||
/// unreachable holder.
|
||||
fn delist_ec_1_shard_0(service: &VolumeGrpcService) {
|
||||
service
|
||||
.state
|
||||
.store
|
||||
.read()
|
||||
.unwrap()
|
||||
.find_ec_volume(VolumeId(1))
|
||||
.unwrap()
|
||||
.merge_shard_locations(
|
||||
(0u8..14)
|
||||
.map(|sid| {
|
||||
let addrs = if sid == 0 {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec!["127.0.0.1:255.1".to_string()]
|
||||
};
|
||||
(sid, addrs)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
|
||||
/// The local shards could rebuild needle 11, but the delisted holder of
|
||||
/// shard 0 still answers and journaled its delete.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn test_ec_read_asks_a_delisted_holder_before_rebuilding() {
|
||||
let (service, tmp) = make_local_service_with_volume("", None);
|
||||
let _peer = put_ec_1_needle_shard_on_a_peer(&service, &tmp, (1..14).collect(), true).await;
|
||||
delist_ec_1_shard_0(&service);
|
||||
|
||||
let err = needle_status(&service, 11).await.unwrap_err();
|
||||
assert_eq!(err.message(), "already deleted", "{err}");
|
||||
}
|
||||
|
||||
/// Delisted holders of shard 0 answer live and deleted: the read must ask
|
||||
/// past the live one, since any of them may hold the delete.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn test_ec_read_asks_every_delisted_holder() {
|
||||
let (service, tmp) = make_local_service_with_volume("", None);
|
||||
generate_and_mount_ec_1(&service, (1..14).collect()).await;
|
||||
let (live, _live_tmp, _live_stop) =
|
||||
serve_ec_1_shards_from_a_peer(&tmp, vec![0], false).await;
|
||||
let (journaled, _journaled_tmp, _journaled_stop) =
|
||||
serve_ec_1_shards_from_a_peer(&tmp, vec![0], true).await;
|
||||
{
|
||||
let mut store = service.state.store.write().unwrap();
|
||||
store.unmount_volume(VolumeId(1)).unwrap();
|
||||
let ecv = store.find_ec_volume(VolumeId(1)).unwrap();
|
||||
ecv.merge_shard_locations(std::collections::HashMap::from([(
|
||||
0,
|
||||
vec![live, journaled],
|
||||
)]));
|
||||
ecv.merge_shard_locations(std::collections::HashMap::from([(0, Vec::new())]));
|
||||
}
|
||||
|
||||
let err = needle_status(&service, 11).await.unwrap_err();
|
||||
assert_eq!(err.message(), "already deleted", "{err}");
|
||||
}
|
||||
|
||||
/// A delisted holder that failed before another answered deleted is
|
||||
/// dropped all the same.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn test_ec_read_drops_a_failed_hint_before_a_deleted_answer() {
|
||||
let (service, tmp) = make_local_service_with_volume("", None);
|
||||
generate_and_mount_ec_1(&service, (1..14).collect()).await;
|
||||
let (journaled, _journaled_tmp, _journaled_stop) =
|
||||
serve_ec_1_shards_from_a_peer(&tmp, vec![0], true).await;
|
||||
{
|
||||
let mut store = service.state.store.write().unwrap();
|
||||
store.unmount_volume(VolumeId(1)).unwrap();
|
||||
let ecv = store.find_ec_volume(VolumeId(1)).unwrap();
|
||||
ecv.merge_shard_locations(std::collections::HashMap::from([(
|
||||
0,
|
||||
vec!["127.0.0.1:255.1".to_string(), journaled.clone()],
|
||||
)]));
|
||||
ecv.merge_shard_locations(std::collections::HashMap::from([(0, Vec::new())]));
|
||||
}
|
||||
|
||||
let err = needle_status(&service, 11).await.unwrap_err();
|
||||
assert_eq!(err.message(), "already deleted", "{err}");
|
||||
let store = service.state.store.read().unwrap();
|
||||
let hints = store
|
||||
.find_ec_volume(VolumeId(1))
|
||||
.unwrap()
|
||||
.shard_read_hints(0)
|
||||
.map(|(hints, _)| hints);
|
||||
assert_eq!(hints, Some(vec![journaled]));
|
||||
}
|
||||
|
||||
/// A delete made after the delisting went to a listed holder, so the
|
||||
/// delisted holder still answers live; the read must not take that answer
|
||||
/// over the reconstruction that asks the listed holder.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn test_ec_read_does_not_take_a_live_answer_from_a_delisted_holder() {
|
||||
let (service, tmp) = make_local_service_with_volume("", None);
|
||||
generate_and_mount_ec_1(&service, (1..10).collect()).await;
|
||||
let (delisted, _delisted_tmp, _delisted_stop) =
|
||||
serve_ec_1_shards_from_a_peer(&tmp, vec![0], false).await;
|
||||
let (journaled, _journaled_tmp, _journaled_stop) =
|
||||
serve_ec_1_shards_from_a_peer(&tmp, vec![10], true).await;
|
||||
{
|
||||
let mut store = service.state.store.write().unwrap();
|
||||
store.unmount_volume(VolumeId(1)).unwrap();
|
||||
let ecv = store.find_ec_volume(VolumeId(1)).unwrap();
|
||||
ecv.merge_shard_locations(std::collections::HashMap::from([(0, vec![delisted])]));
|
||||
ecv.merge_shard_locations(std::collections::HashMap::from([
|
||||
(0, Vec::new()),
|
||||
(10, vec![journaled]),
|
||||
]));
|
||||
}
|
||||
|
||||
let err = needle_status(&service, 11).await.unwrap_err();
|
||||
assert_eq!(err.message(), "already deleted", "{err}");
|
||||
let store = service.state.store.read().unwrap();
|
||||
assert!(
|
||||
store
|
||||
.find_ec_volume(VolumeId(1))
|
||||
.unwrap()
|
||||
.shard_read_hints(0)
|
||||
.is_some(),
|
||||
"a read hint that answered was dropped"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn test_ec_read_drops_an_unreachable_read_hint_and_rebuilds() {
|
||||
let (service, _tmp) = make_local_service_with_volume("", None);
|
||||
let want = needle_status(&service, 11).await.unwrap();
|
||||
generate_and_mount_ec_1(&service, (1..14).collect()).await;
|
||||
{
|
||||
let mut store = service.state.store.write().unwrap();
|
||||
store.unmount_volume(VolumeId(1)).unwrap();
|
||||
store
|
||||
.find_ec_volume(VolumeId(1))
|
||||
.unwrap()
|
||||
.merge_shard_locations(
|
||||
(0u8..14)
|
||||
.map(|sid| (sid, vec!["127.0.0.1:255.1".to_string()]))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
delist_ec_1_shard_0(&service);
|
||||
|
||||
let got = needle_status(&service, 11)
|
||||
.await
|
||||
.expect("the local shards rebuild shard 0");
|
||||
assert_eq!(got, want);
|
||||
let store = service.state.store.read().unwrap();
|
||||
assert_eq!(
|
||||
store
|
||||
.find_ec_volume(VolumeId(1))
|
||||
.unwrap()
|
||||
.shard_read_hints(0),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
fn quarantine_ec_1(service: &VolumeGrpcService) {
|
||||
service
|
||||
.state
|
||||
@@ -15623,6 +15895,149 @@ 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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// A holder whose delete reached only the disk with the needle's shard reads
|
||||
// it deleted, so a retry through another server still forwards the delete
|
||||
// for the holder's other disk.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn test_batch_delete_forwards_when_a_peer_reads_the_ec_needle_deleted() {
|
||||
let (peer, peer_tmp) = make_service_with_two_disk_complete_ec_volume(7067);
|
||||
let vid = VolumeId(7067);
|
||||
let (service, tmp) = make_local_service_with_volume("", None);
|
||||
let idx_dir = peer_tmp.path().join("data1");
|
||||
for name in ["7067.ecx", "7067.ecj", "7067.vif", "7067.ec13"] {
|
||||
std::fs::copy(idx_dir.join(name), tmp.path().join(name)).unwrap();
|
||||
}
|
||||
service
|
||||
.volume_ec_shards_mount(Request::new(volume_server_pb::VolumeEcShardsMountRequest {
|
||||
volume_id: 7067,
|
||||
collection: String::new(),
|
||||
shard_ids: vec![13],
|
||||
source_disk_type: String::new(),
|
||||
recover_missing_index: false,
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
peer.state
|
||||
.store
|
||||
.write()
|
||||
.unwrap()
|
||||
.find_ec_volume_mut(vid)
|
||||
.unwrap()
|
||||
.journal_delete(NeedleId(3))
|
||||
.unwrap();
|
||||
let peer_state = peer.state.clone();
|
||||
let (port, _shutdown) = serve_source(peer).await;
|
||||
let peer_addr = format!("127.0.0.1:{port}.{port}");
|
||||
service
|
||||
.state
|
||||
.store
|
||||
.read()
|
||||
.unwrap()
|
||||
.find_ec_volume(vid)
|
||||
.unwrap()
|
||||
.merge_shard_locations(
|
||||
(0u8..14)
|
||||
.map(|sid| (sid, vec![peer_addr.clone()]))
|
||||
.collect(),
|
||||
);
|
||||
|
||||
let fid = needle::FileId::new(vid, NeedleId(3), Cookie(3));
|
||||
let resp = service
|
||||
.batch_delete(Request::new(volume_server_pb::BatchDeleteRequest {
|
||||
file_ids: vec![fid.to_string()],
|
||||
skip_cookie_check: false,
|
||||
fsync: false,
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
assert_eq!(resp.results[0].status, 404, "{:?}", resp.results);
|
||||
let store = peer_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)),
|
||||
"peer 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(&[]);
|
||||
|
||||
@@ -3669,6 +3669,10 @@ pub async fn delete_handler(
|
||||
// distributed reader reports both as `Ok(None)`, and both
|
||||
// mean the same thing to a deleter.
|
||||
let result = DeleteResult { size: 0 };
|
||||
crate::server::store_ec::forward_ec_delete_of_deleted_needle(
|
||||
&state, vid, needle_id,
|
||||
)
|
||||
.await;
|
||||
return json_response_with_params(
|
||||
StatusCode::NOT_FOUND,
|
||||
&result,
|
||||
|
||||
@@ -158,7 +158,7 @@ pub async fn read_ec_shard_needle_or_miss(
|
||||
match cached_lookup_ec_shard_locations(state, vid).await {
|
||||
Ok(fresh) => {
|
||||
// A complete reply merges into the cache; an incomplete one
|
||||
// (< data_shards) is left unwritten — keep the prior cache.
|
||||
// (< data_shards) only puts the holders it names first.
|
||||
match write_back_shard_locations(
|
||||
state,
|
||||
vid,
|
||||
@@ -167,8 +167,6 @@ pub async fn read_ec_shard_needle_or_miss(
|
||||
snapshot.encode_ts_ns,
|
||||
) {
|
||||
Some(merged) => shard_locations = merged,
|
||||
// An incomplete reply leaves the cache unwritten and its refresh
|
||||
// time unadvanced, so the mark this refresh consumed goes back.
|
||||
None => mark_shard_locations_stale(state, vid),
|
||||
}
|
||||
}
|
||||
@@ -443,6 +441,25 @@ pub async fn delete_ec_shard_needle_distributed(
|
||||
)))
|
||||
}
|
||||
|
||||
/// A delete whose read found no needle. A holder's read checks one disk's
|
||||
/// deletion set, and a delete that failed part way can leave another of its
|
||||
/// disks live, so forward again, best effort; holders skip copies already
|
||||
/// recording it. Nothing is sent when this server's index has no live entry.
|
||||
pub async fn forward_ec_delete_of_deleted_needle(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
needle_id: NeedleId,
|
||||
) {
|
||||
if let Err(e) = delete_ec_shard_needle_distributed(state, vid, needle_id).await {
|
||||
tracing::debug!(
|
||||
"re-forward delete of deleted ec needle {}.{}: {}",
|
||||
vid.0,
|
||||
needle_id,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `doDeleteNeedleFromRemoteEcShardServers` in Go. `Ok(false)` is the
|
||||
/// shard-missing signal — no live holder anywhere — that triggers the
|
||||
/// caller's fallback walk over the remaining shards.
|
||||
@@ -533,38 +550,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<VolumeServerState>,
|
||||
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
|
||||
@@ -714,8 +741,10 @@ pub async fn scrub_ec_volume_distributed(
|
||||
) {
|
||||
match cached_lookup_ec_shard_locations(state, vid).await {
|
||||
Ok(fresh) => {
|
||||
let partial = located_shard_count(&fresh) < data_shards;
|
||||
if write_back_shard_locations(state, vid, fresh, data_shards, expected_encode_ts_ns)
|
||||
.is_none()
|
||||
|| partial
|
||||
{
|
||||
mark_shard_locations_stale(state, vid);
|
||||
return (
|
||||
@@ -1232,35 +1261,44 @@ async fn cached_lookup_ec_shard_locations(
|
||||
.lookup_ec_volume(Request::new(LookupEcVolumeRequest { volume_id: vid.0 }))
|
||||
.await
|
||||
.map_err(|e| io::Error::other(format!("lookup_ec_volume: {}", e)))?;
|
||||
let resp = resp.into_inner();
|
||||
Ok(shard_locations_from_reply(resp.into_inner()))
|
||||
}
|
||||
|
||||
/// The shard slots of a `LookupEcVolume` reply. The master answers every slot
|
||||
/// it tracks, so a shard whose holders are all down comes back with no
|
||||
/// addresses: it does not count toward the reply's completeness, and a complete
|
||||
/// reply drops it from the cache, as Go's `cachedLookupEcShardLocations` does.
|
||||
fn shard_locations_from_reply(
|
||||
resp: master_pb::LookupEcVolumeResponse,
|
||||
) -> HashMap<ShardId, Vec<String>> {
|
||||
let mut out = HashMap::new();
|
||||
for entry in resp.shard_id_locations {
|
||||
let Ok(sid) = shard_id_try_from(entry.shard_id) else {
|
||||
continue;
|
||||
};
|
||||
let addrs: Vec<String> = entry
|
||||
.locations
|
||||
.iter()
|
||||
.map(format_location_as_server_address)
|
||||
.collect();
|
||||
// Defensive: skip out-of-range shard ids from the master instead of
|
||||
// truncating (256 would alias 0). Valid replies are unaffected.
|
||||
let Ok(sid) = shard_id_try_from(entry.shard_id) else {
|
||||
continue;
|
||||
};
|
||||
out.insert(sid, addrs);
|
||||
}
|
||||
Ok(out)
|
||||
out
|
||||
}
|
||||
|
||||
fn located_shard_count(locations: &HashMap<ShardId, Vec<String>>) -> usize {
|
||||
locations.values().filter(|addrs| !addrs.is_empty()).count()
|
||||
}
|
||||
|
||||
/// Merge a fresh `LookupEcVolume` reply into the per-EcVolume shard-location
|
||||
/// cache. Returns the merged map on success, or `None` when the reply is
|
||||
/// incomplete (and was therefore NOT written) or the volume is gone.
|
||||
/// cache. Returns the resulting map, or `None` when the volume is gone.
|
||||
///
|
||||
/// Completeness guard (mirrors Go's `cachedLookupEcShardLocations`): a reply
|
||||
/// carrying fewer than `data_shards` shard locations is a master-mid-recovery
|
||||
/// partial, not ground truth — Go aborts the lookup with a retryable error and
|
||||
/// leaves the cache + refresh time untouched. Returning `None` without writing
|
||||
/// does the same, so a previously-complete cache is never clobbered with a
|
||||
/// partial map. On a complete reply the write is a per-shard MERGE (see
|
||||
/// partial, not ground truth. It only puts the holders it names ahead of the
|
||||
/// cached ones, and leaves the refresh time unadvanced with the map marked
|
||||
/// stale, so a previously-complete cache is never clobbered with a partial map.
|
||||
/// On a complete reply the write is a per-shard MERGE (see
|
||||
/// `merge_shard_locations`), not a full replace.
|
||||
fn write_back_shard_locations(
|
||||
state: &Arc<VolumeServerState>,
|
||||
@@ -1269,11 +1307,11 @@ fn write_back_shard_locations(
|
||||
data_shards: usize,
|
||||
expected_encode_ts_ns: i64,
|
||||
) -> Option<HashMap<ShardId, Vec<String>>> {
|
||||
if locations.len() < data_shards {
|
||||
return None;
|
||||
}
|
||||
let store = state.store.read().unwrap();
|
||||
let ecv = find_ec_volume_for_scrub(&store, vid, expected_encode_ts_ns)?;
|
||||
if located_shard_count(&locations) < data_shards {
|
||||
return Some(ecv.merge_partial_shard_locations(locations));
|
||||
}
|
||||
Some(ecv.merge_shard_locations(locations))
|
||||
}
|
||||
|
||||
@@ -1336,6 +1374,10 @@ struct EcShardMap<'a> {
|
||||
parity_shards: usize,
|
||||
}
|
||||
|
||||
/// Bounds asking a delisted holder, which may have stopped answering, before
|
||||
/// the read reconstructs the shard (Go's `ecReadHintTimeout`).
|
||||
const EC_READ_HINT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Try direct peer read; on failure, reconstruct via Reed-Solomon
|
||||
/// from the other shards. Mirrors `readOneEcShardInterval`'s tail.
|
||||
async fn fetch_one_interval(
|
||||
@@ -1344,6 +1386,12 @@ async fn fetch_one_interval(
|
||||
map: EcShardMap<'_>,
|
||||
) -> io::Result<(Vec<u8>, bool)> {
|
||||
let EcInterval { vid, shard_id, .. } = iv;
|
||||
if map.locations.get(&shard_id).is_none_or(Vec::is_empty)
|
||||
&& let Some((hints, revision)) = shard_read_hints(state, vid, shard_id)
|
||||
&& ask_ec_shard_read_hints(state, iv, &hints, revision).await
|
||||
{
|
||||
return Ok((Vec::new(), true));
|
||||
}
|
||||
// Direct peer read against the cached locations for this shard.
|
||||
if let Some(sources) = map.locations.get(&shard_id)
|
||||
&& !sources.is_empty()
|
||||
@@ -1521,7 +1569,8 @@ async fn do_read_remote_ec_shard_interval(
|
||||
}
|
||||
|
||||
/// Reads one `VolumeEcShardRead` reply into the interval's bytes, or the
|
||||
/// holder's deleted answer, which stands even if the stream fails after it.
|
||||
/// holder's deleted answer, taken as soon as it arrives so a stream that fails
|
||||
/// or stalls after it cannot lose it.
|
||||
async fn collect_ec_shard_read(
|
||||
mut stream: tonic::Streaming<VolumeEcShardReadResponse>,
|
||||
source: &str,
|
||||
@@ -1535,12 +1584,11 @@ async fn collect_ec_shard_read(
|
||||
..
|
||||
} = iv;
|
||||
let mut out = Vec::with_capacity(size);
|
||||
let mut is_deleted = false;
|
||||
// A deleted answer stands even if the stream fails after it.
|
||||
while let Some(msg) = match stream.message().await {
|
||||
Err(_) if is_deleted => None,
|
||||
msg => msg.map_err(|e| io::Error::other(format!("recv: {}", e)))?,
|
||||
} {
|
||||
while let Some(msg) = stream
|
||||
.message()
|
||||
.await
|
||||
.map_err(|e| io::Error::other(format!("recv: {}", e)))?
|
||||
{
|
||||
// Validate the served shard's identity client-side, so the guard holds even
|
||||
// against a pre-upgrade server that ignored the request field (returns 0).
|
||||
// A mismatch fails the read; the caller recovers from parity.
|
||||
@@ -1550,23 +1598,20 @@ async fn collect_ec_shard_read(
|
||||
vid.0, shard_id, source, expected_encode_ts_ns, msg.encode_ts_ns
|
||||
)));
|
||||
}
|
||||
// A runtime EC delete keeps the .ecx size positive; the holder masks the delete
|
||||
// at read time and answers is_deleted with no payload. Signal the deletion to
|
||||
// the caller (Go's `(bytes, is_deleted)` contract) instead of synthesizing bytes
|
||||
// here: the scrub zero-fills the interval (so the assembled needle hits read_bytes
|
||||
// -> SizeMismatch{found:0} -> suppression), the serving direct read short-circuits
|
||||
// to "deleted", and reconstruction EXCLUDES the shard rather than feeding zeros
|
||||
// into Reed-Solomon. Exempt from the short-read guard below.
|
||||
if msg.is_deleted {
|
||||
is_deleted = true;
|
||||
return Ok((Vec::new(), true));
|
||||
}
|
||||
if !msg.data.is_empty() {
|
||||
out.extend_from_slice(&msg.data);
|
||||
}
|
||||
}
|
||||
// A runtime EC delete keeps the .ecx size positive; the holder masks the delete
|
||||
// at read time and answers is_deleted with no payload. Signal the deletion to
|
||||
// the caller (Go's `(bytes, is_deleted)` contract) instead of synthesizing bytes
|
||||
// here: the scrub zero-fills the interval (so the assembled needle hits read_bytes
|
||||
// -> SizeMismatch{found:0} -> suppression), the serving direct read short-circuits
|
||||
// to "deleted", and reconstruction EXCLUDES the shard rather than feeding zeros
|
||||
// into Reed-Solomon. Exempt from the short-read guard below.
|
||||
if is_deleted {
|
||||
return Ok((Vec::new(), true));
|
||||
}
|
||||
if out.len() < size {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
@@ -1828,6 +1873,62 @@ async fn recover_one_remote_ec_shard_interval(
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports whether a delisted holder of the shard journaled the needle's
|
||||
/// delete (Go's `askEcShardReadHints`). Each holder is asked, since any one of
|
||||
/// them may hold the delete; only a deleted answer is taken, so one byte is
|
||||
/// enough. Holders that failed are forgotten, even when a later one answers
|
||||
/// deleted, unless a lookup changed the hints meanwhile.
|
||||
async fn ask_ec_shard_read_hints(
|
||||
state: &Arc<VolumeServerState>,
|
||||
iv: EcInterval,
|
||||
hints: &[String],
|
||||
revision: u64,
|
||||
) -> bool {
|
||||
let probe = EcInterval { size: 1, ..iv };
|
||||
let mut failed = Vec::new();
|
||||
let mut deleted = false;
|
||||
for hint in hints {
|
||||
let err = match tokio::time::timeout(
|
||||
EC_READ_HINT_TIMEOUT,
|
||||
do_read_remote_ec_shard_interval(state, hint, probe),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok((_, true))) => {
|
||||
deleted = true;
|
||||
break;
|
||||
}
|
||||
Ok(Ok(_)) => continue,
|
||||
Ok(Err(e)) => e.to_string(),
|
||||
Err(_) => "timed out".to_string(),
|
||||
};
|
||||
tracing::debug!(
|
||||
"read ec shard {}.{} from delisted holder {} failed: {}",
|
||||
iv.vid.0,
|
||||
iv.shard_id,
|
||||
hint,
|
||||
err
|
||||
);
|
||||
failed.push(hint.clone());
|
||||
}
|
||||
if !failed.is_empty() {
|
||||
let store = state.store.read().unwrap();
|
||||
if let Some(ecv) = store.find_ec_volume(iv.vid) {
|
||||
ecv.forget_shard_read_hints(iv.shard_id, revision, &failed);
|
||||
}
|
||||
}
|
||||
deleted
|
||||
}
|
||||
|
||||
fn shard_read_hints(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
shard_id: ShardId,
|
||||
) -> Option<(Vec<String>, u64)> {
|
||||
let store = state.store.read().unwrap();
|
||||
store.find_ec_volume(vid)?.shard_read_hints(shard_id)
|
||||
}
|
||||
|
||||
/// Drop a confirmed-corrupt shard's cached location so later reads go straight
|
||||
/// to reconstruction — Go's `forgetShardId` reached through the volume.
|
||||
fn forget_shard_location(state: &Arc<VolumeServerState>, vid: VolumeId, shard_id: ShardId) {
|
||||
@@ -2782,6 +2883,38 @@ mod tests {
|
||||
assert!(search(&shards, &metas, &n, dat_offset).is_none());
|
||||
}
|
||||
|
||||
// The master answers all 32 shard slots, located or not. While 7 of a 10+4
|
||||
// volume's shards have a holder up, the reply must count as 7 shards, short
|
||||
// of the data shards.
|
||||
#[test]
|
||||
fn a_lookup_reply_counts_only_located_shards() {
|
||||
use master_pb::lookup_ec_volume_response::EcShardIdLocation;
|
||||
let located = [0u32, 3, 4, 6, 7, 9, 12];
|
||||
let reply = master_pb::LookupEcVolumeResponse {
|
||||
volume_id: 136,
|
||||
shard_id_locations: (0..32u32)
|
||||
.map(|sid| EcShardIdLocation {
|
||||
shard_id: sid,
|
||||
locations: if located.contains(&sid) {
|
||||
vec![master_pb::Location {
|
||||
url: "10.0.0.5:8180".to_string(),
|
||||
grpc_port: 18180,
|
||||
..Default::default()
|
||||
}]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let got = shard_locations_from_reply(reply);
|
||||
assert_eq!(got.len(), 32);
|
||||
assert_eq!(located_shard_count(&got), 7);
|
||||
assert!(got[&1].is_empty());
|
||||
assert_eq!(got[&3], vec!["10.0.0.5:8180.18180".to_string()]);
|
||||
}
|
||||
|
||||
fn locations(count: usize) -> HashMap<ShardId, Vec<String>> {
|
||||
(0..count)
|
||||
.map(|sid| (sid as ShardId, vec!["127.0.0.1:8080".to_string()]))
|
||||
@@ -2808,9 +2941,10 @@ mod tests {
|
||||
assert!(needs_refresh(&locations(0), None, false, 10, 14));
|
||||
}
|
||||
|
||||
struct FailAfterFrame(Option<bytes::Bytes>);
|
||||
/// Serves one frame, then fails the stream or, with `stall`, never ends it.
|
||||
struct AfterFrame(Option<bytes::Bytes>, bool);
|
||||
|
||||
impl http_body::Body for FailAfterFrame {
|
||||
impl http_body::Body for AfterFrame {
|
||||
type Data = bytes::Bytes;
|
||||
type Error = tonic::Status;
|
||||
|
||||
@@ -2819,46 +2953,54 @@ mod tests {
|
||||
_cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<Option<Result<http_body::Frame<bytes::Bytes>, tonic::Status>>>
|
||||
{
|
||||
std::task::Poll::Ready(Some(match self.0.take() {
|
||||
Some(frame) => Ok(http_body::Frame::data(frame)),
|
||||
None => Err(tonic::Status::unavailable(
|
||||
match self.0.take() {
|
||||
Some(frame) => std::task::Poll::Ready(Some(Ok(http_body::Frame::data(frame)))),
|
||||
None if self.1 => std::task::Poll::Pending,
|
||||
None => std::task::Poll::Ready(Some(Err(tonic::Status::unavailable(
|
||||
"stream failed after the deleted answer",
|
||||
)),
|
||||
}))
|
||||
)))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A holder's deleted answer stands even when its stream fails afterwards,
|
||||
/// so a later source or the quarantined shard cannot answer for the needle.
|
||||
/// A holder's deleted answer stands even when its stream fails or stalls
|
||||
/// afterwards, so a later source or the quarantined shard cannot answer for
|
||||
/// the needle.
|
||||
#[tokio::test]
|
||||
async fn test_collect_ec_shard_read_keeps_deletion_when_the_stream_fails() {
|
||||
let message = prost::Message::encode_to_vec(&VolumeEcShardReadResponse {
|
||||
is_deleted: true,
|
||||
..Default::default()
|
||||
});
|
||||
let mut frame = vec![0u8];
|
||||
frame.extend_from_slice(&(message.len() as u32).to_be_bytes());
|
||||
frame.extend_from_slice(&message);
|
||||
let stream = tonic::Streaming::new_response(
|
||||
tonic_prost::ProstDecoder::<VolumeEcShardReadResponse>::default(),
|
||||
FailAfterFrame(Some(frame.into())),
|
||||
tonic::codegen::http::StatusCode::OK,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
let iv = EcInterval {
|
||||
vid: VolumeId(7),
|
||||
needle_id: NeedleId(42),
|
||||
shard_id: 0,
|
||||
shard_offset: 0,
|
||||
size: 64,
|
||||
expected_encode_ts_ns: 0,
|
||||
};
|
||||
for stall in [false, true] {
|
||||
let message = prost::Message::encode_to_vec(&VolumeEcShardReadResponse {
|
||||
is_deleted: true,
|
||||
..Default::default()
|
||||
});
|
||||
let mut frame = vec![0u8];
|
||||
frame.extend_from_slice(&(message.len() as u32).to_be_bytes());
|
||||
frame.extend_from_slice(&message);
|
||||
let stream = tonic::Streaming::new_response(
|
||||
tonic_prost::ProstDecoder::<VolumeEcShardReadResponse>::default(),
|
||||
AfterFrame(Some(frame.into()), stall),
|
||||
tonic::codegen::http::StatusCode::OK,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
let iv = EcInterval {
|
||||
vid: VolumeId(7),
|
||||
needle_id: NeedleId(42),
|
||||
shard_id: 0,
|
||||
shard_offset: 0,
|
||||
size: 64,
|
||||
expected_encode_ts_ns: 0,
|
||||
};
|
||||
|
||||
let (buf, is_deleted) = collect_ec_shard_read(stream, "peer:18080", iv)
|
||||
let (buf, is_deleted) = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
collect_ec_shard_read(stream, "peer:18080", iv),
|
||||
)
|
||||
.await
|
||||
.expect("the deleted answer waited for the stream to end")
|
||||
.unwrap();
|
||||
assert!(is_deleted);
|
||||
assert!(buf.is_empty());
|
||||
assert!(is_deleted, "stall={stall}");
|
||||
assert!(buf.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,17 @@ pub(crate) struct ShardLocationCache {
|
||||
/// Maps shard ID -> list of server addresses where that shard exists.
|
||||
/// Used for distributed EC reads across the cluster.
|
||||
locations: HashMap<ShardId, Vec<String>>,
|
||||
/// Holders a complete lookup stopped placing a shard on (Go's
|
||||
/// `ShardReadHints`). Reads ask them before reconstructing, for a delete only
|
||||
/// such a holder journaled, but take nothing else from them: a delete made
|
||||
/// since went to a listed holder, which reconstruction asks. Deletes never
|
||||
/// use them.
|
||||
read_hints: HashMap<ShardId, Vec<String>>,
|
||||
/// Changes with every change to `read_hints` (Go's `ShardReadHintsRevision`),
|
||||
/// so a read only forgets the hint holders it asked if no lookup changed them.
|
||||
/// Drawn from `READ_HINTS_REVISION`, so a revision read before a remount
|
||||
/// never matches the new `EcVolume`'s cache.
|
||||
read_hints_revision: u64,
|
||||
/// Wall-clock timestamp of the most recent successful `LookupEcVolume`
|
||||
/// refresh of `locations`. `None` until the first refresh. Drives the
|
||||
/// staleness heuristic in `cached_lookup_ec_shard_locations` (mirrors Go's
|
||||
@@ -49,6 +60,12 @@ pub(crate) struct ShardLocationCache {
|
||||
/// A multiple of `NEEDLE_ID_SIZE`; 1 MiB is 131072 entries per syscall.
|
||||
const ECJ_LOAD_CHUNK_BYTES: usize = 1 << 20;
|
||||
|
||||
static READ_HINTS_REVISION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
fn next_read_hints_revision() -> u64 {
|
||||
READ_HINTS_REVISION.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
|
||||
}
|
||||
|
||||
/// Process-wide epoch bumped whenever a failed .ecj append truncates its
|
||||
/// uncommitted tail. A decode that read the journal without the store lock
|
||||
/// compares a sample taken before the read with one taken under the
|
||||
@@ -308,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
|
||||
@@ -1726,10 +1749,11 @@ impl EcVolume {
|
||||
/// stamp the refresh time, returning a clone of the resulting map.
|
||||
///
|
||||
/// Per-shard upsert (mirrors Go's `cachedLookupEcShardLocations`): each shard
|
||||
/// id present in the reply overwrites its cached entry, while shard ids absent
|
||||
/// from the reply keep their previously-cached locations — so a reply that
|
||||
/// passes the data-shard completeness guard but omits a shard already in cache
|
||||
/// does not drop that shard's known location (unlike a full replace).
|
||||
/// id present in the reply overwrites its cached entry, and one the reply
|
||||
/// places nowhere is dropped, while shard ids absent from the reply keep
|
||||
/// their previously-cached locations — so a reply that passes the data-shard
|
||||
/// completeness guard but omits a shard already in cache does not drop that
|
||||
/// shard's known location (unlike a full replace).
|
||||
///
|
||||
/// Map and refresh time advance in one write section, so no reader can pair
|
||||
/// the merged map with the previous lookup's timestamp.
|
||||
@@ -1739,12 +1763,51 @@ impl EcVolume {
|
||||
) -> HashMap<ShardId, Vec<String>> {
|
||||
let mut cache = self.shard_locations.write().unwrap();
|
||||
for (shard_id, addrs) in locations {
|
||||
cache.locations.insert(shard_id, addrs);
|
||||
if addrs.is_empty() {
|
||||
if let Some(known) = cache.locations.remove(&shard_id)
|
||||
&& !known.is_empty()
|
||||
{
|
||||
cache.read_hints.insert(shard_id, known);
|
||||
cache.read_hints_revision = next_read_hints_revision();
|
||||
}
|
||||
} else {
|
||||
if cache.read_hints.remove(&shard_id).is_some() {
|
||||
cache.read_hints_revision = next_read_hints_revision();
|
||||
}
|
||||
cache.locations.insert(shard_id, addrs);
|
||||
}
|
||||
}
|
||||
cache.refreshed_at = Some(Instant::now());
|
||||
cache.locations.clone()
|
||||
}
|
||||
|
||||
/// Put a partial reply's holders ahead of the cached ones for each shard it
|
||||
/// places, keeping the cached addresses as fallback and every other shard
|
||||
/// and the refresh time alone. A partial is not the volume's map, but a read
|
||||
/// can still go straight to a shard it names; the map stays marked so the
|
||||
/// next read looks it up again.
|
||||
pub(crate) fn merge_partial_shard_locations(
|
||||
&self,
|
||||
locations: HashMap<ShardId, Vec<String>>,
|
||||
) -> HashMap<ShardId, Vec<String>> {
|
||||
let mut cache = self.shard_locations.write().unwrap();
|
||||
for (shard_id, mut addrs) in locations {
|
||||
if addrs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(known) = cache.locations.get(&shard_id) {
|
||||
for addr in known {
|
||||
if !addrs.contains(addr) {
|
||||
addrs.push(addr.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
cache.locations.insert(shard_id, addrs);
|
||||
}
|
||||
cache.stale = true;
|
||||
cache.locations.clone()
|
||||
}
|
||||
|
||||
/// The cached map and the time it was learned, read in one section. Both
|
||||
/// halves describe the same refresh, which is what the freshness heuristic
|
||||
/// assumes when it ages the map against the timestamp.
|
||||
@@ -1755,6 +1818,37 @@ impl EcVolume {
|
||||
(cache.locations.clone(), cache.refreshed_at)
|
||||
}
|
||||
|
||||
/// The shard's hint with the revision to pass back to
|
||||
/// `forget_shard_read_hints`.
|
||||
pub(crate) fn shard_read_hints(&self, shard_id: ShardId) -> Option<(Vec<String>, u64)> {
|
||||
let cache = self.shard_locations.read().unwrap();
|
||||
let hints = cache.read_hints.get(&shard_id)?.clone();
|
||||
Some((hints, cache.read_hints_revision))
|
||||
}
|
||||
|
||||
/// Drops the `failed` holders from the shard's hint only if no lookup
|
||||
/// changed the hints since `revision`, as one may have while the reads were
|
||||
/// in flight.
|
||||
pub(crate) fn forget_shard_read_hints(
|
||||
&self,
|
||||
shard_id: ShardId,
|
||||
revision: u64,
|
||||
failed: &[String],
|
||||
) {
|
||||
let mut cache = self.shard_locations.write().unwrap();
|
||||
if cache.read_hints_revision != revision {
|
||||
return;
|
||||
}
|
||||
let Some(hints) = cache.read_hints.get_mut(&shard_id) else {
|
||||
return;
|
||||
};
|
||||
hints.retain(|h| !failed.contains(h));
|
||||
if hints.is_empty() {
|
||||
cache.read_hints.remove(&shard_id);
|
||||
}
|
||||
cache.read_hints_revision = next_read_hints_revision();
|
||||
}
|
||||
|
||||
/// Mark the cached map for a prompt re-check after a read failed against one
|
||||
/// of its locations.
|
||||
pub(crate) fn mark_shard_locations_stale(&self) {
|
||||
@@ -3709,6 +3803,33 @@ mod tests {
|
||||
assert_eq!(vol.read_deleted_needles().unwrap(), ids);
|
||||
}
|
||||
|
||||
/// A read hint revision taken from one instance of a volume must not let
|
||||
/// a read forget the hint a later instance holds after a remount.
|
||||
#[test]
|
||||
fn test_read_hint_revision_is_not_shared_across_instances() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let vid = VolumeId(50);
|
||||
write_ecx_file(dir, "", vid, &[]);
|
||||
let holder = "127.0.0.1:8080".to_string();
|
||||
let delist = |vol: &EcVolume| {
|
||||
vol.merge_shard_locations(HashMap::from([(0, vec![holder.clone()])]));
|
||||
vol.merge_shard_locations(HashMap::from([(0, Vec::new())]));
|
||||
vol.shard_read_hints(0).unwrap().1
|
||||
};
|
||||
let old = EcVolume::new(dir, dir, "", vid).unwrap();
|
||||
let revision = delist(&old);
|
||||
drop(old);
|
||||
|
||||
let vol = EcVolume::new(dir, dir, "", vid).unwrap();
|
||||
delist(&vol);
|
||||
vol.forget_shard_read_hints(0, revision, std::slice::from_ref(&holder));
|
||||
assert_eq!(
|
||||
vol.shard_read_hints(0).map(|(hints, _)| hints),
|
||||
Some(vec![holder])
|
||||
);
|
||||
}
|
||||
|
||||
/// A journal that grew, or was replaced, after it was loaded must not be
|
||||
/// compacted from the stale set.
|
||||
#[test]
|
||||
@@ -5448,6 +5569,78 @@ mod tests {
|
||||
later.unwrap() >= before,
|
||||
"the second merge re-stamped the refresh time"
|
||||
);
|
||||
|
||||
// A shard the master places nowhere is dropped, not kept at an address
|
||||
// a delete would trust; its holder stays a place a read can ask first.
|
||||
let merged = vol.merge_shard_locations(HashMap::from([(0, Vec::new())]));
|
||||
assert_eq!(merged, HashMap::from([(1, vec!["c:3".to_string()])]));
|
||||
let hint = || vol.shard_read_hints(0).map(|(hint, _)| hint);
|
||||
let a = vec!["a:1".to_string()];
|
||||
assert_eq!(hint(), Some(a.clone()));
|
||||
vol.merge_shard_locations(HashMap::from([(0, Vec::new())]));
|
||||
assert_eq!(
|
||||
hint(),
|
||||
Some(a.clone()),
|
||||
"a later reply placing the shard nowhere keeps the hint"
|
||||
);
|
||||
let (_, revision) = vol.shard_read_hints(0).unwrap();
|
||||
vol.merge_shard_locations(HashMap::from([(0, a.clone())]));
|
||||
assert_eq!(hint(), None);
|
||||
vol.merge_shard_locations(HashMap::from([(0, Vec::new())]));
|
||||
vol.forget_shard_read_hints(0, revision, &a);
|
||||
assert_eq!(
|
||||
hint(),
|
||||
Some(a.clone()),
|
||||
"a failed read keeps a hint a lookup reinstalled meanwhile, even for the same holder"
|
||||
);
|
||||
let (_, revision) = vol.shard_read_hints(0).unwrap();
|
||||
vol.forget_shard_read_hints(0, revision, &a);
|
||||
assert_eq!(hint(), None);
|
||||
vol.merge_shard_locations(HashMap::from([(0, vec!["e:5".into(), "f:6".into()])]));
|
||||
vol.merge_shard_locations(HashMap::from([(0, Vec::new())]));
|
||||
let (_, revision) = vol.shard_read_hints(0).unwrap();
|
||||
vol.forget_shard_read_hints(0, revision, &["e:5".into()]);
|
||||
assert_eq!(
|
||||
hint(),
|
||||
Some(vec!["f:6".to_string()]),
|
||||
"only the holders that failed are forgotten"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_partial_shard_locations_keeps_known_holders_and_refresh_time() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let vol = mount_bare_ec_volume(tmp.path().to_str().unwrap());
|
||||
|
||||
let filled =
|
||||
vol.merge_partial_shard_locations(HashMap::from([(0, vec!["a:1".to_string()])]));
|
||||
assert_eq!(filled.get(&0), Some(&vec!["a:1".to_string()]));
|
||||
assert!(
|
||||
vol.shard_locations_snapshot().1.is_none(),
|
||||
"a partial reply is not a refresh"
|
||||
);
|
||||
|
||||
vol.merge_shard_locations(HashMap::from([(1, vec!["b:2".to_string()])]));
|
||||
let stamped = vol.shard_locations_snapshot().1;
|
||||
vol.claim_shard_locations_refresh(|_| true);
|
||||
let filled = vol.merge_partial_shard_locations(HashMap::from([
|
||||
(1, vec!["c:3".to_string()]),
|
||||
(2, vec!["d:4".to_string()]),
|
||||
(3, Vec::new()),
|
||||
]));
|
||||
assert_eq!(
|
||||
filled.get(&1),
|
||||
Some(&vec!["c:3".to_string(), "b:2".to_string()]),
|
||||
"a holder the partial names goes first, the cached one stays as fallback"
|
||||
);
|
||||
assert_eq!(filled.get(&0), Some(&vec!["a:1".to_string()]));
|
||||
assert_eq!(filled.get(&2), Some(&vec!["d:4".to_string()]));
|
||||
assert!(!filled.contains_key(&3), "a partial reply's empty slot adds nothing");
|
||||
assert_eq!(vol.shard_locations_snapshot().1, stamped);
|
||||
assert!(
|
||||
vol.claim_shard_locations_refresh(|stale| stale),
|
||||
"the partial leaves the map marked for the next lookup"
|
||||
);
|
||||
}
|
||||
|
||||
/// The stale mark is consumed by the refresh that acts on it, exactly once:
|
||||
|
||||
@@ -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<usize> {
|
||||
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",
|
||||
);
|
||||
|
||||
@@ -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})
|
||||
}
|
||||
|
||||
|
||||
@@ -485,6 +485,14 @@ func (f *Filer) TransactionCovers(ctx context.Context, paths ...util.FullPath) b
|
||||
return ok && fsw.transactionCovers(paths...)
|
||||
}
|
||||
|
||||
// OverwritesAtOnce reports whether an entry inserted at path replaces what is
|
||||
// stored there at once and whole: the default store says that its inserts do,
|
||||
// and it holds the entry.
|
||||
func (f *Filer) OverwritesAtOnce(path util.FullPath) bool {
|
||||
fsw, ok := f.Store.(*FilerStoreWrapper)
|
||||
return ok && fsw.overwritesAtOnce(path)
|
||||
}
|
||||
|
||||
func (f *Filer) CommitTransaction(ctx context.Context) error {
|
||||
return f.Store.CommitTransaction(ctx)
|
||||
}
|
||||
@@ -666,6 +674,55 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry,
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReplaceFileForRename stores a file renamed over an existing file at the
|
||||
// target's path with one store write, on a store whose insert replaces an
|
||||
// entry at once and whole (OverwritesAtOnce). Deleting the target first would
|
||||
// leave the path empty there for anyone reading it until the new entry lands.
|
||||
// Apart from that it does what CreateEntry does for a new entry: it refuses a
|
||||
// name the filer would not create, and it creates missing parents after the
|
||||
// write. The store drops the replaced entry's hard link, if it had one, after
|
||||
// the write.
|
||||
//
|
||||
// The target was a file when the rename looked it up. Another filer may have
|
||||
// turned it into a directory since, by creating a child under it, and writing
|
||||
// over that would strand its children; or it may have deleted the target's
|
||||
// directory. So the target is read again right before the write and a
|
||||
// directory is refused, as the lookup would have refused it. Such a store has
|
||||
// no conditional write: this leaves the window that a delete-first rename has
|
||||
// between its own read of the target and its delete.
|
||||
func (f *Filer) ReplaceFileForRename(ctx context.Context, entry *Entry, maxFilenameLength uint32) error {
|
||||
ctx = f.syncWriteContext(ctx, entry.FullPath)
|
||||
if entry.FullPath.IsLongerFileName(maxFilenameLength) {
|
||||
return filer_pb.ErrEntryNameTooLong
|
||||
}
|
||||
if entry.FullPath.HasDotSegment() {
|
||||
return fmt.Errorf("invalid path %s", entry.FullPath)
|
||||
}
|
||||
current, findErr := f.FindEntry(context.WithValue(ctx, lazyFetchContextKey{}, true), entry.FullPath)
|
||||
if findErr != nil && !errors.Is(findErr, filer_pb.ErrNotFound) {
|
||||
return fmt.Errorf("find entry %s: %w", entry.FullPath, findErr)
|
||||
}
|
||||
if current != nil && current.IsDirectory() {
|
||||
return fmt.Errorf("%s: %w", entry.FullPath, filer_pb.ErrExistingIsDirectory)
|
||||
}
|
||||
if entry.Attr.Atime.IsZero() {
|
||||
entry.Attr.Atime = entryInitialAtime(entry.Attr)
|
||||
}
|
||||
f.ensureEntryInode(entry)
|
||||
if err := f.Store.InsertEntry(ctx, entry); err != nil {
|
||||
glog.ErrorfCtx(ctx, "replace entry %s: %v", entry.FullPath, err)
|
||||
return fmt.Errorf("replace entry %s: %w", entry.FullPath, err)
|
||||
}
|
||||
// as in CreateEntry, parents go after the entry
|
||||
dirParts := strings.Split(string(entry.FullPath), "/")
|
||||
if err := f.ensureParentDirectoryEntry(ctx, entry, dirParts, len(dirParts)-1, false); err != nil {
|
||||
glog.ErrorfCtx(ctx, "create parent directories of %s: %v", entry.FullPath, err)
|
||||
return err
|
||||
}
|
||||
stats.FilerObjectSizeBytesHistogram.Observe(float64(entry.Size()))
|
||||
return nil
|
||||
}
|
||||
|
||||
// lockDirectoryCreate holds the path's directoryCreateLock; the returned
|
||||
// unlock may be called more than once. A store transaction keeps its
|
||||
// connection until it commits, and a holder may need that connection, so
|
||||
|
||||
@@ -91,3 +91,13 @@ type Debuggable interface {
|
||||
type IsolatingTransactionStore interface {
|
||||
IsolatesTransactions() bool
|
||||
}
|
||||
|
||||
// OverwritingStore is implemented by a store without transactions whose
|
||||
// InsertEntry over an existing entry replaces it at once and whole: the stored
|
||||
// entry, its expiry, and its listing in the directory. A rename can then write
|
||||
// a file over its target instead of deleting the target first. A store says so
|
||||
// itself, once its insert has been checked: an upsert may leave part of the
|
||||
// old row in place. The Redis stores do.
|
||||
type OverwritingStore interface {
|
||||
OverwritesAtOnce() bool
|
||||
}
|
||||
@@ -465,6 +465,14 @@ func (fsw *FilerStoreWrapper) transactionCovers(paths ...util.FullPath) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// overwritesAtOnce reports whether an entry inserted at path replaces what is
|
||||
// stored there at once and whole: the default store says that its inserts do
|
||||
// (OverwritingStore), and it holds the entry.
|
||||
func (fsw *FilerStoreWrapper) overwritesAtOnce(path util.FullPath) bool {
|
||||
overwriting, ok := fsw.defaultStore.(OverwritingStore)
|
||||
return ok && overwriting.OverwritesAtOnce() && fsw.getActualStore(path) == fsw.defaultStore
|
||||
}
|
||||
|
||||
func (fsw *FilerStoreWrapper) BeginTransaction(ctx context.Context) (context.Context, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -23,6 +23,15 @@ type UniversalRedisStore struct {
|
||||
Client redis.UniversalClient
|
||||
}
|
||||
|
||||
// OverwritesAtOnce: Redis keeps no transaction here, the SET of an insert
|
||||
// replaces the stored entry together with its expiry, and the insert lists the
|
||||
// name whether or not it was listed before.
|
||||
func (store *UniversalRedisStore) OverwritesAtOnce() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
var _ filer.OverwritingStore = (*UniversalRedisStore)(nil)
|
||||
|
||||
func (store *UniversalRedisStore) BeginTransaction(ctx context.Context) (context.Context, error) {
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -179,3 +179,43 @@ func TestDeleteFolderChildrenRemovesTheListing(t *testing.T) {
|
||||
t.Errorf("listing key should be removed with the children, still present")
|
||||
}
|
||||
}
|
||||
|
||||
// What OverwritesAtOnce declares: an InsertEntry over an existing entry
|
||||
// replaces the stored entry together with its expiry, and leaves the name
|
||||
// listed once.
|
||||
func TestInsertEntryOverAnExistingEntryReplacesIt(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
if !store.OverwritesAtOnce() {
|
||||
t.Fatal("OverwritesAtOnce = false")
|
||||
}
|
||||
ctx := context.Background()
|
||||
path := dir.Child("replaced")
|
||||
now := time.Now()
|
||||
if err := store.InsertEntry(ctx, &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644, TtlSec: 3600},
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertEntry %s: %v", path, err)
|
||||
}
|
||||
|
||||
if err := store.InsertEntry(ctx, &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0600, Inode: 4242},
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertEntry over %s: %v", path, err)
|
||||
}
|
||||
|
||||
got, err := store.FindEntry(ctx, path)
|
||||
if err != nil || got.Attr.Inode != 4242 || got.Attr.TtlSec != 0 {
|
||||
t.Fatalf("FindEntry = %+v, %v; want the second entry", got, err)
|
||||
}
|
||||
if ttl, err := store.Client.TTL(ctx, string(path)).Result(); err != nil || ttl != -1 {
|
||||
t.Fatalf("TTL of the stored entry = %v, %v; want none left from the first entry", ttl, err)
|
||||
}
|
||||
if members := indexMembers(t, store, dir); len(members) != 1 || members[0] != "replaced" {
|
||||
t.Fatalf("directory index holds %v, want [replaced]", members)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "replaced" {
|
||||
t.Fatalf("listed %v, want [replaced]", names)
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,15 @@ func (store *UniversalRedis2Store) getKey(key string) string {
|
||||
return store.keyPrefix + key
|
||||
}
|
||||
|
||||
// OverwritesAtOnce: Redis keeps no transaction here, the SET of an insert
|
||||
// replaces the stored entry together with its expiry, and the insert lists the
|
||||
// name whether or not it was listed before.
|
||||
func (store *UniversalRedis2Store) OverwritesAtOnce() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
var _ filer.OverwritingStore = (*UniversalRedis2Store)(nil)
|
||||
|
||||
func (store *UniversalRedis2Store) BeginTransaction(ctx context.Context) (context.Context, error) {
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -437,3 +437,42 @@ func TestDeleteEntryKeepsChildListing(t *testing.T) {
|
||||
t.Errorf("listing key should be removed with the children, still present")
|
||||
}
|
||||
}
|
||||
|
||||
// What OverwritesAtOnce declares: an InsertEntry over an existing entry
|
||||
// replaces the stored entry together with its expiry, and leaves the name
|
||||
// listed once.
|
||||
func TestInsertEntryOverAnExistingEntryReplacesIt(t *testing.T) {
|
||||
for _, keyPrefix := range []string{"", "sw:"} {
|
||||
t.Run("keyPrefix="+keyPrefix, func(t *testing.T) {
|
||||
store, dir := newTestStore(t, keyPrefix)
|
||||
if !store.OverwritesAtOnce() {
|
||||
t.Fatal("OverwritesAtOnce = false")
|
||||
}
|
||||
ctx := context.Background()
|
||||
path := dir.Child("replaced")
|
||||
insertTestEntry(t, store, path, 3600)
|
||||
|
||||
now := time.Now()
|
||||
if err := store.InsertEntry(ctx, &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0600, Inode: 4242},
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertEntry over %s: %v", path, err)
|
||||
}
|
||||
|
||||
got, err := store.FindEntry(ctx, path)
|
||||
if err != nil || got.Attr.Inode != 4242 || got.Attr.TtlSec != 0 {
|
||||
t.Fatalf("FindEntry = %+v, %v; want the second entry", got, err)
|
||||
}
|
||||
if ttl, err := store.Client.TTL(ctx, store.getKey(string(path))).Result(); err != nil || ttl != -1 {
|
||||
t.Fatalf("TTL of the stored entry = %v, %v; want none left from the first entry", ttl, err)
|
||||
}
|
||||
if members := indexMembers(t, store, dir); len(members) != 1 || members[0] != "replaced" {
|
||||
t.Fatalf("directory index holds %v, want [replaced]", members)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "replaced" {
|
||||
t.Fatalf("listed %v, want [replaced]", names)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,15 @@ func checkUserPassword(username, password string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// OverwritesAtOnce: Redis keeps no transaction here, the SET of an insert
|
||||
// replaces the stored entry together with its expiry, and the insert lists the
|
||||
// name whether or not it was listed before.
|
||||
func (store *UniversalRedis3Store) OverwritesAtOnce() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
var _ filer.OverwritingStore = (*UniversalRedis3Store)(nil)
|
||||
|
||||
func (store *UniversalRedis3Store) BeginTransaction(ctx context.Context) (context.Context, error) {
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -194,3 +194,40 @@ func TestKeyPrefixScopesAllKeys(t *testing.T) {
|
||||
t.Fatalf("no prefixed keys should remain after cleanup: keys=%v err=%v", keys, err)
|
||||
}
|
||||
}
|
||||
|
||||
// What OverwritesAtOnce declares: an InsertEntry over an existing entry
|
||||
// replaces the stored entry together with its expiry, and leaves the name
|
||||
// listed once.
|
||||
func TestInsertEntryOverAnExistingEntryReplacesIt(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
if !store.OverwritesAtOnce() {
|
||||
t.Fatal("OverwritesAtOnce = false")
|
||||
}
|
||||
ctx := context.Background()
|
||||
path := dir.Child("replaced")
|
||||
now := time.Now()
|
||||
if err := store.InsertEntry(ctx, &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644, TtlSec: 3600},
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertEntry %s: %v", path, err)
|
||||
}
|
||||
|
||||
if err := store.InsertEntry(ctx, &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0600, Inode: 4242},
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertEntry over %s: %v", path, err)
|
||||
}
|
||||
|
||||
got, err := store.FindEntry(ctx, path)
|
||||
if err != nil || got.Attr.Inode != 4242 || got.Attr.TtlSec != 0 {
|
||||
t.Fatalf("FindEntry = %+v, %v; want the second entry", got, err)
|
||||
}
|
||||
if ttl, err := store.Client.TTL(ctx, store.getKey(string(path))).Result(); err != nil || ttl != -1 {
|
||||
t.Fatalf("TTL of the stored entry = %v, %v; want none left from the first entry", ttl, err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "replaced" {
|
||||
t.Fatalf("listed %v, want [replaced]", names)
|
||||
}
|
||||
}
|
||||
+18
-1
@@ -8,8 +8,10 @@ import (
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
@@ -571,12 +573,27 @@ func (wfs *WFS) maybeReadEntry(ctx context.Context, inode uint64) (path util.Ful
|
||||
if entry = wfs.removedDirEntry(inode); entry != nil {
|
||||
return "", nil, entry, fuse.OK
|
||||
}
|
||||
return
|
||||
return "", nil, nil, wfs.pathlessInodeStatus(inode, status)
|
||||
}
|
||||
entry, _, status = wfs.maybeLoadEntry(ctx, path)
|
||||
return
|
||||
}
|
||||
|
||||
// pathlessInodeStatus answers an operation on an inode that has no path here.
|
||||
// While the kernel still holds the inode (no Forget yet), its name was
|
||||
// replaced or removed under it, as by a rename over it after the kernel
|
||||
// resolved the old name: ESTALE makes open, stat, access and xattr calls redo
|
||||
// the path walk and reach the current entry (as on NFS), where ENOENT would
|
||||
// fail them although the name exists. A forgotten inode keeps status. Only
|
||||
// Linux redoes the walk: FUSE on macOS and FreeBSD purges the name cache on
|
||||
// ENOENT instead, and WinFsp has neither, so they keep ENOENT.
|
||||
func (wfs *WFS) pathlessInodeStatus(inode uint64, status fuse.Status) fuse.Status {
|
||||
if runtime.GOOS == "linux" && wfs.inodeToPath.HasInode(inode) {
|
||||
return fuse.Status(syscall.ESTALE)
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
// isLocalOnlyEntry reports whether entry holds local-only state not yet on the
|
||||
// filer — an open handle with dirty metadata, or a pending async flush. A
|
||||
// directory rebuild refills from a filer listing that omits such an entry, so it
|
||||
|
||||
@@ -28,7 +28,7 @@ func (wfs *WFS) AcquireHandle(ctx context.Context, inode uint64, flags, uid, gid
|
||||
var pathStatus fuse.Status
|
||||
path, pathStatus = wfs.inodeToPath.GetPath(inode)
|
||||
if pathStatus != fuse.OK {
|
||||
return nil, 0, pathStatus
|
||||
return nil, 0, wfs.pathlessInodeStatus(inode, pathStatus)
|
||||
}
|
||||
|
||||
// A fresh lookup returns the entry with the filer log position it
|
||||
|
||||
@@ -3,8 +3,12 @@ package mount
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
@@ -89,3 +93,88 @@ func TestHandleRenameResponseLeavesUncachedTargetOutOfCache(t *testing.T) {
|
||||
t.Fatalf("target inode = %d, want %d", updatedInode, sourceInode)
|
||||
}
|
||||
}
|
||||
|
||||
// A reader may resolve the target name to its old inode just before a rename
|
||||
// replaces it, then send OPEN/GETATTR for that inode after MovePath dropped
|
||||
// its path. Those must fail with ESTALE, so the kernel redoes the path walk
|
||||
// and opens the new file, not with ENOENT while the name exists. Once the
|
||||
// kernel forgets the old inode, the answer is ENOENT again.
|
||||
func TestRenameOverTargetLeavesOldInodeStale(t *testing.T) {
|
||||
uidGidMapper, err := meta_cache.NewUidGidMapper("", "")
|
||||
if err != nil {
|
||||
t.Fatalf("create uid/gid mapper: %v", err)
|
||||
}
|
||||
|
||||
root := util.FullPath("/")
|
||||
inodeToPath := NewInodeToPath(root, 1)
|
||||
|
||||
mc := meta_cache.NewMetaCache(
|
||||
filepath.Join(t.TempDir(), "meta"),
|
||||
uidGidMapper,
|
||||
root,
|
||||
false,
|
||||
func(path util.FullPath) {
|
||||
inodeToPath.MarkChildrenCached(path)
|
||||
},
|
||||
func(path util.FullPath) bool {
|
||||
return inodeToPath.IsChildrenCached(path)
|
||||
},
|
||||
func(meta_cache.EntryInvalidation) {},
|
||||
nil,
|
||||
)
|
||||
defer mc.Shutdown()
|
||||
|
||||
parentPath := util.FullPath("/run/shards/gpu0")
|
||||
sourcePath := parentPath.Child("active.json.tmp")
|
||||
targetPath := parentPath.Child("active.json")
|
||||
|
||||
inodeToPath.Lookup(parentPath, 1, true, false, 0, true)
|
||||
sourceInode := inodeToPath.Lookup(sourcePath, 1, false, false, 0, true)
|
||||
oldTargetInode := inodeToPath.Lookup(targetPath, 1, false, false, 0, true)
|
||||
|
||||
wfs := &WFS{
|
||||
metaCache: mc,
|
||||
inodeToPath: inodeToPath,
|
||||
fhMap: NewFileHandleToInode(),
|
||||
}
|
||||
|
||||
resp := &filer_pb.StreamRenameEntryResponse{
|
||||
Directory: string(parentPath),
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: &filer_pb.Entry{Name: "active.json.tmp"},
|
||||
NewEntry: &filer_pb.Entry{
|
||||
Name: "active.json",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Crtime: 1,
|
||||
Mtime: 1,
|
||||
FileMode: 0100644,
|
||||
FileSize: 17,
|
||||
Inode: sourceInode,
|
||||
},
|
||||
},
|
||||
NewParentPath: string(parentPath),
|
||||
},
|
||||
}
|
||||
if err := wfs.handleRenameResponse(context.Background(), resp, targetPath, nil); err != nil {
|
||||
t.Fatalf("handle rename response: %v", err)
|
||||
}
|
||||
|
||||
want := fuse.Status(syscall.ESTALE)
|
||||
if runtime.GOOS != "linux" {
|
||||
want = fuse.ENOENT
|
||||
}
|
||||
var attrOut fuse.AttrOut
|
||||
if status := wfs.GetAttr(nil, &fuse.GetAttrIn{InHeader: fuse.InHeader{NodeId: oldTargetInode}}, &attrOut); status != want {
|
||||
t.Fatalf("GetAttr on replaced inode = %v, want %v", status, want)
|
||||
}
|
||||
var openOut fuse.OpenOut
|
||||
if status := wfs.Open(nil, &fuse.OpenIn{InHeader: fuse.InHeader{NodeId: oldTargetInode}}, &openOut); status != want {
|
||||
t.Fatalf("Open on replaced inode = %v, want %v", status, want)
|
||||
}
|
||||
|
||||
// once the kernel forgets the old inode, it is unknown here
|
||||
inodeToPath.Forget(oldTargetInode, 1, nil, nil)
|
||||
if status := wfs.GetAttr(nil, &fuse.GetAttrIn{InHeader: fuse.InHeader{NodeId: oldTargetInode}}, &attrOut); status != fuse.ENOENT {
|
||||
t.Fatalf("GetAttr on forgotten inode = %v, want ENOENT", status)
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
}
|
||||
|
||||
@@ -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" +
|
||||
|
||||
@@ -479,7 +479,19 @@ func (fs *FilerServer) moveSelfEntry(ctx context.Context, stream filer_pb.Seawee
|
||||
remoteEntry = copiedRemote
|
||||
}
|
||||
|
||||
if existingTarget != nil {
|
||||
// A file renamed over a file is written over the target with one store
|
||||
// write when the store says that its insert replaces an entry at once and
|
||||
// whole (the Redis stores). Deleting the target first leaves its path empty
|
||||
// there for anyone reading it through another filer until the new entry
|
||||
// lands, since the rename's path locks fence this filer only. Everything
|
||||
// else keeps delete-then-create: any other store, among them those with
|
||||
// transactions, which hide the gap and fail cleanly if the target went
|
||||
// meanwhile; a target in a path-specific store; directories; and entries
|
||||
// with a remote object.
|
||||
inPlace := existingTarget != nil && !entry.IsDirectory() && !existingTarget.IsDirectory() &&
|
||||
entry.Remote == nil && existingTarget.Remote == nil && fs.filer.OverwritesAtOnce(newPath)
|
||||
|
||||
if existingTarget != nil && !inPlace {
|
||||
targetCtx := filer.WithSuppressedMetadataEvents(ctx)
|
||||
if copiedRemote != nil || deferredCopy {
|
||||
// the copy has replaced or still needs the target's object; keep it
|
||||
@@ -536,7 +548,20 @@ func (fs *FilerServer) moveSelfEntry(ctx context.Context, stream filer_pb.Seawee
|
||||
newEntry.Extended = maps.Clone(newEntry.Extended)
|
||||
delete(newEntry.Extended, filer.ExtRemoteRenameSourceKey)
|
||||
}
|
||||
if skipTargetLookup {
|
||||
if inPlace {
|
||||
var createdParents []*filer.Entry
|
||||
fs.filer.StampEntryCommitTsNs(newEntry)
|
||||
replaceErr := fs.filer.ReplaceFileForRename(filer.WithCreatedParents(ctx, &createdParents), newEntry, fs.filer.MaxFilenameLength)
|
||||
// as for a create below: a parent the write had to create again
|
||||
// reaches peers through its own event, published before the move
|
||||
for _, parent := range createdParents {
|
||||
*metadataEvents = append(*metadataEvents, metadataEvent{newEntry: parent})
|
||||
}
|
||||
if replaceErr != nil {
|
||||
fs.filer.ReleaseEntryCommitTsNs(newEntry.CommitTsNs)
|
||||
return replaceErr
|
||||
}
|
||||
} else if skipTargetLookup {
|
||||
if newEntry.FullPath.IsLongerFileName(fs.filer.MaxFilenameLength) {
|
||||
return filer_pb.ErrEntryNameTooLong
|
||||
}
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// watchTarget records every store write after which path was missing: what a
|
||||
// lookup through another filer would have seen at that moment on a store
|
||||
// without transactions.
|
||||
func watchTarget(store *renameTestStore, path string) (writes, missing *[]string) {
|
||||
writes, missing = &[]string{}, &[]string{}
|
||||
store.afterOp = func(op string, p util.FullPath) {
|
||||
*writes = append(*writes, op+" "+string(p))
|
||||
store.mu.Lock()
|
||||
_, found := store.entries[path]
|
||||
store.mu.Unlock()
|
||||
if !found {
|
||||
*missing = append(*missing, op+" "+string(p))
|
||||
}
|
||||
}
|
||||
return writes, missing
|
||||
}
|
||||
|
||||
// onLookup makes fn run right after the n-th lookup of path, as another filer
|
||||
// acting just then would: what that lookup returned is already out of date.
|
||||
func onLookup(store *renameTestStore, path util.FullPath, n int, fn func()) {
|
||||
lookups := 0
|
||||
store.afterFind = func(p util.FullPath) {
|
||||
if p == path {
|
||||
if lookups++; lookups == n {
|
||||
fn()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// newInPlaceRenameStore is a store that says its insert replaces an entry at
|
||||
// once and whole, as the Redis stores do, holding /dir/src.txt.
|
||||
func newInPlaceRenameStore() *renameTestStore {
|
||||
store := newRenameTestStore()
|
||||
store.overwritesAtOnce = true
|
||||
store.entries["/dir"] = newDirectoryEntry("/dir", 100)
|
||||
store.entries["/dir/src.txt"] = fileEntryWithChunk("/dir/src.txt", 101, "1,0a01")
|
||||
return store
|
||||
}
|
||||
|
||||
func renameSrcOverDst(t *testing.T, server *FilerServer) {
|
||||
t.Helper()
|
||||
if _, err := server.AtomicRenameEntry(context.Background(), &filer_pb.AtomicRenameEntryRequest{
|
||||
OldDirectory: "/dir", OldName: "src.txt", NewDirectory: "/dir", NewName: "dst.txt",
|
||||
}); err != nil {
|
||||
t.Fatalf("AtomicRenameEntry: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// checkReplaced: /dir/src.txt is gone and /dir/dst.txt is the renamed file.
|
||||
func checkReplaced(t *testing.T, f *filer.Filer, store *renameTestStore) {
|
||||
t.Helper()
|
||||
if _, err := store.FindEntry(context.Background(), "/dir/src.txt"); err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("source after rename: %v, want %v", err, filer_pb.ErrNotFound)
|
||||
}
|
||||
dst, err := f.FindEntry(context.Background(), "/dir/dst.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("find target: %v", err)
|
||||
}
|
||||
if dst.Attr.Inode != 101 {
|
||||
t.Fatalf("target inode = %d, want the renamed file's 101", dst.Attr.Inode)
|
||||
}
|
||||
if len(dst.HardLinkId) != 0 {
|
||||
t.Fatalf("target still carries hard link id %x", dst.HardLinkId)
|
||||
}
|
||||
if chunks := dst.GetChunks(); len(chunks) != 1 || chunks[0].GetFileIdString() != "1,0a01" {
|
||||
t.Fatalf("target chunks = %v, want the renamed file's 1,0a01", chunks)
|
||||
}
|
||||
}
|
||||
|
||||
// On a store whose insert replaces an entry at once and whole, the target never
|
||||
// goes missing while a file is renamed over it, and subscribers still see the
|
||||
// target's delete, then the rename.
|
||||
func TestAtomicRenameEntryOverwriteKeepsTargetResolvable(t *testing.T) {
|
||||
store := newInPlaceRenameStore()
|
||||
store.entries["/dir/dst.txt"] = fileEntryWithChunk("/dir/dst.txt", 202, "2,0b02")
|
||||
writes, missing := watchTarget(store, "/dir/dst.txt")
|
||||
|
||||
queue := &captureQueue{}
|
||||
swapNotificationQueue(t, queue)
|
||||
f := newRenameTestFiler(t, store)
|
||||
renameSrcOverDst(t, &FilerServer{filer: f, entryLockTable: util.NewLockTable[util.FullPath]()})
|
||||
|
||||
if len(*missing) != 0 {
|
||||
t.Fatalf("target missing after writes %v (all writes %v)", *missing, *writes)
|
||||
}
|
||||
checkReplaced(t, f, store)
|
||||
if got := queuedDeletions(f); len(got) != 1 || got[0] != "2,0b02" {
|
||||
t.Fatalf("queued chunk deletions = %v, want the replaced file's 2,0b02", got)
|
||||
}
|
||||
events := queue.snapshot()
|
||||
if len(events) != 2 || events[0].key != "/dir/dst.txt" || events[0].notification.NewEntry != nil ||
|
||||
!events[0].notification.DeleteChunks || events[1].key != "/dir/src.txt" ||
|
||||
events[1].notification.NewEntry.GetName() != "dst.txt" {
|
||||
t.Fatalf("events = %+v, want the target's delete then the rename", events)
|
||||
}
|
||||
}
|
||||
|
||||
type inPlaceRenameStream struct {
|
||||
grpc.ServerStream
|
||||
sent []*filer_pb.StreamRenameEntryResponse
|
||||
}
|
||||
|
||||
func (s *inPlaceRenameStream) Context() context.Context { return context.Background() }
|
||||
func (s *inPlaceRenameStream) Send(resp *filer_pb.StreamRenameEntryResponse) error {
|
||||
s.sent = append(s.sent, resp)
|
||||
return nil
|
||||
}
|
||||
|
||||
// weed mount renames through StreamRenameEntry.
|
||||
func TestStreamRenameEntryOverwriteKeepsTargetResolvable(t *testing.T) {
|
||||
store := newInPlaceRenameStore()
|
||||
store.entries["/dir/dst.txt"] = fileEntryWithChunk("/dir/dst.txt", 202, "2,0b02")
|
||||
writes, missing := watchTarget(store, "/dir/dst.txt")
|
||||
|
||||
swapNotificationQueue(t, &captureQueue{})
|
||||
f := newRenameTestFiler(t, store)
|
||||
server := &FilerServer{filer: f, entryLockTable: util.NewLockTable[util.FullPath]()}
|
||||
stream := &inPlaceRenameStream{}
|
||||
if err := server.StreamRenameEntry(&filer_pb.StreamRenameEntryRequest{
|
||||
OldDirectory: "/dir", OldName: "src.txt", NewDirectory: "/dir", NewName: "dst.txt",
|
||||
}, stream); err != nil {
|
||||
t.Fatalf("StreamRenameEntry: %v", err)
|
||||
}
|
||||
|
||||
if len(*missing) != 0 {
|
||||
t.Fatalf("target missing after writes %v (all writes %v)", *missing, *writes)
|
||||
}
|
||||
checkReplaced(t, f, store)
|
||||
if len(stream.sent) != 2 || stream.sent[0].EventNotification.NewEntry.GetName() != "dst.txt" {
|
||||
t.Fatalf("stream responses = %+v, want the rename then the source removal", stream.sent)
|
||||
}
|
||||
}
|
||||
|
||||
// A directory renamed over an empty directory still goes through
|
||||
// delete-then-create: in-place replacement is for files only.
|
||||
func TestAtomicRenameEntryDirectoryOverEmptyDirectory(t *testing.T) {
|
||||
store := newRenameTestStore()
|
||||
store.overwritesAtOnce = true
|
||||
store.entries["/a"] = newDirectoryEntry("/a", 10)
|
||||
store.entries["/a/f.txt"] = newFileEntry("/a/f.txt", 11)
|
||||
store.entries["/b"] = newDirectoryEntry("/b", 20)
|
||||
|
||||
swapNotificationQueue(t, &captureQueue{})
|
||||
f := newRenameTestFiler(t, store)
|
||||
server := &FilerServer{filer: f, entryLockTable: util.NewLockTable[util.FullPath]()}
|
||||
if _, err := server.AtomicRenameEntry(context.Background(), &filer_pb.AtomicRenameEntryRequest{
|
||||
OldDirectory: "/", OldName: "a", NewDirectory: "/", NewName: "b",
|
||||
}); err != nil {
|
||||
t.Fatalf("AtomicRenameEntry: %v", err)
|
||||
}
|
||||
for _, p := range []string{"/a", "/a/f.txt"} {
|
||||
if _, err := store.FindEntry(context.Background(), util.FullPath(p)); err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("%s after rename: %v, want %v", p, err, filer_pb.ErrNotFound)
|
||||
}
|
||||
}
|
||||
b, err := store.FindEntry(context.Background(), "/b")
|
||||
if err != nil || b.Attr.Inode != 10 {
|
||||
t.Fatalf("/b = %+v, %v; want the renamed directory (inode 10)", b, err)
|
||||
}
|
||||
if _, err := store.FindEntry(context.Background(), "/b/f.txt"); err != nil {
|
||||
t.Fatalf("/b/f.txt: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Another filer deletes the target right after this filer looked it up. The
|
||||
// renamed file must still be stored at the target and listed in its
|
||||
// directory: on Redis an update after that delete would store it unlisted.
|
||||
func TestAtomicRenameEntryOverATargetDeletedMeanwhile(t *testing.T) {
|
||||
store := newInPlaceRenameStore()
|
||||
store.entries["/dir/dst.txt"] = fileEntryWithChunk("/dir/dst.txt", 202, "2,0b02")
|
||||
store.listing = map[string]bool{"/dir/src.txt": true, "/dir/dst.txt": true}
|
||||
onLookup(store, "/dir/dst.txt", 1, func() {
|
||||
if err := store.DeleteEntry(context.Background(), "/dir/dst.txt"); err != nil {
|
||||
t.Errorf("delete the target as another filer: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
swapNotificationQueue(t, &captureQueue{})
|
||||
f := newRenameTestFiler(t, store)
|
||||
renameSrcOverDst(t, &FilerServer{filer: f, entryLockTable: util.NewLockTable[util.FullPath]()})
|
||||
|
||||
checkReplaced(t, f, store)
|
||||
if !store.listing["/dir/dst.txt"] || store.listing["/dir/src.txt"] {
|
||||
t.Fatalf("listing = %v, want dst.txt listed and src.txt gone", store.listing)
|
||||
}
|
||||
// the rename saw the target, so it queued the target's chunks
|
||||
if got := queuedDeletions(f); len(got) != 1 || got[0] != "2,0b02" {
|
||||
t.Fatalf("queued chunk deletions = %v, want the target's 2,0b02", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A store that does not say its insert replaces an entry keeps
|
||||
// delete-then-create: with transactions nothing else sees the target missing
|
||||
// before the commit, and an insert over an existing row can abort one
|
||||
// (Postgres); without them, the insert may leave part of the old row in place.
|
||||
func TestAtomicRenameEntryOverwriteOnOtherStoresDeletesThenCreates(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
strictTx bool
|
||||
}{
|
||||
{"without transactions", false},
|
||||
{"with transactions", true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
store := newInPlaceRenameStore()
|
||||
store.overwritesAtOnce = false
|
||||
store.strictTx = tc.strictTx
|
||||
store.entries["/dir/dst.txt"] = fileEntryWithChunk("/dir/dst.txt", 202, "2,0b02")
|
||||
writes, _ := watchTarget(store, "/dir/dst.txt")
|
||||
|
||||
swapNotificationQueue(t, &captureQueue{})
|
||||
f := newRenameTestFiler(t, store)
|
||||
renameSrcOverDst(t, &FilerServer{filer: f, entryLockTable: util.NewLockTable[util.FullPath]()})
|
||||
|
||||
if want := []string{"delete /dir/dst.txt", "insert /dir/dst.txt", "delete /dir/src.txt"}; !reflect.DeepEqual(*writes, want) {
|
||||
t.Fatalf("store writes = %v, want %v", *writes, want)
|
||||
}
|
||||
checkReplaced(t, f, store)
|
||||
if got := queuedDeletions(f); len(got) != 1 || got[0] != "2,0b02" {
|
||||
t.Fatalf("queued chunk deletions = %v, want the replaced file's 2,0b02", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A target in a path-specific store keeps delete-then-create: what the default
|
||||
// store says of its insert does not hold for that store. A path-specific store
|
||||
// elsewhere changes nothing for a rename within the default store.
|
||||
func TestAtomicRenameEntryOverwriteWithPathSpecificStore(t *testing.T) {
|
||||
t.Run("holding the target", func(t *testing.T) {
|
||||
store := newInPlaceRenameStore()
|
||||
store.entries["/dir/sub"] = newDirectoryEntry("/dir/sub", 110)
|
||||
writes, _ := watchTarget(store, "/dir/src.txt")
|
||||
// the store for /dir/sub/ keeps its entries by their path under it;
|
||||
// even one that says the same of its insert is not asked
|
||||
subStore := newRenameTestStore()
|
||||
subStore.overwritesAtOnce = true
|
||||
subStore.entries["/dst.txt"] = fileEntryWithChunk("/dst.txt", 202, "2,0b02")
|
||||
subWrites, _ := watchTarget(subStore, "/dst.txt")
|
||||
|
||||
swapNotificationQueue(t, &captureQueue{})
|
||||
f := newRenameTestFiler(t, store)
|
||||
f.Store.(*filer.FilerStoreWrapper).AddPathSpecificStore("/dir/sub/", "sub", subStore)
|
||||
server := &FilerServer{filer: f, entryLockTable: util.NewLockTable[util.FullPath]()}
|
||||
if _, err := server.AtomicRenameEntry(context.Background(), &filer_pb.AtomicRenameEntryRequest{
|
||||
OldDirectory: "/dir", OldName: "src.txt", NewDirectory: "/dir/sub", NewName: "dst.txt",
|
||||
}); err != nil {
|
||||
t.Fatalf("AtomicRenameEntry: %v", err)
|
||||
}
|
||||
|
||||
if want := []string{"delete /dst.txt", "insert /dst.txt"}; !reflect.DeepEqual(*subWrites, want) {
|
||||
t.Fatalf("writes to the target's store = %v, want %v", *subWrites, want)
|
||||
}
|
||||
if want := []string{"delete /dir/src.txt"}; !reflect.DeepEqual(*writes, want) {
|
||||
t.Fatalf("writes to the default store = %v, want %v", *writes, want)
|
||||
}
|
||||
dst, err := f.FindEntry(context.Background(), "/dir/sub/dst.txt")
|
||||
if err != nil || dst.Attr.Inode != 101 {
|
||||
t.Fatalf("/dir/sub/dst.txt = %+v, %v; want the renamed file (inode 101)", dst, err)
|
||||
}
|
||||
})
|
||||
t.Run("elsewhere", func(t *testing.T) {
|
||||
store := newInPlaceRenameStore()
|
||||
store.entries["/dir/dst.txt"] = fileEntryWithChunk("/dir/dst.txt", 202, "2,0b02")
|
||||
writes, missing := watchTarget(store, "/dir/dst.txt")
|
||||
|
||||
swapNotificationQueue(t, &captureQueue{})
|
||||
f := newRenameTestFiler(t, store)
|
||||
f.Store.(*filer.FilerStoreWrapper).AddPathSpecificStore("/archive/", "archive", newRenameTestStore())
|
||||
renameSrcOverDst(t, &FilerServer{filer: f, entryLockTable: util.NewLockTable[util.FullPath]()})
|
||||
|
||||
if len(*missing) != 0 {
|
||||
t.Fatalf("target missing after writes %v (all writes %v)", *missing, *writes)
|
||||
}
|
||||
checkReplaced(t, f, store)
|
||||
})
|
||||
}
|
||||
|
||||
// The in-place write over a hard-linked target takes that name off its file:
|
||||
// the file's chunks stay while another name holds them, and go with its last
|
||||
// name.
|
||||
func TestAtomicRenameEntryInPlaceOverHardLink(t *testing.T) {
|
||||
for _, links := range []int32{2, 1} {
|
||||
t.Run(map[int32]string{2: "one of two links", 1: "the last link"}[links], func(t *testing.T) {
|
||||
store := newInPlaceRenameStore()
|
||||
id := hardLinkedTarget(t, store, links)
|
||||
writes, missing := watchTarget(store, "/dir/dst.txt")
|
||||
|
||||
swapNotificationQueue(t, &captureQueue{})
|
||||
f := newRenameTestFiler(t, store)
|
||||
renameSrcOverDst(t, &FilerServer{filer: f, entryLockTable: util.NewLockTable[util.FullPath]()})
|
||||
|
||||
if len(*missing) != 0 {
|
||||
t.Fatalf("target missing after writes %v (all writes %v)", *missing, *writes)
|
||||
}
|
||||
checkReplaced(t, f, store)
|
||||
_, recordKept := store.kv[string(id)]
|
||||
if links == 2 {
|
||||
if got := queuedDeletions(f); len(got) != 0 {
|
||||
t.Fatalf("queued chunk deletions = %v, want none: /dir/other.txt still uses %s", got, replacedChunk)
|
||||
}
|
||||
if other, err := f.FindEntry(context.Background(), "/dir/other.txt"); err != nil || other.HardLinkCounter != 1 {
|
||||
t.Fatalf("/dir/other.txt = %+v, %v; want it with a link count of 1", other, err)
|
||||
}
|
||||
if !recordKept {
|
||||
t.Fatal("hard link record deleted while a link remains")
|
||||
}
|
||||
} else {
|
||||
if got := queuedDeletions(f); len(got) != 1 || got[0] != replacedChunk {
|
||||
t.Fatalf("queued chunk deletions = %v, want the last link's %s", got, replacedChunk)
|
||||
}
|
||||
if recordKept {
|
||||
t.Fatal("hard link record kept after its last link was replaced")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Another filer unlinks the target's other hard link after this filer read
|
||||
// the link count (2), but before its write drops the target's link. No link is
|
||||
// left then, so the file's chunks must go.
|
||||
func TestAtomicRenameEntryOverHardLinkWhoseOtherLinkGoesMeanwhile(t *testing.T) {
|
||||
store := newInPlaceRenameStore()
|
||||
id := hardLinkedTarget(t, store, 2)
|
||||
|
||||
swapNotificationQueue(t, &captureQueue{})
|
||||
f := newRenameTestFiler(t, store)
|
||||
// lookup 1 of the target is the rename's own; lookup 2 comes from the
|
||||
// store write, just before it drops the target's link
|
||||
onLookup(store, "/dir/dst.txt", 2, func() {
|
||||
if err := f.Store.DeleteEntry(context.Background(), "/dir/other.txt"); err != nil {
|
||||
t.Errorf("unlink the other link as another filer: %v", err)
|
||||
}
|
||||
})
|
||||
renameSrcOverDst(t, &FilerServer{filer: f, entryLockTable: util.NewLockTable[util.FullPath]()})
|
||||
|
||||
checkReplaced(t, f, store)
|
||||
if got := queuedDeletions(f); len(got) != 1 || got[0] != replacedChunk {
|
||||
t.Fatalf("queued chunk deletions = %v, want %s: no link to it is left", got, replacedChunk)
|
||||
}
|
||||
if _, found := store.kv[string(id)]; found {
|
||||
t.Fatal("hard link record kept after its last link was replaced")
|
||||
}
|
||||
}
|
||||
|
||||
// Another filer turns the target into a directory right after this filer
|
||||
// looked it up, by storing a child under it. Writing the renamed file over it
|
||||
// would strand the child, so the rename is refused, as it is when the lookup
|
||||
// already finds a directory.
|
||||
func TestAtomicRenameEntryOverATargetThatBecameADirectory(t *testing.T) {
|
||||
store := newInPlaceRenameStore()
|
||||
store.entries["/dir/dst.txt"] = fileEntryWithChunk("/dir/dst.txt", 202, "2,0b02")
|
||||
onLookup(store, "/dir/dst.txt", 1, func() {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
store.entries["/dir/dst.txt"] = newDirectoryEntry("/dir/dst.txt", 202)
|
||||
store.entries["/dir/dst.txt/child"] = fileEntryWithChunk("/dir/dst.txt/child", 203, "4,0d04")
|
||||
})
|
||||
|
||||
queue := &captureQueue{}
|
||||
swapNotificationQueue(t, queue)
|
||||
f := newRenameTestFiler(t, store)
|
||||
server := &FilerServer{filer: f, entryLockTable: util.NewLockTable[util.FullPath]()}
|
||||
_, err := server.AtomicRenameEntry(context.Background(), &filer_pb.AtomicRenameEntryRequest{
|
||||
OldDirectory: "/dir", OldName: "src.txt", NewDirectory: "/dir", NewName: "dst.txt",
|
||||
})
|
||||
if !errors.Is(err, filer_pb.ErrExistingIsDirectory) && (err == nil || !strings.Contains(err.Error(), filer_pb.ErrExistingIsDirectory.Error())) {
|
||||
t.Fatalf("AtomicRenameEntry = %v, want %v", err, filer_pb.ErrExistingIsDirectory)
|
||||
}
|
||||
if dst, err := store.FindEntry(context.Background(), "/dir/dst.txt"); err != nil || !dst.IsDirectory() {
|
||||
t.Fatalf("/dir/dst.txt = %+v, %v; want the directory left as it is", dst, err)
|
||||
}
|
||||
if _, err := store.FindEntry(context.Background(), "/dir/dst.txt/child"); err != nil {
|
||||
t.Fatalf("the directory's child: %v", err)
|
||||
}
|
||||
if _, err := store.FindEntry(context.Background(), "/dir/src.txt"); err != nil {
|
||||
t.Fatalf("source after the refused rename: %v", err)
|
||||
}
|
||||
if got := queuedDeletions(f); len(got) != 0 {
|
||||
t.Fatalf("queued chunk deletions = %v for a rename that did not happen", got)
|
||||
}
|
||||
if events := queue.snapshot(); len(events) != 0 {
|
||||
t.Fatalf("events = %+v for a rename that did not happen", events)
|
||||
}
|
||||
}
|
||||
|
||||
// Another filer deletes the target and its directory right after this filer
|
||||
// looked the target up. The renamed file must not be left under a directory
|
||||
// that does not exist: the directory is created again, as a create does, and
|
||||
// announced before the rename.
|
||||
func TestAtomicRenameEntryOverATargetWhoseDirectoryWentMeanwhile(t *testing.T) {
|
||||
store := newInPlaceRenameStore()
|
||||
store.entries["/dir/sub"] = newDirectoryEntry("/dir/sub", 300)
|
||||
store.entries["/dir/sub/dst.txt"] = fileEntryWithChunk("/dir/sub/dst.txt", 202, "2,0b02")
|
||||
onLookup(store, "/dir/sub/dst.txt", 1, func() {
|
||||
for _, p := range []util.FullPath{"/dir/sub/dst.txt", "/dir/sub"} {
|
||||
if err := store.DeleteEntry(context.Background(), p); err != nil {
|
||||
t.Errorf("delete %s as another filer: %v", p, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
queue := &captureQueue{}
|
||||
swapNotificationQueue(t, queue)
|
||||
f := newRenameTestFiler(t, store)
|
||||
server := &FilerServer{filer: f, entryLockTable: util.NewLockTable[util.FullPath]()}
|
||||
if _, err := server.AtomicRenameEntry(context.Background(), &filer_pb.AtomicRenameEntryRequest{
|
||||
OldDirectory: "/dir", OldName: "src.txt", NewDirectory: "/dir/sub", NewName: "dst.txt",
|
||||
}); err != nil {
|
||||
t.Fatalf("AtomicRenameEntry: %v", err)
|
||||
}
|
||||
|
||||
if dir, err := store.FindEntry(context.Background(), "/dir/sub"); err != nil || !dir.IsDirectory() {
|
||||
t.Fatalf("/dir/sub = %+v, %v; want the directory created again", dir, err)
|
||||
}
|
||||
if dst, err := store.FindEntry(context.Background(), "/dir/sub/dst.txt"); err != nil || dst.Attr.Inode != 101 {
|
||||
t.Fatalf("/dir/sub/dst.txt = %+v, %v; want the renamed file (inode 101)", dst, err)
|
||||
}
|
||||
if _, err := store.FindEntry(context.Background(), "/dir/src.txt"); err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("source after rename: %v, want %v", err, filer_pb.ErrNotFound)
|
||||
}
|
||||
createdAt, renamedAt := -1, -1
|
||||
for i, event := range queue.snapshot() {
|
||||
switch {
|
||||
case event.notification.OldEntry == nil && event.notification.NewEntry.GetName() == "sub":
|
||||
createdAt = i
|
||||
case event.notification.OldEntry.GetName() == "src.txt" && event.notification.NewEntry.GetName() == "dst.txt":
|
||||
renamedAt = i
|
||||
}
|
||||
}
|
||||
if createdAt < 0 || renamedAt < 0 || createdAt > renamedAt {
|
||||
t.Fatalf("events = %+v, want /dir/sub's create before the rename", queue.snapshot())
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,23 @@ type renameTestStore struct {
|
||||
|
||||
kv map[string][]byte // optional KV (hard links); nil: every key is absent
|
||||
kvGetErrs int // fail this many KvGet calls before answering
|
||||
|
||||
afterOp func(op string, p util.FullPath) // optional: runs after each insert, update or delete
|
||||
afterFind func(p util.FullPath) // optional: runs after each lookup
|
||||
listing map[string]bool // optional: directory listing kept the way Redis keeps it
|
||||
|
||||
overwritesAtOnce bool // declares filer.OverwritingStore, as the Redis stores do
|
||||
}
|
||||
|
||||
// OverwritesAtOnce is what the store declares; its InsertEntry does replace an
|
||||
// entry at once and whole either way.
|
||||
func (s *renameTestStore) OverwritesAtOnce() bool { return s.overwritesAtOnce }
|
||||
|
||||
// noteOp runs the afterOp hook after a write, outside the store's lock.
|
||||
func (s *renameTestStore) noteOp(op string, p util.FullPath) {
|
||||
if s.afterOp != nil {
|
||||
s.afterOp(op, p)
|
||||
}
|
||||
}
|
||||
|
||||
type renameTestTxKey struct{}
|
||||
@@ -131,18 +148,24 @@ func (s *renameTestStore) InsertEntry(ctx context.Context, entry *filer.Entry) e
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.entries[string(entry.FullPath)] = entry.ShallowClone()
|
||||
if s.listing != nil {
|
||||
s.listing[string(entry.FullPath)] = true
|
||||
}
|
||||
s.mu.Unlock()
|
||||
s.noteOp("insert", entry.FullPath)
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateEntry rewrites the entry and leaves the listing alone, as Redis does.
|
||||
func (s *renameTestStore) UpdateEntry(ctx context.Context, entry *filer.Entry) error {
|
||||
if err := s.txDone(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.entries[string(entry.FullPath)] = entry.ShallowClone()
|
||||
s.mu.Unlock()
|
||||
s.noteOp("update", entry.FullPath)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -153,6 +176,9 @@ func (s *renameTestStore) FindEntry(ctx context.Context, p util.FullPath) (*file
|
||||
if s.findDelay > 0 {
|
||||
time.Sleep(s.findDelay)
|
||||
}
|
||||
if s.afterFind != nil {
|
||||
defer s.afterFind(p)
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.findCalls[string(p)]++
|
||||
@@ -174,8 +200,12 @@ func (s *renameTestStore) DeleteEntry(ctx context.Context, p util.FullPath) erro
|
||||
return s.deleteErr
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
delete(s.entries, string(p))
|
||||
if s.listing != nil {
|
||||
delete(s.listing, string(p))
|
||||
}
|
||||
s.mu.Unlock()
|
||||
s.noteOp("delete", p)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,14 @@ type EcVolume struct {
|
||||
Shards []*EcVolumeShard
|
||||
ShardLocations map[ShardId][]pb.ServerAddress
|
||||
ShardLocationsRefreshTime time.Time
|
||||
// ShardReadHints keeps the holders a complete lookup stopped placing a shard
|
||||
// on. Reads ask them before reconstructing, for a delete only such a holder
|
||||
// journaled, but take nothing else from them: a delete made since went to a
|
||||
// listed holder, which reconstruction asks. Deletes never use them.
|
||||
ShardReadHints map[ShardId][]pb.ServerAddress
|
||||
// ShardReadHintsRevision changes with every change to ShardReadHints, so a
|
||||
// read only forgets the hint holders it asked if no lookup changed them.
|
||||
ShardReadHintsRevision uint64
|
||||
// ShardLocationsStale marks the map for a prompt re-check: a read that failed
|
||||
// against a cached location has disproved what the map claims, and the normal
|
||||
// freshness window is far too long to serve from a map known to be wrong.
|
||||
|
||||
+114
-10
@@ -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
|
||||
@@ -722,8 +739,14 @@ func (s *Store) readOneEcShardInterval(needleId types.NeedleId, ecVolume *erasur
|
||||
|
||||
ecVolume.ShardLocationsLock.RLock()
|
||||
sourceDataNodes, hasShardIdLocation := ecVolume.ShardLocations[shardId]
|
||||
readHints := ecVolume.ShardReadHints[shardId]
|
||||
readHintsRevision := ecVolume.ShardReadHintsRevision
|
||||
ecVolume.ShardLocationsLock.RUnlock()
|
||||
|
||||
if !hasShardIdLocation && len(readHints) > 0 && s.askEcShardReadHints(needleId, ecVolume, shardId, readHints, readHintsRevision, data[:1], actualOffset) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// try reading directly
|
||||
if hasShardIdLocation {
|
||||
_, is_deleted, err = s.readRemoteEcShardInterval(sourceDataNodes, needleId, ecVolume.VolumeId, shardId, data, actualOffset, ecVolume.EncodeTsNs)
|
||||
@@ -1182,13 +1205,52 @@ func (s *Store) cachedLookupEcShardLocations(ecVolume *erasure_coding.EcVolume)
|
||||
if err != nil {
|
||||
return fmt.Errorf("lookup ec volume %d: %v", ecVolume.VolumeId, err)
|
||||
}
|
||||
if len(resp.ShardIdLocations) < ecCtx.DataShards {
|
||||
return fmt.Errorf("only %d shards found but %d required", len(resp.ShardIdLocations), ecCtx.DataShards)
|
||||
// The master answers every shard slot it tracks; only the shards it
|
||||
// places on a server count toward a usable map.
|
||||
located := 0
|
||||
for _, shardIdLocations := range resp.ShardIdLocations {
|
||||
if len(shardIdLocations.Locations) > 0 {
|
||||
located++
|
||||
}
|
||||
}
|
||||
if located < ecCtx.DataShards {
|
||||
// Too few to trust as the volume's map, but a read can still go
|
||||
// straight to a shard it names: put those holders first, keep the
|
||||
// cached ones as fallback, and leave the refresh time alone.
|
||||
ecVolume.ShardLocationsLock.Lock()
|
||||
for _, shardIdLocations := range resp.ShardIdLocations {
|
||||
if len(shardIdLocations.Locations) == 0 {
|
||||
continue
|
||||
}
|
||||
shardId := erasure_coding.ShardId(shardIdLocations.ShardId)
|
||||
var holders []pb.ServerAddress
|
||||
for _, loc := range shardIdLocations.Locations {
|
||||
holders = append(holders, pb.NewServerAddressFromLocation(loc))
|
||||
}
|
||||
for _, known := range ecVolume.ShardLocations[shardId] {
|
||||
if !slices.Contains(holders, known) {
|
||||
holders = append(holders, known)
|
||||
}
|
||||
}
|
||||
ecVolume.ShardLocations[shardId] = holders
|
||||
}
|
||||
ecVolume.ShardLocationsLock.Unlock()
|
||||
return fmt.Errorf("only %d shards found but %d required", located, ecCtx.DataShards)
|
||||
}
|
||||
|
||||
ecVolume.ShardLocationsLock.Lock()
|
||||
for _, shardIdLocations := range resp.ShardIdLocations {
|
||||
shardId := erasure_coding.ShardId(shardIdLocations.ShardId)
|
||||
if _, hinted := ecVolume.ShardReadHints[shardId]; hinted && len(shardIdLocations.Locations) > 0 {
|
||||
delete(ecVolume.ShardReadHints, shardId)
|
||||
ecVolume.ShardReadHintsRevision++
|
||||
} else if known := ecVolume.ShardLocations[shardId]; len(known) > 0 && len(shardIdLocations.Locations) == 0 {
|
||||
if ecVolume.ShardReadHints == nil {
|
||||
ecVolume.ShardReadHints = make(map[erasure_coding.ShardId][]pb.ServerAddress)
|
||||
}
|
||||
ecVolume.ShardReadHints[shardId] = known
|
||||
ecVolume.ShardReadHintsRevision++
|
||||
}
|
||||
delete(ecVolume.ShardLocations, shardId)
|
||||
for _, loc := range shardIdLocations.Locations {
|
||||
ecVolume.ShardLocations[shardId] = append(ecVolume.ShardLocations[shardId], pb.NewServerAddressFromLocation(loc))
|
||||
@@ -1215,6 +1277,48 @@ func (s *Store) cachedLookupEcShardLocations(ecVolume *erasure_coding.EcVolume)
|
||||
// to peers or reconstruction first.
|
||||
var errShardQuarantined = fmt.Errorf("ec shard on a quarantined disk: %w", errShardNotLocal)
|
||||
|
||||
// ecReadHintTimeout bounds asking a delisted holder, which may have stopped
|
||||
// answering, before the read reconstructs the shard.
|
||||
var ecReadHintTimeout = 5 * time.Second
|
||||
|
||||
// askEcShardReadHints reports whether a delisted holder of the shard journaled
|
||||
// the needle's delete. Each holder is asked, since any one of them may hold the
|
||||
// delete; only a deleted answer is taken, so one byte is enough. Holders that
|
||||
// failed are forgotten, even when a later one answers deleted, unless a lookup
|
||||
// changed the hints meanwhile.
|
||||
func (s *Store) askEcShardReadHints(needleId types.NeedleId, ecVolume *erasure_coding.EcVolume, shardId erasure_coding.ShardId, hints []pb.ServerAddress, revision uint64, probe []byte, offset int64) (deleted bool) {
|
||||
var failed []pb.ServerAddress
|
||||
for _, hint := range hints {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), ecReadHintTimeout)
|
||||
_, isDeleted, err := s.doReadRemoteEcShardInterval(ctx, hint, needleId, ecVolume.VolumeId, shardId, probe, offset, ecVolume.EncodeTsNs)
|
||||
cancel()
|
||||
if err == nil && isDeleted {
|
||||
deleted = true
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
glog.V(1).Infof("read ec shard %d.%d from delisted holder %s: %v", ecVolume.VolumeId, shardId, hint, err)
|
||||
failed = append(failed, hint)
|
||||
}
|
||||
}
|
||||
if len(failed) == 0 {
|
||||
return
|
||||
}
|
||||
ecVolume.ShardLocationsLock.Lock()
|
||||
defer ecVolume.ShardLocationsLock.Unlock()
|
||||
if ecVolume.ShardReadHintsRevision != revision {
|
||||
return
|
||||
}
|
||||
kept := slices.DeleteFunc(slices.Clone(hints), func(hint pb.ServerAddress) bool { return slices.Contains(failed, hint) })
|
||||
if len(kept) == 0 {
|
||||
delete(ecVolume.ShardReadHints, shardId)
|
||||
} else {
|
||||
ecVolume.ShardReadHints[shardId] = kept
|
||||
}
|
||||
ecVolume.ShardReadHintsRevision++
|
||||
return
|
||||
}
|
||||
|
||||
// readLocalEcShardInterval refuses a shard whose disk is quarantined unless
|
||||
// allowQuarantined is set.
|
||||
func (s *Store) readLocalEcShardInterval(ecVolume *erasure_coding.EcVolume, shardId erasure_coding.ShardId, buf []byte, offset int64, allowQuarantined bool) error {
|
||||
@@ -1257,7 +1361,7 @@ func (s *Store) readRemoteEcShardInterval(sourceDataNodes []pb.ServerAddress, ne
|
||||
|
||||
for _, sourceDataNode := range sourceDataNodes {
|
||||
glog.V(3).Infof("read remote ec shard %d.%d from %s", vid, shardId, sourceDataNode)
|
||||
n, is_deleted, err = s.doReadRemoteEcShardInterval(sourceDataNode, needleId, vid, shardId, buf, offset, expectedEncodeTsNs)
|
||||
n, is_deleted, err = s.doReadRemoteEcShardInterval(context.Background(), sourceDataNode, needleId, vid, shardId, buf, offset, expectedEncodeTsNs)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
@@ -1267,12 +1371,12 @@ func (s *Store) readRemoteEcShardInterval(sourceDataNodes []pb.ServerAddress, ne
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Store) doReadRemoteEcShardInterval(sourceDataNode pb.ServerAddress, needleId types.NeedleId, vid needle.VolumeId, shardId erasure_coding.ShardId, buf []byte, offset int64, expectedEncodeTsNs int64) (n int, is_deleted bool, err error) {
|
||||
func (s *Store) doReadRemoteEcShardInterval(ctx context.Context, sourceDataNode pb.ServerAddress, needleId types.NeedleId, vid needle.VolumeId, shardId erasure_coding.ShardId, buf []byte, offset int64, expectedEncodeTsNs int64) (n int, is_deleted bool, err error) {
|
||||
|
||||
err = operation.WithVolumeServerClient(false, sourceDataNode, s.grpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
|
||||
|
||||
// copy data slice
|
||||
shardReadClient, err := client.VolumeEcShardRead(context.Background(), &volume_server_pb.VolumeEcShardReadRequest{
|
||||
shardReadClient, err := client.VolumeEcShardRead(ctx, &volume_server_pb.VolumeEcShardReadRequest{
|
||||
VolumeId: uint32(vid),
|
||||
ShardId: uint32(shardId),
|
||||
Offset: offset,
|
||||
|
||||
@@ -17,8 +17,21 @@ import (
|
||||
|
||||
func (s *Store) DeleteEcShardNeedle(ecVolume *erasure_coding.EcVolume, n *needle.Needle, cookie types.Cookie) (int64, error) {
|
||||
|
||||
needleId := n.Id
|
||||
count, err := s.ReadEcShardNeedle(ecVolume.VolumeId, n, nil)
|
||||
|
||||
if errors.Is(err, ErrorDeleted) {
|
||||
// The read sees one disk's deletion set, and a delete that failed
|
||||
// part way can leave a sibling disk of the holder still live, so
|
||||
// forward again; the holder skips the copies that already record it.
|
||||
// A failed parse can overwrite n.Id, so use the requested id.
|
||||
if _, size, locErr := ecVolume.FindNeedleFromEcx(needleId); locErr == nil && !size.IsDeleted() {
|
||||
if fwdErr := s.doDeleteNeedleFromAtLeastOneRemoteEcShards(ecVolume, needleId); fwdErr != nil {
|
||||
glog.V(1).Infof("re-forward delete of deleted ec needle %d.%s: %v", ecVolume.VolumeId, needleId, fwdErr)
|
||||
}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -3,8 +3,12 @@ package storage
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net"
|
||||
"os"
|
||||
"slices"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -30,6 +34,22 @@ type countingMaster struct {
|
||||
onLookup func()
|
||||
// failLookup answers with an error instead of a shard map.
|
||||
failLookup atomic.Bool
|
||||
// located, when set, answers every shard slot as the master does but
|
||||
// places only the first located shards on a server.
|
||||
located atomic.Int64
|
||||
// partialPort is the port of the server those shards are placed on; 0 is 1.
|
||||
partialPort atomic.Int64
|
||||
}
|
||||
|
||||
func partialLocation(port int64) *master_pb.Location {
|
||||
if port == 0 {
|
||||
port = 1
|
||||
}
|
||||
return &master_pb.Location{Url: fmt.Sprintf("127.0.0.1:%d", port), GrpcPort: 2}
|
||||
}
|
||||
|
||||
func partialHolder(port int64) pb.ServerAddress {
|
||||
return pb.NewServerAddressFromLocation(partialLocation(port))
|
||||
}
|
||||
|
||||
func (m *countingMaster) LookupEcVolume(_ context.Context, req *master_pb.LookupEcVolumeRequest) (*master_pb.LookupEcVolumeResponse, error) {
|
||||
@@ -41,6 +61,16 @@ func (m *countingMaster) LookupEcVolume(_ context.Context, req *master_pb.Lookup
|
||||
return nil, status.Error(codes.Unavailable, "master is having a moment")
|
||||
}
|
||||
resp := &master_pb.LookupEcVolumeResponse{VolumeId: req.VolumeId}
|
||||
if located := int(m.located.Load()); located > 0 {
|
||||
for shardId := 0; shardId < erasure_coding.MaxShardCount; shardId++ {
|
||||
entry := &master_pb.LookupEcVolumeResponse_EcShardIdLocation{ShardId: uint32(shardId)}
|
||||
if shardId < located {
|
||||
entry.Locations = []*master_pb.Location{partialLocation(m.partialPort.Load())}
|
||||
}
|
||||
resp.ShardIdLocations = append(resp.ShardIdLocations, entry)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
for shardId := 0; shardId < erasure_coding.TotalShardsCount; shardId++ {
|
||||
resp.ShardIdLocations = append(resp.ShardIdLocations, &master_pb.LookupEcVolumeResponse_EcShardIdLocation{
|
||||
ShardId: uint32(shardId),
|
||||
@@ -152,6 +182,97 @@ func TestCachedLookupEcShardLocationsSettlesAfterRefresh(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The master answers every shard slot, so a reply naming 32 shards can still
|
||||
// place fewer than the data shards on a server, as while several holders are
|
||||
// down. That reply is a partial and must leave a complete cache as it was.
|
||||
func TestCachedLookupEcShardLocationsRefusesAReplyWithFewLocatedShards(t *testing.T) {
|
||||
master, masterAddr := startCountingMaster(t)
|
||||
store := &Store{
|
||||
MasterFn: func() pb.ServerAddress { return masterAddr },
|
||||
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
ecVolume := &erasure_coding.EcVolume{
|
||||
VolumeId: 9,
|
||||
ShardLocations: make(map[erasure_coding.ShardId][]pb.ServerAddress),
|
||||
}
|
||||
if err := store.cachedLookupEcShardLocations(ecVolume); err != nil {
|
||||
t.Fatalf("first lookup: %v", err)
|
||||
}
|
||||
|
||||
master.located.Store(7)
|
||||
master.partialPort.Store(3)
|
||||
rewindShardLocationsRefresh(ecVolume, 12*time.Second)
|
||||
ecVolume.ShardLocationsLock.Lock()
|
||||
ecVolume.ShardLocationsStale = true
|
||||
refreshedAt := ecVolume.ShardLocationsRefreshTime
|
||||
ecVolume.ShardLocationsLock.Unlock()
|
||||
if err := store.cachedLookupEcShardLocations(ecVolume); err == nil {
|
||||
t.Error("a reply placing 7 of 14 shards was accepted")
|
||||
}
|
||||
ecVolume.ShardLocationsLock.RLock()
|
||||
cached := len(ecVolume.ShardLocations)
|
||||
named := ecVolume.ShardLocations[0]
|
||||
unnamed := ecVolume.ShardLocations[7]
|
||||
refreshed := ecVolume.ShardLocationsRefreshTime
|
||||
ecVolume.ShardLocationsLock.RUnlock()
|
||||
if cached != erasure_coding.TotalShardsCount {
|
||||
t.Errorf("the cache holds %d shards after the partial reply, want all %d kept", cached, erasure_coding.TotalShardsCount)
|
||||
}
|
||||
if want := []pb.ServerAddress{partialHolder(3), partialHolder(1)}; !slices.Equal(named, want) {
|
||||
t.Errorf("a shard the partial reply places holds %v, want its new holder first and the cached one kept: %v", named, want)
|
||||
}
|
||||
if want := []pb.ServerAddress{partialHolder(1)}; !slices.Equal(unnamed, want) {
|
||||
t.Errorf("a shard the partial reply places nowhere holds %v, want its cached %v", unnamed, want)
|
||||
}
|
||||
if !refreshed.Equal(refreshedAt) {
|
||||
t.Errorf("the partial reply moved the refresh time from %v to %v", refreshedAt, refreshed)
|
||||
}
|
||||
}
|
||||
|
||||
// A partial reply is no map to trust, but the cache takes the holders it names,
|
||||
// so a read can still go straight to a shard whose holder is up, including one
|
||||
// that moved while the replies stayed partial.
|
||||
func TestCachedLookupEcShardLocationsFillsAColdCacheFromAPartialReply(t *testing.T) {
|
||||
master, masterAddr := startCountingMaster(t)
|
||||
master.located.Store(7)
|
||||
store := &Store{
|
||||
MasterFn: func() pb.ServerAddress { return masterAddr },
|
||||
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
ecVolume := &erasure_coding.EcVolume{
|
||||
VolumeId: 9,
|
||||
ShardLocations: make(map[erasure_coding.ShardId][]pb.ServerAddress),
|
||||
}
|
||||
if err := store.cachedLookupEcShardLocations(ecVolume); err == nil {
|
||||
t.Error("a reply placing 7 of 14 shards was accepted")
|
||||
}
|
||||
ecVolume.ShardLocationsLock.RLock()
|
||||
cached := len(ecVolume.ShardLocations)
|
||||
refreshed := !ecVolume.ShardLocationsRefreshTime.IsZero()
|
||||
stale := ecVolume.ShardLocationsStale
|
||||
ecVolume.ShardLocationsLock.RUnlock()
|
||||
if cached != 7 {
|
||||
t.Errorf("the cold cache holds %d shards after the partial reply, want the 7 it placed", cached)
|
||||
}
|
||||
if refreshed || !stale {
|
||||
t.Errorf("a partial reply must leave the map due a lookup: refreshed=%v stale=%v", refreshed, stale)
|
||||
}
|
||||
|
||||
master.partialPort.Store(4)
|
||||
if err := store.cachedLookupEcShardLocations(ecVolume); err == nil {
|
||||
t.Error("a second reply placing 7 of 14 shards was accepted")
|
||||
}
|
||||
if got := master.lookups.Load(); got != 2 {
|
||||
t.Fatalf("asked the master %d times, want 2: a partial reply leaves the map due", got)
|
||||
}
|
||||
ecVolume.ShardLocationsLock.RLock()
|
||||
moved := ecVolume.ShardLocations[0]
|
||||
ecVolume.ShardLocationsLock.RUnlock()
|
||||
if want := []pb.ServerAddress{partialHolder(4), partialHolder(1)}; !slices.Equal(moved, want) {
|
||||
t.Errorf("after the shard moved, the cache holds %v, want %v", moved, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEcShardLocationsTTL(t *testing.T) {
|
||||
ecCtx := erasure_coding.NewDefaultECContext("", 1)
|
||||
for _, tc := range []struct {
|
||||
@@ -328,3 +449,234 @@ func TestCachedLookupEcShardLocationsKeepsTheMarkWhenTheLookupFails(t *testing.T
|
||||
t.Errorf("asked the master %d times, want 3: a failed lookup must not leave the disproved map trusted", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A complete reply that places a shard nowhere takes it out of the map a delete
|
||||
// routes by, but its former holder stays a place a read can ask first.
|
||||
func TestCachedLookupEcShardLocationsKeepsADelistedHolderForReads(t *testing.T) {
|
||||
const delisted = erasure_coding.ShardId(13)
|
||||
master, masterAddr := startCountingMaster(t)
|
||||
master.located.Store(13)
|
||||
store := &Store{
|
||||
MasterFn: func() pb.ServerAddress { return masterAddr },
|
||||
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
ecVolume := &erasure_coding.EcVolume{
|
||||
VolumeId: 9,
|
||||
ShardLocations: map[erasure_coding.ShardId][]pb.ServerAddress{delisted: {partialHolder(5)}},
|
||||
}
|
||||
if err := store.cachedLookupEcShardLocations(ecVolume); err != nil {
|
||||
t.Fatalf("lookup: %v", err)
|
||||
}
|
||||
ecVolume.ShardLocationsLock.RLock()
|
||||
_, listed := ecVolume.ShardLocations[delisted]
|
||||
hints := maps.Clone(ecVolume.ShardReadHints)
|
||||
ecVolume.ShardLocationsLock.RUnlock()
|
||||
if listed {
|
||||
t.Error("shard 13 is still in the map after the master placed it nowhere")
|
||||
}
|
||||
if want := map[erasure_coding.ShardId][]pb.ServerAddress{delisted: {partialHolder(5)}}; !maps.EqualFunc(hints, want, slices.Equal) {
|
||||
t.Errorf("read hints %v, want %v", hints, want)
|
||||
}
|
||||
if err := store.doDeleteNeedleFromRemoteEcShardServers(delisted, ecVolume, 1); !errors.Is(err, errEcShardMissing) {
|
||||
t.Errorf("a delete for shard 13 got %v, want it routed elsewhere", err)
|
||||
}
|
||||
|
||||
master.located.Store(14)
|
||||
rewindShardLocationsRefresh(ecVolume, time.Hour)
|
||||
if err := store.cachedLookupEcShardLocations(ecVolume); err != nil {
|
||||
t.Fatalf("second lookup: %v", err)
|
||||
}
|
||||
ecVolume.ShardLocationsLock.RLock()
|
||||
_, hinted := ecVolume.ShardReadHints[delisted]
|
||||
ecVolume.ShardLocationsLock.RUnlock()
|
||||
if hinted {
|
||||
t.Error("the read hint outlived the master placing shard 13 again")
|
||||
}
|
||||
}
|
||||
|
||||
// deletedNeedlePeer answers every shard read as the holder that journaled the
|
||||
// needle's delete.
|
||||
type deletedNeedlePeer struct {
|
||||
volume_server_pb.UnimplementedVolumeServerServer
|
||||
}
|
||||
|
||||
func (deletedNeedlePeer) VolumeEcShardRead(req *volume_server_pb.VolumeEcShardReadRequest, stream volume_server_pb.VolumeServer_VolumeEcShardReadServer) error {
|
||||
return stream.Send(&volume_server_pb.VolumeEcShardReadResponse{IsDeleted: true, EncodeTsNs: req.EncodeTsNs})
|
||||
}
|
||||
|
||||
// The other shards rebuild a delisted shard's bytes but know nothing of a delete
|
||||
// its holder journaled, so a read asks that holder before rebuilding.
|
||||
func TestReadOneEcShardIntervalAsksADelistedHolderBeforeRebuilding(t *testing.T) {
|
||||
const delisted = erasure_coding.ShardId(3)
|
||||
baseFileName, n := writeEcVolumeFiles(t, t.TempDir(), 7)
|
||||
others := startEcShardPeer(t, &oneBadShardPeer{baseFileName: baseFileName, badShard: delisted})
|
||||
live := startEcShardPeer(t, &oneBadShardPeer{baseFileName: baseFileName, badShard: 13})
|
||||
journaled := startEcShardPeer(t, deletedNeedlePeer{})
|
||||
|
||||
store := &Store{grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials())}
|
||||
ecVolume := &erasure_coding.EcVolume{
|
||||
VolumeId: 7,
|
||||
ShardLocations: make(map[erasure_coding.ShardId][]pb.ServerAddress),
|
||||
}
|
||||
seedShardLocations(ecVolume, others)
|
||||
delete(ecVolume.ShardLocations, delisted)
|
||||
ecVolume.ShardReadHints = map[erasure_coding.ShardId][]pb.ServerAddress{delisted: {live, journaled}}
|
||||
|
||||
interval := erasure_coding.Interval{BlockIndex: int(delisted), Size: 4096, IsLargeBlock: true}
|
||||
got := make([]byte, interval.Size)
|
||||
isDeleted, err := store.readOneEcShardInterval(n.Id, ecVolume, interval, got)
|
||||
if err != nil || !isDeleted {
|
||||
t.Fatalf("read interval: deleted=%v err=%v, want the delisted holder's delete after another answered live", isDeleted, err)
|
||||
}
|
||||
|
||||
// A holder that failed before another answered deleted is dropped all the same.
|
||||
ecVolume.ShardReadHints[delisted] = []pb.ServerAddress{others, journaled}
|
||||
isDeleted, err = store.readOneEcShardInterval(n.Id, ecVolume, interval, got)
|
||||
if err != nil || !isDeleted {
|
||||
t.Fatalf("read interval: deleted=%v err=%v, want the delete after a failed holder", isDeleted, err)
|
||||
}
|
||||
ecVolume.ShardLocationsLock.RLock()
|
||||
hints := slices.Clone(ecVolume.ShardReadHints[delisted])
|
||||
ecVolume.ShardLocationsLock.RUnlock()
|
||||
if want := []pb.ServerAddress{journaled}; !slices.Equal(hints, want) {
|
||||
t.Errorf("read hints %v, want only the holder that answered %v", hints, want)
|
||||
}
|
||||
|
||||
// A holder that no longer answers is dropped, and the read rebuilds the shard.
|
||||
ecVolume.ShardReadHints[delisted] = []pb.ServerAddress{others, live}
|
||||
isDeleted, err = store.readOneEcShardInterval(n.Id, ecVolume, interval, got)
|
||||
if err != nil || isDeleted {
|
||||
t.Fatalf("read interval: deleted=%v err=%v, want it rebuilt", isDeleted, err)
|
||||
}
|
||||
ecVolume.ShardLocationsLock.RLock()
|
||||
hints = ecVolume.ShardReadHints[delisted]
|
||||
ecVolume.ShardLocationsLock.RUnlock()
|
||||
if want := []pb.ServerAddress{live}; !slices.Equal(hints, want) {
|
||||
t.Errorf("read hints %v, want only the holder that answered %v", hints, want)
|
||||
}
|
||||
want := make([]byte, len(got))
|
||||
f, err := os.Open(baseFileName + erasure_coding.ToExt(int(delisted)))
|
||||
if err != nil {
|
||||
t.Fatalf("open shard %d: %v", delisted, err)
|
||||
}
|
||||
defer f.Close()
|
||||
if _, err := f.ReadAt(want, 0); err != nil {
|
||||
t.Fatalf("read shard %d: %v", delisted, err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Error("the rebuilt interval does not match the shard on disk")
|
||||
}
|
||||
}
|
||||
|
||||
// A delete made after the delisting went to a listed holder, so the delisted
|
||||
// holder still answers live; the read must not take that answer over the
|
||||
// reconstruction that asks the listed holders.
|
||||
func TestReadOneEcShardIntervalDoesNotTakeALiveAnswerFromADelistedHolder(t *testing.T) {
|
||||
const delisted = erasure_coding.ShardId(3)
|
||||
baseFileName, n := writeEcVolumeFiles(t, t.TempDir(), 7)
|
||||
live := startEcShardPeer(t, &oneBadShardPeer{baseFileName: baseFileName, badShard: 13})
|
||||
journaled := startEcShardPeer(t, deletedNeedlePeer{})
|
||||
|
||||
store := &Store{grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials())}
|
||||
ecVolume := &erasure_coding.EcVolume{
|
||||
VolumeId: 7,
|
||||
ShardLocations: map[erasure_coding.ShardId][]pb.ServerAddress{0: {journaled}},
|
||||
ShardReadHints: map[erasure_coding.ShardId][]pb.ServerAddress{delisted: {live}},
|
||||
}
|
||||
for shardId := erasure_coding.ShardId(4); shardId < 13; shardId++ {
|
||||
ecVolume.ShardLocations[shardId] = []pb.ServerAddress{live}
|
||||
}
|
||||
ecVolume.ShardLocationsRefreshTime = time.Now()
|
||||
|
||||
interval := erasure_coding.Interval{BlockIndex: int(delisted), Size: 4096, IsLargeBlock: true}
|
||||
isDeleted, err := store.readOneEcShardInterval(n.Id, ecVolume, interval, make([]byte, interval.Size))
|
||||
if !isDeleted {
|
||||
t.Fatalf("read interval: deleted=%v err=%v, want the listed holder's delete", isDeleted, err)
|
||||
}
|
||||
ecVolume.ShardLocationsLock.RLock()
|
||||
_, hinted := ecVolume.ShardReadHints[delisted]
|
||||
ecVolume.ShardLocationsLock.RUnlock()
|
||||
if !hinted {
|
||||
t.Error("a read hint that answered was dropped")
|
||||
}
|
||||
}
|
||||
|
||||
// stalledPeer accepts a shard read and never answers it.
|
||||
type stalledPeer struct {
|
||||
volume_server_pb.UnimplementedVolumeServerServer
|
||||
}
|
||||
|
||||
func (stalledPeer) VolumeEcShardRead(req *volume_server_pb.VolumeEcShardReadRequest, stream volume_server_pb.VolumeServer_VolumeEcShardReadServer) error {
|
||||
<-stream.Context().Done()
|
||||
return stream.Context().Err()
|
||||
}
|
||||
|
||||
// hintReplacingPeer fails a read after a lookup has changed the hint it used.
|
||||
type hintReplacingPeer struct {
|
||||
volume_server_pb.UnimplementedVolumeServerServer
|
||||
replace func()
|
||||
}
|
||||
|
||||
func (p hintReplacingPeer) VolumeEcShardRead(req *volume_server_pb.VolumeEcShardReadRequest, stream volume_server_pb.VolumeServer_VolumeEcShardReadServer) error {
|
||||
p.replace()
|
||||
return status.Error(codes.Unavailable, "holder went away")
|
||||
}
|
||||
|
||||
// A delisted holder that stops answering costs a read only the hint's deadline,
|
||||
// and a failed hinted read leaves a hint a lookup installed meanwhile, even one
|
||||
// naming the same holder.
|
||||
func TestReadOneEcShardIntervalBoundsAndScopesAFailedReadHint(t *testing.T) {
|
||||
const delisted = erasure_coding.ShardId(3)
|
||||
baseFileName, n := writeEcVolumeFiles(t, t.TempDir(), 7)
|
||||
others := startEcShardPeer(t, &oneBadShardPeer{baseFileName: baseFileName, badShard: delisted})
|
||||
stalled := startEcShardPeer(t, stalledPeer{})
|
||||
|
||||
store := &Store{grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials())}
|
||||
ecVolume := &erasure_coding.EcVolume{
|
||||
VolumeId: 7,
|
||||
ShardLocations: make(map[erasure_coding.ShardId][]pb.ServerAddress),
|
||||
}
|
||||
seedShardLocations(ecVolume, others)
|
||||
delete(ecVolume.ShardLocations, delisted)
|
||||
ecVolume.ShardReadHints = map[erasure_coding.ShardId][]pb.ServerAddress{delisted: {stalled}}
|
||||
defer func(old time.Duration) { ecReadHintTimeout = old }(ecReadHintTimeout)
|
||||
ecReadHintTimeout = 200 * time.Millisecond
|
||||
|
||||
interval := erasure_coding.Interval{BlockIndex: int(delisted), Size: 4096, IsLargeBlock: true}
|
||||
read := func() {
|
||||
t.Helper()
|
||||
if isDeleted, err := store.readOneEcShardInterval(n.Id, ecVolume, interval, make([]byte, interval.Size)); err != nil || isDeleted {
|
||||
t.Fatalf("read interval: deleted=%v err=%v, want it rebuilt", isDeleted, err)
|
||||
}
|
||||
}
|
||||
hint := func() []pb.ServerAddress {
|
||||
ecVolume.ShardLocationsLock.RLock()
|
||||
defer ecVolume.ShardLocationsLock.RUnlock()
|
||||
return ecVolume.ShardReadHints[delisted]
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
read()
|
||||
if elapsed := time.Since(start); elapsed > 5*time.Second {
|
||||
t.Errorf("the read waited %v on a holder that never answers", elapsed)
|
||||
}
|
||||
if got := hint(); got != nil {
|
||||
t.Errorf("a hint that timed out is still kept: %v", got)
|
||||
}
|
||||
|
||||
var replacing pb.ServerAddress
|
||||
replacing = startEcShardPeer(t, hintReplacingPeer{replace: func() {
|
||||
// The master places the shard on this holder again, then nowhere.
|
||||
ecVolume.ShardLocationsLock.Lock()
|
||||
delete(ecVolume.ShardReadHints, delisted)
|
||||
ecVolume.ShardReadHintsRevision++
|
||||
ecVolume.ShardReadHints[delisted] = []pb.ServerAddress{replacing}
|
||||
ecVolume.ShardReadHintsRevision++
|
||||
ecVolume.ShardLocationsLock.Unlock()
|
||||
}})
|
||||
ecVolume.ShardReadHints[delisted] = []pb.ServerAddress{replacing}
|
||||
read()
|
||||
if got, want := hint(), []pb.ServerAddress{replacing}; !slices.Equal(got, want) {
|
||||
t.Errorf("read hint %v, want the reinstalled %v kept", got, want)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"math/rand"
|
||||
"net"
|
||||
"os"
|
||||
@@ -362,3 +363,58 @@ func TestReadEcShardNeedleAnswersDeletedWhenRecoveryFallsShort(t *testing.T) {
|
||||
t.Errorf("read a deleted needle returned %v, want %v", err, ErrorDeleted)
|
||||
}
|
||||
}
|
||||
|
||||
// partlyDeletedEcShardPeer reports the needle deleted on its shard reads and
|
||||
// counts the deletes forwarded to it.
|
||||
type partlyDeletedEcShardPeer struct {
|
||||
deletingEcShardPeer
|
||||
deletes atomic.Int64
|
||||
fileKey atomic.Uint64
|
||||
}
|
||||
|
||||
func (p *partlyDeletedEcShardPeer) VolumeEcBlobDelete(ctx context.Context, req *volume_server_pb.VolumeEcBlobDeleteRequest) (*volume_server_pb.VolumeEcBlobDeleteResponse, error) {
|
||||
p.deletes.Add(1)
|
||||
p.fileKey.Store(req.FileKey)
|
||||
return &volume_server_pb.VolumeEcBlobDeleteResponse{}, nil
|
||||
}
|
||||
|
||||
// A holder whose delete stopped part way reports the needle deleted from the
|
||||
// disk that recorded it, so a retry still forwards the delete for the rest.
|
||||
func TestDeleteEcShardNeedleForwardsWhenReadSaysDeleted(t *testing.T) {
|
||||
store := newTestStore(t, 1)
|
||||
store.grpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
const vid = needle.VolumeId(8)
|
||||
_, n := writeEcVolumeFiles(t, store.Locations[0].Directory, vid)
|
||||
for shardId := 1; shardId < erasure_coding.TotalShardsCount; shardId++ {
|
||||
if err := store.MountEcShards("", vid, erasure_coding.ShardId(shardId), ""); err != nil {
|
||||
t.Fatalf("mount shard %d: %v", shardId, err)
|
||||
}
|
||||
}
|
||||
ecVolume, found := store.Locations[0].FindEcVolume(vid)
|
||||
if !found {
|
||||
t.Fatal("ec volume not mounted")
|
||||
}
|
||||
|
||||
peer := &partlyDeletedEcShardPeer{}
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
srv := grpc.NewServer()
|
||||
volume_server_pb.RegisterVolumeServerServer(srv, peer)
|
||||
go srv.Serve(lis)
|
||||
t.Cleanup(srv.Stop)
|
||||
seedShardLocations(ecVolume, pb.NewServerAddressWithGrpcPort("127.0.0.1:1", lis.Addr().(*net.TCPAddr).Port))
|
||||
|
||||
got := new(needle.Needle)
|
||||
got.Id = n.Id
|
||||
if _, err := store.DeleteEcShardNeedle(ecVolume, got, n.Cookie); err != ErrorDeleted {
|
||||
t.Fatalf("delete of a needle read as deleted returned %v, want %v", err, ErrorDeleted)
|
||||
}
|
||||
if peer.deletes.Load() != 1 {
|
||||
t.Errorf("forwarded %d deletes to the holder, want 1", peer.deletes.Load())
|
||||
}
|
||||
if got := types.NeedleId(peer.fileKey.Load()); got != n.Id {
|
||||
t.Errorf("forwarded the delete of needle %s, want %s", got, n.Id)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
var (
|
||||
MAJOR_VERSION = int32(4)
|
||||
MINOR_VERSION = int32(54)
|
||||
MINOR_VERSION = int32(55)
|
||||
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
|
||||
VERSION = util.SizeLimit + " " + VERSION_NUMBER
|
||||
COMMIT = ""
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user