mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cbeaa63e2e | ||
|
|
31fd0b834e | ||
|
|
a604414363 | ||
|
|
1e0244dfc8 | ||
|
|
55fe8bf947 | ||
|
|
2dbc5263bc | ||
|
|
d674199290 | ||
|
|
e23c665523 | ||
|
|
190aa130e2 |
No files matched your search
@@ -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),
|
||||
}
|
||||
}
|
||||
@@ -714,8 +712,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 +1232,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 +1278,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))
|
||||
}
|
||||
|
||||
@@ -1344,6 +1353,23 @@ 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) = shard_read_hints(state, vid, shard_id)
|
||||
{
|
||||
match read_remote_ec_shard_interval(state, &hints, iv).await {
|
||||
Ok(read) => return Ok(read),
|
||||
Err(e) => {
|
||||
tracing::debug!(
|
||||
"read ec shard {}.{} from delisted holders {:?} failed: {}",
|
||||
vid.0,
|
||||
shard_id,
|
||||
hints,
|
||||
e
|
||||
);
|
||||
forget_shard_read_hints(state, vid, shard_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Direct peer read against the cached locations for this shard.
|
||||
if let Some(sources) = map.locations.get(&shard_id)
|
||||
&& !sources.is_empty()
|
||||
@@ -1828,6 +1854,22 @@ async fn recover_one_remote_ec_shard_interval(
|
||||
}
|
||||
}
|
||||
|
||||
fn shard_read_hints(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
shard_id: ShardId,
|
||||
) -> Option<Vec<String>> {
|
||||
let store = state.store.read().unwrap();
|
||||
store.find_ec_volume(vid)?.shard_read_hints(shard_id)
|
||||
}
|
||||
|
||||
fn forget_shard_read_hints(state: &Arc<VolumeServerState>, vid: VolumeId, shard_id: ShardId) {
|
||||
let store = state.store.read().unwrap();
|
||||
if let Some(ecv) = store.find_ec_volume(vid) {
|
||||
ecv.forget_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 +2824,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()]))
|
||||
|
||||
@@ -31,6 +31,11 @@ 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`). Only reads consult them, before reconstructing: such a
|
||||
/// holder may still answer, and may be the one that journaled a delete.
|
||||
/// Deletes never do.
|
||||
read_hints: HashMap<ShardId, Vec<String>>,
|
||||
/// 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
|
||||
@@ -1726,10 +1731,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 +1745,48 @@ 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);
|
||||
}
|
||||
} else {
|
||||
cache.read_hints.remove(&shard_id);
|
||||
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 +1797,19 @@ impl EcVolume {
|
||||
(cache.locations.clone(), cache.refreshed_at)
|
||||
}
|
||||
|
||||
pub(crate) fn shard_read_hints(&self, shard_id: ShardId) -> Option<Vec<String>> {
|
||||
let cache = self.shard_locations.read().unwrap();
|
||||
cache.read_hints.get(&shard_id).cloned()
|
||||
}
|
||||
|
||||
pub(crate) fn forget_shard_read_hints(&self, shard_id: ShardId) {
|
||||
self.shard_locations
|
||||
.write()
|
||||
.unwrap()
|
||||
.read_hints
|
||||
.remove(&shard_id);
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
@@ -5448,6 +5503,59 @@ 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()])]));
|
||||
assert_eq!(vol.shard_read_hints(0), Some(vec!["a:1".to_string()]));
|
||||
vol.merge_shard_locations(HashMap::from([(0, Vec::new())]));
|
||||
assert_eq!(
|
||||
vol.shard_read_hints(0),
|
||||
Some(vec!["a:1".to_string()]),
|
||||
"a later reply placing the shard nowhere keeps the hint"
|
||||
);
|
||||
vol.merge_shard_locations(HashMap::from([(0, vec!["d:4".to_string()])]));
|
||||
assert_eq!(vol.shard_read_hints(0), None);
|
||||
vol.merge_shard_locations(HashMap::from([(0, Vec::new())]));
|
||||
vol.forget_shard_read_hints(0);
|
||||
assert_eq!(vol.shard_read_hints(0), None);
|
||||
}
|
||||
|
||||
#[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:
|
||||
|
||||
@@ -61,6 +61,10 @@ 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. Only reads consult them, before reconstructing: such a holder may still
|
||||
// answer, and may be the one that journaled a delete. Deletes never do.
|
||||
ShardReadHints map[ShardId][]pb.ServerAddress
|
||||
// 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.
|
||||
|
||||
@@ -722,8 +722,20 @@ func (s *Store) readOneEcShardInterval(needleId types.NeedleId, ecVolume *erasur
|
||||
|
||||
ecVolume.ShardLocationsLock.RLock()
|
||||
sourceDataNodes, hasShardIdLocation := ecVolume.ShardLocations[shardId]
|
||||
readHints := ecVolume.ShardReadHints[shardId]
|
||||
ecVolume.ShardLocationsLock.RUnlock()
|
||||
|
||||
if !hasShardIdLocation && len(readHints) > 0 {
|
||||
_, is_deleted, err = s.readRemoteEcShardInterval(readHints, needleId, ecVolume.VolumeId, shardId, data, actualOffset, ecVolume.EncodeTsNs)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
glog.V(1).Infof("read ec shard %d.%d from delisted holders %v: %v", ecVolume.VolumeId, shardId, readHints, err)
|
||||
ecVolume.ShardLocationsLock.Lock()
|
||||
delete(ecVolume.ShardReadHints, shardId)
|
||||
ecVolume.ShardLocationsLock.Unlock()
|
||||
}
|
||||
|
||||
// try reading directly
|
||||
if hasShardIdLocation {
|
||||
_, is_deleted, err = s.readRemoteEcShardInterval(sourceDataNodes, needleId, ecVolume.VolumeId, shardId, data, actualOffset, ecVolume.EncodeTsNs)
|
||||
@@ -1182,13 +1194,50 @@ 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 len(shardIdLocations.Locations) > 0 {
|
||||
delete(ecVolume.ShardReadHints, shardId)
|
||||
} else if known := ecVolume.ShardLocations[shardId]; len(known) > 0 {
|
||||
if ecVolume.ShardReadHints == nil {
|
||||
ecVolume.ShardReadHints = make(map[erasure_coding.ShardId][]pb.ServerAddress)
|
||||
}
|
||||
ecVolume.ShardReadHints[shardId] = known
|
||||
}
|
||||
delete(ecVolume.ShardLocations, shardId)
|
||||
for _, loc := range shardIdLocations.Locations {
|
||||
ecVolume.ShardLocations[shardId] = append(ecVolume.ShardLocations[shardId], pb.NewServerAddressFromLocation(loc))
|
||||
|
||||
@@ -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,107 @@ 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})
|
||||
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: {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", isDeleted, err)
|
||||
}
|
||||
|
||||
// A hint that no longer answers is dropped, and the read rebuilds the shard.
|
||||
ecVolume.ShardReadHints[delisted] = []pb.ServerAddress{others}
|
||||
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()
|
||||
_, hinted := ecVolume.ShardReadHints[delisted]
|
||||
ecVolume.ShardLocationsLock.RUnlock()
|
||||
if hinted {
|
||||
t.Error("a read hint that failed is still kept")
|
||||
}
|
||||
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")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user