From aeca7a9a8a99007884fd5f7bc6d1a9ff831b16a8 Mon Sep 17 00:00:00 2001 From: mattia-eleuteri <104386589+mattia-eleuteri@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:05:54 +0100 Subject: [PATCH] master: keep writes available when the replica placement cannot be satisfied (#13178) * master: keep writes available when the replica placement cannot be satisfied With a placement such as 200 on exactly three data centers, losing one data center stops all writes: every volume misses a copy and leaves the writable list, and volume growth cannot find three data centers. Add master.replication.degraded_growth_min_copies (0 = off). When the topology no longer has enough data centers, racks or servers for a placement, the master grows volumes with fewer copies, never below that number. A lack of free space never triggers it. These volumes keep the requested placement in their super block and are writable while the master flags them as degraded; lookups report the copies they need, so volume servers accept writes to them. Once the topology can hold the placement again the flag is cleared: they turn read-only until volume.fix.replication adds the missing copies. The flag is in memory only, so a master restart has the same safe effect. Refs #13177 Co-Authored-By: Claude Opus 5.5 * master: tighten degraded volume growth after review - A degraded volume is writable only with exactly the copies it was grown with: losing one turns it read-only, so a copy that comes back has missed no write, and it is not writable before all its copies are registered. - Use the first relaxed placement the topology can hold and stop there when it lacks free slots, so full disks never drop more copies. - Try every relaxed placement, ordered by copies, then data centers, then racks (011 can fall back to 010, not only 001). - Data nodes in maintenance mode do not count when checking the topology. Co-Authored-By: Claude Opus 5.5 * master: tie degraded writability to the original servers - A degraded volume is writable only on exactly the servers it was grown on: a replacement copy no longer stands in for a missing original one. - Lookups report the degraded copy count only in that exact state, so a volume server never relaxes its check when the layout would not. - When a relaxed placement fails to find slots, try the other placements with as many copies (for example in the requested data center) before giving up, still never dropping copies for lack of space. Co-Authored-By: Claude Opus 5.5 * seaweed-volume: copy min_writable_copies into the master.proto copy Co-Authored-By: Claude Opus 5.5 * seaweed-volume: let a degraded volume replicate with the master's min_writable_copies Mirrors getRemoteReplications: lookup_volume also returns the lookup's min_writable_copies, and do_replicated_request uses it instead of the placement's copy count when it is lower. Co-Authored-By: Claude Opus 5.5 * seaweed-volume: test the degraded replicated write through the admin router Co-Authored-By: Claude Opus 5.5 * master: grow degraded volumes without a setting Degraded growth no longer needs master.replication.degraded_growth_min_copies: it always applies when the topology cannot hold a placement, never below two copies. Lookups skip the degraded scan until a volume was grown degraded. Co-Authored-By: Claude Opus 5.5 * master: leave refused servers out of the degraded slot search findDegradedSlots cleared option.refused, so a retry could pick the server that just refused the allocation. Search without the refused servers first and fall back to them only when nothing else fits, as findAndGrow does. Co-Authored-By: Claude Opus 5.5 * master: document that a degraded volume losing every copy stays read-only Co-Authored-By: Claude Opus 5.5 * admin: warn about under-replicated and misplaced volumes on the dashboard The dashboard health line now counts the volumes volume.fix.replication would repair, using the same placement checks, so volumes grown degraded while a data center is down show up until they are repaired. Co-Authored-By: Claude Opus 5.5 * master: spread degraded copies over racks and servers when data centers are missing A 200 volume with a single data center left found no degraded placement: only per-dimension reductions were tried, and 100 needs two data centers. Try every placement with fewer copies and no more data centers, so the remaining copies go to other racks or servers. Co-Authored-By: Claude Opus 5.5 * master: report min_writable_copies only for the locations it is returned with LookupVolume read the locations and the degraded minimum in two steps, so a replica set change in between could pair the minimum with locations it does not hold for. Count the minimum only when the returned locations are exactly the servers the volume was grown on. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Chris Lu --- seaweed-volume/proto/master.proto | 3 + seaweed-volume/src/server/handlers.rs | 90 +++++- weed/admin/dash/admin_data.go | 6 + weed/admin/dash/cluster_topology.go | 1 + weed/admin/dash/replica_health.go | 50 +++ weed/admin/dash/replica_health_test.go | 46 +++ weed/admin/dash/types.go | 4 + weed/admin/view/app/admin_render_test.go | 4 +- weed/admin/view/app/dashboard_health.go | 6 + weed/operation/lookup.go | 5 + weed/pb/master.proto | 3 + weed/pb/master_pb/master.pb.go | 21 +- weed/server/master_grpc_server_volume.go | 15 +- weed/topology/store_replicate.go | 4 + weed/topology/topology.go | 1 + weed/topology/topology_event_handling.go | 1 + weed/topology/volume_growth.go | 23 +- weed/topology/volume_growth_degraded.go | 243 +++++++++++++++ weed/topology/volume_growth_degraded_test.go | 306 +++++++++++++++++++ weed/topology/volume_layout.go | 10 +- 20 files changed, 819 insertions(+), 23 deletions(-) create mode 100644 weed/admin/dash/replica_health.go create mode 100644 weed/admin/dash/replica_health_test.go create mode 100644 weed/topology/volume_growth_degraded.go create mode 100644 weed/topology/volume_growth_degraded_test.go diff --git a/seaweed-volume/proto/master.proto b/seaweed-volume/proto/master.proto index b10cba2bfd..51a3161ebf 100644 --- a/seaweed-volume/proto/master.proto +++ b/seaweed-volume/proto/master.proto @@ -289,6 +289,9 @@ message LookupVolumeResponse { repeated Location locations = 2; string error = 3; string auth = 4; + // > 0 when the volume was grown degraded: a write needs this many + // writable copies instead of its replica placement's copy count. + uint32 min_writable_copies = 5; } repeated VolumeIdLocation volume_id_locations = 1; } diff --git a/seaweed-volume/src/server/handlers.rs b/seaweed-volume/src/server/handlers.rs index ecfde57b46..0a9fe3d80c 100644 --- a/seaweed-volume/src/server/handlers.rs +++ b/seaweed-volume/src/server/handlers.rs @@ -577,12 +577,13 @@ async fn master_lookup_once( /// Look up volume locations over the master's gRPC port, like Go's /// operation.LookupVolumeIds: the master's HTTP port need not speak the -/// `[https.client]` scheme. +/// `[https.client]` scheme. Also returns the master's min_writable_copies +/// (0 unless the volume was grown degraded). async fn lookup_volume( tls: Option<&OutgoingGrpcTlsConfig>, master_url: &str, volume_id: u32, -) -> Result, String> { +) -> Result<(Vec, u32), String> { let grpc_addr = parse_grpc_address(master_url)?; let cached = MASTER_LOOKUP_CHANNEL .lock() @@ -618,15 +619,17 @@ async fn lookup_volume( } }; let mut locations = Vec::new(); + let mut min_writable_copies = 0; for found in resp.volume_id_locations { // Mirror Go: a per-volume error in an answered lookup (e.g. a missing // volume) means "no locations"; only a failed call is an error. if !found.error.is_empty() { tracing::debug!("volume {} lookup: {}", volume_id, found.error); } + min_writable_copies = min_writable_copies.max(found.min_writable_copies); locations.extend(found.locations.into_iter().map(VolumeLocation::from)); } - Ok(locations) + Ok((locations, min_writable_copies)) } fn grpc_address_for_location(location: &VolumeLocation) -> Result { @@ -678,7 +681,7 @@ async fn batch_delete_file_ids( let locations = if let Some(locations) = lookup_cache.get(&volume_id) { locations.clone() } else { - let locations = lookup_volume( + let (locations, _) = lookup_volume( state.outgoing_grpc_tls.as_ref(), &state.current_master().await, volume_id, @@ -828,7 +831,7 @@ async fn do_replicated_request( body: Option, replica_jwt: Option<&ReplicaJwt>, ) -> Result<(), String> { - let locations = lookup_volume( + let (locations, min_writable_copies) = lookup_volume( state.outgoing_grpc_tls.as_ref(), &state.current_master().await, vid, @@ -839,9 +842,15 @@ async fn do_replicated_request( let copy_count = { let store = state.store.read().unwrap(); store.find_volume(VolumeId(vid)).map_or(1, |(_, v)| { - v.super_block().replica_placement.get_copy_count() + v.super_block().replica_placement.get_copy_count() as u32 }) }; + // A degraded volume is writable with fewer copies, like Go's + // getRemoteReplications. + let copy_count = match min_writable_copies { + n if n > 0 && n < copy_count => n, + _ => copy_count, + }; let allow_delete = method == axum::http::Method::DELETE; let eligible_locations: Vec<_> = locations .into_iter() @@ -1009,7 +1018,7 @@ async fn proxy_or_redirect_to_target( ) .await { - Ok(locs) => locs, + Ok((locs, _)) => locs, Err(e) => { tracing::warn!("volume lookup failed for {}: {}", vid.0, e); // Go: master lookup failure is 500 in proxy mode, 404 for redirect @@ -4927,7 +4936,7 @@ async fn read_remote_chunk_needle( fid: &str, how: RemoteRead, ) -> Result { - let locations = lookup_volume( + let (locations, _) = lookup_volume( state.outgoing_grpc_tls.as_ref(), &state.current_master().await, vid.0, @@ -5485,6 +5494,67 @@ mod tests { } } + /// A volume grown degraded keeps its placement's copy count in the super + /// block; the master's min_writable_copies lets it write with fewer. + #[tokio::test] + async fn http_replicated_write_uses_the_master_min_writable_copies() { + use crate::storage::super_block::ReplicaPlacement; + use tower::ServiceExt; + + let app = axum::Router::new().fallback(|| async { StatusCode::CREATED }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let peer = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + for (min_writable_copies, written) in [(0, false), (2, true), (3, false)] { + let tmp = tempfile::TempDir::new().unwrap(); + let mut state = volume_test_state(&tmp); + Arc::get_mut(&mut state).unwrap().self_url = "127.0.0.1:8080".to_string(); + state + .store + .read() + .unwrap() + .find_volume(VolumeId(1)) + .unwrap() + .1 + .set_replica_placement(ReplicaPlacement::from_string("200").unwrap()) + .unwrap(); + *state.current_master_url.write().await = spawn_lookup_master(move |vid| { + let location = |url: String| master_pb::Location { + url, + ..Default::default() + }; + let mut answer = lookup_answer( + vid, + vec![ + location("127.0.0.1:8080".to_string()), + location(peer.to_string()), + ], + "", + ); + answer.volume_id_locations[0].min_writable_copies = min_writable_copies; + Ok(answer) + }) + .await; + + let response = super::super::volume_server::build_admin_router(state) + .oneshot( + Request::builder() + .method(Method::POST) + .uri(format!("/1,{:x}{TEST_COOKIE:08x}", 0x6e7a_0c04u64)) + .body(Body::from("x")) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + response.status() == StatusCode::CREATED, + written, + "{min_writable_copies}: {}", + response.status() + ); + } + } + /// A write forward carries a JWT signed for it, not the incoming one, which /// can expire while the body streams in. #[tokio::test] @@ -6420,7 +6490,7 @@ mod tests { .await; for _ in 0..2 { - let locations = super::lookup_volume(None, &master_url, 31) + let (locations, _) = super::lookup_volume(None, &master_url, 31) .await .expect("lookup over the master's gRPC port"); assert_eq!(locations.len(), 1); @@ -6471,7 +6541,7 @@ mod tests { }) .await; - let locations = super::lookup_volume(None, &master_url, 7) + let (locations, _) = super::lookup_volume(None, &master_url, 7) .await .expect("missing volume is not a lookup failure"); assert!(locations.is_empty()); diff --git a/weed/admin/dash/admin_data.go b/weed/admin/dash/admin_data.go index 770c58d23d..50b50585a6 100644 --- a/weed/admin/dash/admin_data.go +++ b/weed/admin/dash/admin_data.go @@ -56,6 +56,9 @@ type AdminData struct { // VersionSummary reports whether all cluster nodes run the same binary // version, so the dashboard can warn about partially upgraded clusters. VersionSummary ClusterVersionSummary `json:"version_summary"` + + UnderReplicatedVolumes int `json:"under_replicated_volumes"` + MisplacedVolumes int `json:"misplaced_volumes"` } // Object Store Users management structures @@ -261,6 +264,9 @@ func (s *AdminServer) GetAdminData(username string) (AdminData, error) { Trends: s.GetDashboardTrends(), TierStats: topology.TierStats, VersionSummary: buildClusterVersionSummary(volumeServersData.VolumeServers, filerNodes, s3Nodes, messageBrokers), + + UnderReplicatedVolumes: topology.UnderReplicatedVolumes, + MisplacedVolumes: topology.MisplacedVolumes, } return adminData, nil diff --git a/weed/admin/dash/cluster_topology.go b/weed/admin/dash/cluster_topology.go index 4c95b8a950..1692a571e5 100644 --- a/weed/admin/dash/cluster_topology.go +++ b/weed/admin/dash/cluster_topology.go @@ -251,6 +251,7 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error { topology.TotalChunks = totalCollectionFileCount(resp.TopologyInfo) topology.TierStats = CollectTierStats(resp.TopologyInfo, volumeSizeLimitMb) + topology.UnderReplicatedVolumes, topology.MisplacedVolumes = countReplicaIssues(resp.TopologyInfo) } return nil diff --git a/weed/admin/dash/replica_health.go b/weed/admin/dash/replica_health.go new file mode 100644 index 0000000000..ad690ec900 --- /dev/null +++ b/weed/admin/dash/replica_health.go @@ -0,0 +1,50 @@ +package dash + +import ( + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/master_pb" + "github.com/seaweedfs/seaweedfs/weed/storage/super_block" + "github.com/seaweedfs/seaweedfs/weed/topology/balancer" +) + +// countReplicaIssues counts the volumes volume.fix.replication would repair: +// under-replicated ones, missing a copy or not spread as their placement +// asks, and misplaced ones. +func countReplicaIssues(topologyInfo *master_pb.TopologyInfo) (underReplicated, misplaced int) { + replicas := make(map[uint32][]balancer.Replica) + placements := make(map[uint32]uint32) + for _, dc := range topologyInfo.GetDataCenterInfos() { + for _, rack := range dc.RackInfos { + for _, dn := range rack.DataNodeInfos { + loc := balancer.Location{ + DataCenter: dc.Id, + Rack: rack.Id, + NodeID: dn.Id, + Host: pb.NewServerAddressFromDataNode(dn).ToHost(), + } + for _, disk := range dn.DiskInfos { + for _, v := range disk.VolumeInfos { + if _, found := placements[v.Id]; !found { + placements[v.Id] = v.ReplicaPlacement + } + replicas[v.Id] = append(replicas[v.Id], balancer.Replica{Location: loc}) + } + } + } + } + } + for vid, rs := range replicas { + rp, _ := super_block.NewReplicaPlacementFromByte(byte(placements[vid])) + locs := make([]balancer.Location, len(rs)) + for i, r := range rs { + locs[i] = r.Location + } + switch { + case rp.GetCopyCount() > len(rs) || !balancer.SatisfyReplicaCurrentLocation(rp, locs): + underReplicated++ + case balancer.IsMisplaced(rs, rp): + misplaced++ + } + } + return +} diff --git a/weed/admin/dash/replica_health_test.go b/weed/admin/dash/replica_health_test.go new file mode 100644 index 0000000000..7090348d3d --- /dev/null +++ b/weed/admin/dash/replica_health_test.go @@ -0,0 +1,46 @@ +package dash + +import ( + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb/master_pb" +) + +func TestCountReplicaIssues(t *testing.T) { + node := func(id string, volumes ...*master_pb.VolumeInformationMessage) *master_pb.DataNodeInfo { + return &master_pb.DataNodeInfo{ + Id: id, + Address: id, + DiskInfos: map[string]*master_pb.DiskInfo{"": {VolumeInfos: volumes}}, + } + } + volume := func(id uint32, placement uint32) *master_pb.VolumeInformationMessage { + return &master_pb.VolumeInformationMessage{Id: id, ReplicaPlacement: placement} + } + dc := func(id string, nodes ...*master_pb.DataNodeInfo) *master_pb.DataCenterInfo { + return &master_pb.DataCenterInfo{Id: id, RackInfos: []*master_pb.RackInfo{{Id: "rack1", DataNodeInfos: nodes}}} + } + // placements are stored as their decimal digits: 200, 100, 001 as 1. + topo := &master_pb.TopologyInfo{DataCenterInfos: []*master_pb.DataCenterInfo{ + dc("dc1", + node("10.0.0.11:8080", volume(1, 200), volume(2, 200), volume(3, 100), volume(4, 1), volume(5, 0)), + node("10.0.0.12:8080", volume(4, 1))), + dc("dc2", node("10.0.0.21:8080", volume(1, 200), volume(2, 200), volume(3, 100))), + dc("dc3", node("10.0.0.31:8080", volume(1, 200))), + }} + // volume 1 has its 3 copies; volume 2, grown degraded, misses its dc3 copy. + under, misplaced := countReplicaIssues(topo) + if under != 1 || misplaced != 0 { + t.Fatalf("got %d under-replicated and %d misplaced, want 1 and 0", under, misplaced) + } + + // volume 6 (010) has its two racks, but in two data centers. + dc1 := topo.DataCenterInfos[0].RackInfos[0].DataNodeInfos[0].DiskInfos[""] + dc2 := topo.DataCenterInfos[1].RackInfos[0].DataNodeInfos[0].DiskInfos[""] + dc1.VolumeInfos = append(dc1.VolumeInfos, volume(6, 10)) + dc2.VolumeInfos = append(dc2.VolumeInfos, volume(6, 10)) + under, misplaced = countReplicaIssues(topo) + if under != 1 || misplaced != 1 { + t.Fatalf("got %d under-replicated and %d misplaced, want 1 and 1", under, misplaced) + } +} diff --git a/weed/admin/dash/types.go b/weed/admin/dash/types.go index 1fafb88ff2..9453cab71a 100644 --- a/weed/admin/dash/types.go +++ b/weed/admin/dash/types.go @@ -29,6 +29,10 @@ type ClusterTopology struct { // TierStats breaks volumes and EC shards down by storage tier: local // disk types plus one entry per remote storage holding tiered volumes. TierStats []TierStats `json:"tier_stats"` + // UnderReplicatedVolumes and MisplacedVolumes count the volumes + // volume.fix.replication would repair. + UnderReplicatedVolumes int `json:"under_replicated_volumes"` + MisplacedVolumes int `json:"misplaced_volumes"` } type MasterNode struct { diff --git a/weed/admin/view/app/admin_render_test.go b/weed/admin/view/app/admin_render_test.go index 504d98f0f9..59a3aead46 100644 --- a/weed/admin/view/app/admin_render_test.go +++ b/weed/admin/view/app/admin_render_test.go @@ -75,7 +75,9 @@ func TestClusterHealthSummary(t *testing.T) { degraded := healthy degraded.MasterNodes = []dash.MasterNode{{Address: "m1:9333"}} degraded.DiskUsage = 95 - want := "Needs attention: no master leader, disks 95% full. 2 volume servers and 1 filer reporting, 1 master configured." + degraded.UnderReplicatedVolumes = 3 + degraded.MisplacedVolumes = 1 + want := "Needs attention: no master leader, disks 95% full, 3 volumes under-replicated, 1 volume misplaced. 2 volume servers and 1 filer reporting, 1 master configured." if got := clusterHealthSummary(degraded); got != want { t.Errorf("degraded summary = %q, want %q", got, want) } diff --git a/weed/admin/view/app/dashboard_health.go b/weed/admin/view/app/dashboard_health.go index 17a671363f..bd3c8188e2 100644 --- a/weed/admin/view/app/dashboard_health.go +++ b/weed/admin/view/app/dashboard_health.go @@ -24,6 +24,12 @@ func clusterHealthIssues(data dash.AdminData) []string { issues = append(issues, fmt.Sprintf("disks %d%% full", p)) } } + if data.UnderReplicatedVolumes > 0 { + issues = append(issues, countNoun(data.UnderReplicatedVolumes, "volume")+" under-replicated") + } + if data.MisplacedVolumes > 0 { + issues = append(issues, countNoun(data.MisplacedVolumes, "volume")+" misplaced") + } if data.VersionSummary.Mixed() { issues = append(issues, "mixed server versions") } diff --git a/weed/operation/lookup.go b/weed/operation/lookup.go index 77326a10ac..b59d839756 100644 --- a/weed/operation/lookup.go +++ b/weed/operation/lookup.go @@ -34,6 +34,9 @@ type LookupResult struct { Jwt string `json:"jwt,omitempty"` Error string `json:"error,omitempty"` NotFound bool `json:"-"` + // MinWritableCopies is set for a degraded volume, see + // topology.DegradedMinCopies. + MinWritableCopies int `json:"minWritableCopies,omitempty"` } func (lr *LookupResult) String() string { @@ -164,6 +167,8 @@ func LookupVolumeIdsWithContext(ctx context.Context, masterFn GetMasterFn, grpcD Locations: locations, Jwt: vidLocations.Auth, Error: vidLocations.Error, + + MinWritableCopies: int(vidLocations.MinWritableCopies), } } diff --git a/weed/pb/master.proto b/weed/pb/master.proto index b10cba2bfd..51a3161ebf 100644 --- a/weed/pb/master.proto +++ b/weed/pb/master.proto @@ -289,6 +289,9 @@ message LookupVolumeResponse { repeated Location locations = 2; string error = 3; string auth = 4; + // > 0 when the volume was grown degraded: a write needs this many + // writable copies instead of its replica placement's copy count. + uint32 min_writable_copies = 5; } repeated VolumeIdLocation volume_id_locations = 1; } diff --git a/weed/pb/master_pb/master.pb.go b/weed/pb/master_pb/master.pb.go index 2f6a07af5b..048627aee0 100644 --- a/weed/pb/master_pb/master.pb.go +++ b/weed/pb/master_pb/master.pb.go @@ -4956,8 +4956,11 @@ type LookupVolumeResponse_VolumeIdLocation struct { Locations []*Location `protobuf:"bytes,2,rep,name=locations,proto3" json:"locations,omitempty"` Error string `protobuf:"bytes,3,opt,name=error,proto3" json:"error,omitempty"` Auth string `protobuf:"bytes,4,opt,name=auth,proto3" json:"auth,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // > 0 when the volume was grown degraded: a write needs this many + // writable copies instead of its replica placement's copy count. + MinWritableCopies uint32 `protobuf:"varint,5,opt,name=min_writable_copies,json=minWritableCopies,proto3" json:"min_writable_copies,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *LookupVolumeResponse_VolumeIdLocation) Reset() { @@ -5018,6 +5021,13 @@ func (x *LookupVolumeResponse_VolumeIdLocation) GetAuth() string { return "" } +func (x *LookupVolumeResponse_VolumeIdLocation) GetMinWritableCopies() uint32 { + if x != nil { + return x.MinWritableCopies + } + return 0 +} + type LookupEcVolumeResponse_EcShardIdLocation struct { state protoimpl.MessageState `protogen:"open.v1"` ShardId uint32 `protobuf:"varint,1,opt,name=shard_id,json=shardId,proto3" json:"shard_id,omitempty"` @@ -5420,14 +5430,15 @@ const file_master_proto_rawDesc = "" + "\x12volume_or_file_ids\x18\x01 \x03(\tR\x0fvolumeOrFileIds\x12\x1e\n" + "\n" + "collection\x18\x02 \x01(\tR\n" + - "collection\"\x95\x02\n" + + "collection\"\xc5\x02\n" + "\x14LookupVolumeResponse\x12`\n" + - "\x13volume_id_locations\x18\x01 \x03(\v20.master_pb.LookupVolumeResponse.VolumeIdLocationR\x11volumeIdLocations\x1a\x9a\x01\n" + + "\x13volume_id_locations\x18\x01 \x03(\v20.master_pb.LookupVolumeResponse.VolumeIdLocationR\x11volumeIdLocations\x1a\xca\x01\n" + "\x10VolumeIdLocation\x12)\n" + "\x11volume_or_file_id\x18\x01 \x01(\tR\x0evolumeOrFileId\x121\n" + "\tlocations\x18\x02 \x03(\v2\x13.master_pb.LocationR\tlocations\x12\x14\n" + "\x05error\x18\x03 \x01(\tR\x05error\x12\x12\n" + - "\x04auth\x18\x04 \x01(\tR\x04auth\"\xed\x01\n" + + "\x04auth\x18\x04 \x01(\tR\x04auth\x12.\n" + + "\x13min_writable_copies\x18\x05 \x01(\rR\x11minWritableCopies\"\xed\x01\n" + "\bLocation\x12\x10\n" + "\x03url\x18\x01 \x01(\tR\x03url\x12\x1d\n" + "\n" + diff --git a/weed/server/master_grpc_server_volume.go b/weed/server/master_grpc_server_volume.go index 4a83502f26..5dcab40d6d 100644 --- a/weed/server/master_grpc_server_volume.go +++ b/weed/server/master_grpc_server_volume.go @@ -252,7 +252,9 @@ func (ms *MasterServer) LookupVolume(ctx context.Context, req *master_pb.LookupV } if result, found := volumeLocations[vid]; found { var locations []*master_pb.Location + var urls []string for _, loc := range result.Locations { + urls = append(urls, loc.Url) locations = append(locations, &master_pb.Location{ Url: loc.Url, PublicUrl: loc.PublicUrl, @@ -270,11 +272,16 @@ func (ms *MasterServer) LookupVolume(ctx context.Context, req *master_pb.LookupV if result.NotFound { notFoundCount++ } + var minWritableCopies int + if volumeId, err := needle.NewVolumeId(vid); err == nil { + minWritableCopies = ms.Topo.DegradedMinCopies(req.Collection, volumeId, urls) + } resp.VolumeIdLocations = append(resp.VolumeIdLocations, &master_pb.LookupVolumeResponse_VolumeIdLocation{ - VolumeOrFileId: result.VolumeOrFileId, - Locations: locations, - Error: result.Error, - Auth: auth, + VolumeOrFileId: result.VolumeOrFileId, + Locations: locations, + Error: result.Error, + Auth: auth, + MinWritableCopies: uint32(minWritableCopies), }) } } diff --git a/weed/topology/store_replicate.go b/weed/topology/store_replicate.go index 41f55e47b8..64d55f869d 100644 --- a/weed/topology/store_replicate.go +++ b/weed/topology/store_replicate.go @@ -419,6 +419,10 @@ func getRemoteReplications(s *storage.Store, grpcDialOption grpc.DialOption, vol if v != nil { // has one local and has remote replications copyCount := v.ReplicaPlacement.GetCopyCount() + if n := lookupResult.MinWritableCopies; n > 0 && n < copyCount { + // a degraded volume, writable with fewer copies + copyCount = n + } if writableLocations < copyCount { operation.InvalidateVolumeIdLocationCache(volumeId.String()) label := "replication" diff --git a/weed/topology/topology.go b/weed/topology/topology.go index 3e82d85df4..31ba7ea30d 100644 --- a/weed/topology/topology.go +++ b/weed/topology/topology.go @@ -51,6 +51,7 @@ type Topology struct { volumeSizeLimit uint64 replicationAsMin bool maxWritableVolumes int + degradedGrown atomic.Bool // set once a volume was grown degraded, see volume_growth_degraded.go vacuumDisabledByOperator atomic.Bool // true when operator manually disables vacuum vacuumDisabledByPlugin atomic.Bool // true when disabled by the vacuum plugin monitor adminServerConnectedFunc func() bool // optional callback to check admin server presence diff --git a/weed/topology/topology_event_handling.go b/weed/topology/topology_event_handling.go index a27d8fcdb5..bcfd424e99 100644 --- a/weed/topology/topology_event_handling.go +++ b/weed/topology/topology_event_handling.go @@ -22,6 +22,7 @@ func (t *Topology) StartRefreshWritableVolumes(grpcDialOption grpc.DialOption, g freshThreshHold := time.Now().Unix() - 3*t.pulse //3 times of sleep interval t.CollectDeadNodeAndFullVolumes(freshThreshHold, t.volumeSizeLimit, growThreshold) t.DecayQuietVolumeSizes() + t.ReleaseDegradedVolumes() t.retryPendingQuarantineReleases() } time.Sleep(time.Duration(float32(t.pulse*1e3)*(1+rand.Float32())) * time.Millisecond) diff --git a/weed/topology/volume_growth.go b/weed/topology/volume_growth.go index 812c12478b..9b979e21b6 100644 --- a/weed/topology/volume_growth.go +++ b/weed/topology/volume_growth.go @@ -147,7 +147,9 @@ func (vg *VolumeGrowth) AutomaticGrowByType(option *VolumeGrowOption, grpcDialOp targetCount = vg.findVolumeCount(option.ReplicaPlacement.GetCopyCount()) } result, err = vg.GrowByCountAndType(grpcDialOption, targetCount, option, topo) - if len(result) > 0 && len(result)%option.ReplicaPlacement.GetCopyCount() == 0 { + // result only holds fully created volumes; degraded ones have fewer + // locations than the placement's copy count. + if len(result) > 0 { return result, nil } return result, err @@ -227,6 +229,12 @@ func (vg *VolumeGrowth) findAndGrow(grpcDialOption grpc.DialOption, topo *Topolo retry.refused = nil servers, reservation, e = vg.findEmptySlotsForOneVolume(topo, &retry, true) } + var degraded *super_block.ReplicaPlacement + if e != nil { + if s, r, rp, ok := vg.findDegradedSlots(topo, option); ok { + servers, reservation, degraded, e = s, r, rp, nil + } + } if e != nil { return nil, e } @@ -240,6 +248,19 @@ func (vg *VolumeGrowth) findAndGrow(grpcDialOption grpc.DialOption, topo *Topolo if raftErr != nil { return nil, raftErr } + if degraded != nil { + // Flag before grow registers the volume, so it turns writable with + // the copies it gets; the super block keeps the requested placement. + vl := topo.GetVolumeLayout(option.Collection, option.ReplicaPlacement, option.Ttl, option.DiskType) + vl.markDegraded(vid, servers) + topo.degradedGrown.Store(true) + defer func() { + if err != nil { + vl.unmarkDegraded(vid) + } + }() + glog.V(0).Infof("topology cannot hold replication %s: growing volume %d with %d copies (%s)", option.ReplicaPlacement, vid, len(servers), degraded) + } if err = vg.grow(grpcDialOption, topo, vid, option, reservation, servers...); err == nil { for _, server := range servers { if option.layoutLoad != nil { diff --git a/weed/topology/volume_growth_degraded.go b/weed/topology/volume_growth_degraded.go new file mode 100644 index 0000000000..5382fe940a --- /dev/null +++ b/weed/topology/volume_growth_degraded.go @@ -0,0 +1,243 @@ +package topology + +import ( + "slices" + + "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/storage/needle" + "github.com/seaweedfs/seaweedfs/weed/storage/super_block" +) + +// Degraded volume growth keeps writes available when the topology no longer +// has enough data centers, racks or data nodes for a replica placement, for +// example while one of three data centers is down with placement 200. A +// volume is never grown with fewer than degradedGrowthMinCopies copies. +// +// Volumes grown this way keep the requested placement in their super block, +// so the usual repair (volume.fix.replication) restores the missing copies +// once the topology recovers. They are writable with fewer copies only while +// the master flags them as degraded. The flag lives in memory: it is cleared +// as soon as the topology can hold the full placement again, and it is lost +// on a master restart; in both cases the volumes become ordinary +// under-replicated, read-only volumes until they are repaired. +const degradedGrowthMinCopies = 2 + +// degradedPlacements lists the placements to try when rp cannot be +// satisfied: every placement with fewer copies, no more data centers than rp +// and at least minCopies copies, the remaining copies spread over racks or +// servers instead. They keep as many copies as possible, then as many other +// data centers, then as many other racks. +func degradedPlacements(rp *super_block.ReplicaPlacement, minCopies int) (ret []*super_block.ReplicaPlacement) { + copies := rp.GetCopyCount() + for total := copies - 1; total >= max(minCopies, 1); total-- { + for dc := min(rp.DiffDataCenterCount, total-1); dc >= 0; dc-- { + for rack := min(total-1-dc, 9); rack >= 0; rack-- { + node := total - 1 - dc - rack + if node > 9 { + continue + } + ret = append(ret, &super_block.ReplicaPlacement{DiffDataCenterCount: dc, DiffRackCount: rack, SameRackCount: node}) + } + } + } + return +} + +// topologyCanHold reports whether the topology has enough data centers, +// racks and data nodes for rp, regardless of free space. Data nodes in +// maintenance mode receive no volumes and do not count. Degraded growth only +// applies when the topology cannot hold a placement: a placement that fails +// for lack of free slots must keep failing rather than silently lose copies. +func topologyCanHold(topo *Topology, rp *super_block.ReplicaPlacement) bool { + dataCenters, hasMain := 0, false + for _, dc := range topo.Children() { + racks, hasMainRack := 0, false + for _, rack := range dc.Children() { + nodes := 0 + for _, n := range rack.Children() { + if dn, ok := n.(*DataNode); ok && dn.InMaintenanceMode() { + continue + } + nodes++ + } + if nodes == 0 { + continue + } + racks++ + if nodes >= rp.SameRackCount+1 { + hasMainRack = true + } + } + if racks == 0 { + continue + } + dataCenters++ + if hasMainRack && racks >= rp.DiffRackCount+1 { + hasMain = true + } + } + return hasMain && dataCenters >= rp.DiffDataCenterCount+1 +} + +// findDegradedSlots looks for servers for one volume under a relaxed +// placement, when the topology cannot hold the requested one. It tries the +// relaxed placements the topology can hold, most copies first. Once one of +// them fails to find slots (no free space, or not in the requested +// location), it still tries the others with as many copies, but never fewer: +// a lack of space must not drop copies. Servers that refused an allocation +// are only tried again when no other server fits, as in findAndGrow. +func (vg *VolumeGrowth) findDegradedSlots(topo *Topology, option *VolumeGrowOption) (servers []*DataNode, reservation *VolumeGrowReservation, placement *super_block.ReplicaPlacement, ok bool) { + if topologyCanHold(topo, option.ReplicaPlacement) { + return nil, nil, nil, false + } + placements := degradedPlacements(option.ReplicaPlacement, degradedGrowthMinCopies) + search := func(refused map[*DataNode]bool) ([]*DataNode, *VolumeGrowReservation, *super_block.ReplicaPlacement, bool) { + failedAt := 0 + for _, rp := range placements { + if failedAt > 0 && rp.GetCopyCount() < failedAt { + break + } + if !topologyCanHold(topo, rp) { + continue + } + relaxed := *option + relaxed.ReplicaPlacement = rp + relaxed.refused = refused + if s, r, err := vg.findEmptySlotsForOneVolume(topo, &relaxed, true); err == nil { + return s, r, rp, true + } + failedAt = rp.GetCopyCount() + } + return nil, nil, nil, false + } + if servers, reservation, placement, ok = search(option.refused); ok || len(option.refused) == 0 { + return + } + return search(nil) +} + +// markDegraded lets vid be writable on exactly the servers it is grown on. +func (vl *VolumeLayout) markDegraded(vid needle.VolumeId, servers []*DataNode) { + nodes := make([]NodeId, 0, len(servers)) + for _, dn := range servers { + nodes = append(nodes, dn.Id()) + } + vl.accessLock.Lock() + defer vl.accessLock.Unlock() + vl.degradedVolumes[vid] = nodes +} + +func (vl *VolumeLayout) unmarkDegraded(vid needle.VolumeId) { + vl.accessLock.Lock() + defer vl.accessLock.Unlock() + delete(vl.degradedVolumes, vid) +} + +// degradedWritable reports whether vid is a degraded volume registered on +// exactly the servers it was grown on. A degraded volume missing one of them +// turns read-only like any other volume, so a copy that comes back has missed +// no write; a replacement copy does not stand in for a missing one; and the +// volume is not writable before all of its copies are registered. The mark +// is dropped once the volume has no location left, so a degraded volume +// whose copies all disconnected stays read-only until it is repaired. +// Callers hold accessLock. +func (vl *VolumeLayout) degradedWritable(vid needle.VolumeId) bool { + nodes, ok := vl.degradedVolumes[vid] + if !ok { + return false + } + location, found := vl.vid2location[vid] + if !found || location.Length() != len(nodes) { + return false + } + for _, dn := range location.list { + if !slices.Contains(nodes, dn.Id()) { + return false + } + } + return true +} + +// degradedCopies returns the copies a degraded volume writes to, only while +// it is in that exact state on the servers at urls. +func (vl *VolumeLayout) degradedCopies(vid needle.VolumeId, urls []string) int { + vl.accessLock.RLock() + defer vl.accessLock.RUnlock() + if !vl.degradedWritable(vid) || len(urls) != len(vl.degradedVolumes[vid]) { + return 0 + } + for _, dn := range vl.vid2location[vid].list { + if !slices.Contains(urls, dn.Url()) { + return 0 + } + } + return len(urls) +} + +// DegradedMinCopies returns how many writable copies a degraded volume needs +// to accept writes (the copies it was grown with), or 0 when vid is not +// degraded or urls are not exactly the servers it was grown on. Volume +// servers use it to replicate a write to fewer copies than the volume's +// placement asks for, to the locations it is returned with. +func (t *Topology) DegradedMinCopies(collection string, vid needle.VolumeId, urls []string) int { + if !t.degradedGrown.Load() { + return 0 + } + inCollection := func(c *Collection) int { + for _, vl := range c.GetAllVolumeLayouts() { + if n := vl.degradedCopies(vid, urls); n > 0 { + return n + } + } + return 0 + } + if collection != "" { + if c, ok := t.collectionMap.Find(collection); ok { + return inCollection(c.(*Collection)) + } + return 0 + } + for _, c := range t.collectionMap.Items() { + if n := inCollection(c.(*Collection)); n > 0 { + return n + } + } + return 0 +} + +func (vl *VolumeLayout) hasDegradedVolumes() bool { + vl.accessLock.RLock() + defer vl.accessLock.RUnlock() + return len(vl.degradedVolumes) > 0 +} + +// releaseDegradedVolumes clears the degraded flags, so the volumes that still +// miss copies leave the writable list until they are repaired. +func (vl *VolumeLayout) releaseDegradedVolumes() int { + vl.accessLock.Lock() + defer vl.accessLock.Unlock() + released := 0 + for vid := range vl.degradedVolumes { + delete(vl.degradedVolumes, vid) + if _, found := vl.vid2location[vid]; found { + vl.ensureCorrectWritables(vid) + } + released++ + } + return released +} + +// ReleaseDegradedVolumes clears the degraded flags of every layout whose +// placement the topology can hold again. +func (t *Topology) ReleaseDegradedVolumes() { + for _, c := range t.collectionMap.Items() { + for _, vl := range c.(*Collection).GetAllVolumeLayouts() { + if !vl.hasDegradedVolumes() || !topologyCanHold(t, vl.rp) { + continue + } + if n := vl.releaseDegradedVolumes(); n > 0 { + glog.V(0).Infof("topology can hold replication %s again: %d degraded volumes are read-only until repaired", vl.rp, n) + } + } + } +} diff --git a/weed/topology/volume_growth_degraded_test.go b/weed/topology/volume_growth_degraded_test.go new file mode 100644 index 0000000000..ca30f9f8c8 --- /dev/null +++ b/weed/topology/volume_growth_degraded_test.go @@ -0,0 +1,306 @@ +package topology + +import ( + "testing" + + "github.com/seaweedfs/seaweedfs/weed/storage" + "github.com/seaweedfs/seaweedfs/weed/storage/needle" + "github.com/seaweedfs/seaweedfs/weed/storage/super_block" + "github.com/seaweedfs/seaweedfs/weed/storage/types" +) + +// dc3 has no data node left, as when a whole data center is down. +var topologyLayoutOneDataCenterDown = ` +{ + "dc1":{"rack1":{"server11":{"ip":"10.0.0.11","volumes":[],"limit":10}, + "server12":{"ip":"10.0.0.12","volumes":[],"limit":10}}}, + "dc2":{"rack1":{"server21":{"ip":"10.0.0.21","volumes":[],"limit":10}}}, + "dc3":{} +} +` + +// All three data centers are up, but dc3 has no free slot. +var topologyLayoutOneDataCenterFull = ` +{ + "dc1":{"rack1":{"server11":{"ip":"10.0.0.11","volumes":[],"limit":10}}}, + "dc2":{"rack1":{"server21":{"ip":"10.0.0.21","volumes":[],"limit":10}}}, + "dc3":{"rack1":{"server31":{"ip":"10.0.0.31","volumes":[],"limit":0}}} +} +` + +// Only dc1 is left, with one rack of two servers. +var topologyLayoutOneDataCenterLeft = ` +{ + "dc1":{"rack1":{"server11":{"ip":"10.0.0.11","volumes":[],"limit":10}, + "server12":{"ip":"10.0.0.12","volumes":[],"limit":10}}}, + "dc2":{}, + "dc3":{} +} +` + +// Neither data center holds 011: dc1 has one rack, dc2 one server per rack. +var topologyLayoutRacksSplit = ` +{ + "dc1":{"rack1":{"server11":{"ip":"10.0.0.11","volumes":[],"limit":10}, + "server12":{"ip":"10.0.0.12","volumes":[],"limit":10}}}, + "dc2":{"rack1":{"server21":{"ip":"10.0.0.21","volumes":[],"limit":10}}, + "rack2":{"server22":{"ip":"10.0.0.22","volumes":[],"limit":10}}} +} +` + +func mustPlacement(t *testing.T, s string) *super_block.ReplicaPlacement { + t.Helper() + rp, err := super_block.NewReplicaPlacementFromString(s) + if err != nil { + t.Fatalf("placement %s: %v", s, err) + } + return rp +} + +func TestDegradedPlacements(t *testing.T) { + cases := []struct { + rp string + minCopies int + want []string + }{ + {"200", 2, []string{"100", "010", "001"}}, + {"200", 1, []string{"100", "010", "001", "000"}}, + {"210", 2, []string{"200", "110", "101", "020", "011", "002", "100", "010", "001"}}, + {"011", 2, []string{"010", "001"}}, + {"110", 2, []string{"100", "010", "001"}}, + {"001", 2, nil}, + {"000", 1, nil}, + } + for _, c := range cases { + got := degradedPlacements(mustPlacement(t, c.rp), c.minCopies) + if len(got) != len(c.want) { + t.Fatalf("%s min %d: got %v, want %v", c.rp, c.minCopies, got, c.want) + } + for i := range got { + if got[i].String() != c.want[i] { + t.Errorf("%s min %d: got %v, want %v", c.rp, c.minCopies, got, c.want) + } + } + } +} + +func TestTopologyCanHold(t *testing.T) { + down := setup(topologyLayoutOneDataCenterDown) + if topologyCanHold(down, mustPlacement(t, "200")) { + t.Error("200 should not fit two data centers") + } + if !topologyCanHold(down, mustPlacement(t, "100")) { + t.Error("100 should fit two data centers") + } + full := setup(topologyLayoutOneDataCenterFull) + if !topologyCanHold(full, mustPlacement(t, "200")) { + t.Error("a full data center still holds 200; free space is not the topology") + } + findDataNode(t, full, "server31").SetMaintenanceMode(true) + if topologyCanHold(full, mustPlacement(t, "200")) { + t.Error("a data node in maintenance receives no volume and must not count") + } +} + +func TestFindDegradedSlots(t *testing.T) { + vg := NewDefaultVolumeGrowth() + option := &VolumeGrowOption{ReplicaPlacement: mustPlacement(t, "200")} + + down := setup(topologyLayoutOneDataCenterDown) + servers, reservation, rp, ok := vg.findDegradedSlots(down, option) + if !ok { + t.Fatal("expected degraded slots with one data center down") + } + defer reservation.releaseAllReservations() + if rp.String() != "100" || len(servers) != 2 { + t.Fatalf("got placement %s on %d servers, want 100 on 2", rp, len(servers)) + } + if servers[0].GetDataCenterId() == servers[1].GetDataCenterId() { + t.Errorf("both copies in %s", servers[0].GetDataCenterId()) + } + + left := setup(topologyLayoutOneDataCenterLeft) + servers, reservation, rp, ok = vg.findDegradedSlots(left, option) + if !ok { + t.Fatal("expected two copies in the one data center left") + } + defer reservation.releaseAllReservations() + if rp.String() != "001" || len(servers) != 2 || servers[0] == servers[1] { + t.Fatalf("got placement %s on %v, want 001 on two servers", rp, servers) + } + + full := setup(topologyLayoutOneDataCenterFull) + if _, _, _, ok := vg.findDegradedSlots(full, option); ok { + t.Error("lack of free space must not degrade the placement") + } + // 210 cannot fit one rack per data center; 200 can, but dc3 has no free slot. + // Dropping to 100 would lose a copy for lack of space. + if _, _, _, ok := vg.findDegradedSlots(full, &VolumeGrowOption{ReplicaPlacement: mustPlacement(t, "210")}); ok { + t.Error("a relaxed placement the topology holds must not be relaxed further for lack of space") + } + + // 010 is tried first and fits dc2, not the requested dc1; 001 has as + // many copies and fits dc1. + split := setup(topologyLayoutRacksSplit) + inDc1 := &VolumeGrowOption{ReplicaPlacement: mustPlacement(t, "011"), DataCenter: "dc1"} + servers, reservation, rp, ok = vg.findDegradedSlots(split, inDc1) + if !ok { + t.Fatal("expected an equal-copy alternative in the requested data center") + } + defer reservation.releaseAllReservations() + if rp.String() != "001" || servers[0].GetDataCenterId() != "dc1" || servers[1].GetDataCenterId() != "dc1" { + t.Errorf("got %s on %s and %s, want 001 in dc1", rp, servers[0].GetDataCenterId(), servers[1].GetDataCenterId()) + } +} + +func TestDegradedVolumeWritability(t *testing.T) { + topo := setup(topologyLayoutOneDataCenterDown) + rp := mustPlacement(t, "200") + vl := topo.GetVolumeLayout("", rp, needle.EMPTY_TTL, types.HardDriveType) + + register := func(vid needle.VolumeId, servers ...string) []*DataNode { + var dns []*DataNode + for _, id := range servers { + dn := findDataNode(t, topo, id) + vi := storage.VolumeInfo{Id: vid, ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, Version: needle.GetCurrentVersion()} + dn.AddOrUpdateVolume(vi) + topo.RegisterVolumeLayout(vi, dn) + dns = append(dns, dn) + } + return dns + } + writable := func(vid needle.VolumeId) bool { + vl.accessLock.RLock() + defer vl.accessLock.RUnlock() + _, ok := vl.writableMembers[vid] + return ok + } + + register(1, "server11", "server21") + if writable(1) { + t.Fatal("a volume missing a copy must stay read-only without the degraded flag") + } + + vl.markDegraded(2, []*DataNode{findDataNode(t, topo, "server11"), findDataNode(t, topo, "server21")}) + dns := register(2, "server11") + if writable(2) { + t.Fatal("a degraded volume must not be writable before all its copies are registered") + } + dns = append(dns, register(2, "server21")...) + if !writable(2) { + t.Fatal("a degraded volume with its minimum copies should be writable") + } + urls := []string{dns[0].Url(), dns[1].Url()} + if n := topo.DegradedMinCopies("", 2, urls); n != 0 { + t.Fatalf("lookup reports %d min copies before any degraded growth", n) + } + topo.degradedGrown.Store(true) + if n := topo.DegradedMinCopies("", 2, urls); n != 2 { + t.Fatalf("lookup reports %d min copies for the degraded volume, want 2", n) + } + if n := topo.DegradedMinCopies("", 1, urls); n != 0 { + t.Fatalf("lookup reports %d min copies for a regular volume, want 0", n) + } + // locations read from another layout state than the current one + other := findDataNode(t, topo, "server12").Url() + for _, stale := range [][]string{{urls[0], other}, {urls[0]}, {urls[0], urls[1], other}} { + if n := topo.DegradedMinCopies("", 2, stale); n != 0 { + t.Fatalf("lookup reports %d min copies with locations %v, want 0", n, stale) + } + } + + vl.SetVolumeUnavailable(dns[1], 2) + if writable(2) { + t.Fatal("a degraded volume missing one of its copies must be read-only") + } + if n := topo.DegradedMinCopies("", 2, urls); n != 0 { + t.Fatalf("lookup reports %d min copies for a degraded volume missing a copy, want 0", n) + } + replacement := register(2, "server12") + if writable(2) { + t.Fatal("a replacement copy must not stand in for a missing original one") + } + vl.SetVolumeUnavailable(replacement[0], 2) + register(2, "server21") + if !writable(2) { + t.Fatal("the degraded volume should be writable again with its copies back") + } + + // dc3 comes back: the topology holds 200 again. + rack := NewRack("rack1") + findDataCenter(t, topo, "dc3").LinkChildNode(rack) + dn := NewDataNode("server31") + dn.Ip = "10.0.0.31" + rack.LinkChildNode(dn) + dn.getOrCreateDisk("").UpAdjustDiskUsageDelta("", &DiskUsageCounts{maxVolumeCount: 10}) + + topo.ReleaseDegradedVolumes() + if writable(2) { + t.Error("once the topology holds the placement, the degraded volume waits for repair read-only") + } + if vl.hasDegradedVolumes() { + t.Error("degraded flags should be cleared") + } + if n := topo.DegradedMinCopies("", 2, urls); n != 0 { + t.Errorf("lookup still reports %d min copies after release", n) + } +} + +func findDataCenter(t *testing.T, topo *Topology, id string) *DataCenter { + t.Helper() + for _, dc := range topo.Children() { + if string(dc.Id()) == id { + return dc.(*DataCenter) + } + } + t.Fatalf("data center %s not found", id) + return nil +} + +func findDataNode(t *testing.T, topo *Topology, id string) *DataNode { + t.Helper() + for _, dc := range topo.Children() { + for _, rack := range dc.Children() { + for _, n := range rack.Children() { + if string(n.Id()) == id { + return n.(*DataNode) + } + } + } + } + t.Fatalf("data node %s not found", id) + return nil +} + +func TestFindDegradedSlotsSkipsRefusedServers(t *testing.T) { + vg := NewDefaultVolumeGrowth() + down := setup(topologyLayoutOneDataCenterDown) + server11 := findDataNode(t, down, "server11") + option := &VolumeGrowOption{ + ReplicaPlacement: mustPlacement(t, "200"), + refused: map[*DataNode]bool{server11: true}, + } + for i := 0; i < 20; i++ { + servers, reservation, _, ok := vg.findDegradedSlots(down, option) + if !ok { + t.Fatal("expected degraded slots on the servers that did not refuse") + } + reservation.releaseAllReservations() + for _, s := range servers { + if s == server11 { + t.Fatal("picked a server that refused the allocation while server12 fits") + } + } + } + + server21 := findDataNode(t, down, "server21") + option.refused[server21] = true + servers, reservation, _, ok := vg.findDegradedSlots(down, option) + if !ok { + t.Fatal("refused servers must be retried when no other server fits") + } + reservation.releaseAllReservations() + if len(servers) != 2 { + t.Fatalf("got %d servers, want 2", len(servers)) + } +} diff --git a/weed/topology/volume_layout.go b/weed/topology/volume_layout.go index e915d4dea9..759d22b102 100644 --- a/weed/topology/volume_layout.go +++ b/weed/topology/volume_layout.go @@ -84,6 +84,9 @@ type VolumeLayout struct { deletingVolumes map[needle.VolumeId]struct{} volumeSizeLimit uint64 replicationAsMin bool + // degradedVolumes holds the volumes grown with fewer copies than rp + // asks for, with the servers they were grown on. + degradedVolumes map[needle.VolumeId][]NodeId // maxWritableVolumes caps how many writables PickForWrite spreads over; // 0 means every writable volume is a candidate. maxWritableVolumes int @@ -116,6 +119,7 @@ func NewVolumeLayout(rp *super_block.ReplicaPlacement, ttl *needle.TTL, diskType deletingVolumes: make(map[needle.VolumeId]struct{}), volumeSizeLimit: volumeSizeLimit, replicationAsMin: replicationAsMin, + degradedVolumes: make(map[needle.VolumeId][]NodeId), sizeTracking: make(map[needle.VolumeId]*volumeSizeTracking), } } @@ -430,6 +434,7 @@ func (vl *VolumeLayout) UnRegisterVolume(v *storage.VolumeInfo, dn *DataNode) { if location.Length() == 0 { delete(vl.vid2location, v.Id) delete(vl.sizeTracking, v.Id) + delete(vl.degradedVolumes, v.Id) vl.removeFromCrowded(v.Id) } @@ -1285,7 +1290,7 @@ func (vl *VolumeLayout) SetVolumeUnavailable(dn *DataNode, vid needle.VolumeId) if removed := location.Remove(dn); removed != nil { moveLookupOwnership(vid, removed, nil) wasWritable := false - if location.Length() < vl.rp.GetCopyCount() { + if location.Length() < vl.rp.GetCopyCount() && !vl.degradedWritable(vid) { glog.V(0).Infoln("Volume", vid, "has", location.Length(), "replica, less than required", vl.rp.GetCopyCount()) wasWritable = vl.removeFromWritable(vid) } @@ -1296,6 +1301,7 @@ func (vl *VolumeLayout) SetVolumeUnavailable(dn *DataNode, vid needle.VolumeId) // Mirrors UnRegisterVolume. delete(vl.vid2location, vid) delete(vl.sizeTracking, vid) + delete(vl.degradedVolumes, vid) vl.removeFromCrowded(vid) } return wasWritable @@ -1359,7 +1365,7 @@ func (vl *VolumeLayout) SetVolumeAvailable(dn *DataNode, vid needle.VolumeId, si func (vl *VolumeLayout) enoughCopies(vid needle.VolumeId) bool { locations := vl.vid2location[vid].Length() desired := vl.rp.GetCopyCount() - return locations == desired || (vl.replicationAsMin && locations > desired) + return locations == desired || (vl.replicationAsMin && locations > desired) || vl.degradedWritable(vid) } func (vl *VolumeLayout) SetVolumeCapacityFull(vid needle.VolumeId) bool {