diff --git a/seaweed-volume/src/config.rs b/seaweed-volume/src/config.rs index 93e106c858..2e1ebdcd0f 100644 --- a/seaweed-volume/src/config.rs +++ b/seaweed-volume/src/config.rs @@ -188,7 +188,7 @@ pub struct Cli { pub min_free_space_percent: String, /// Min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). - /// Low disk space will mark all volumes as ReadOnly. + /// Low disk space will mark all volumes as ReadOnly, until free space is 1% of the disk above the limit. #[arg(long = "minFreeSpace", default_value = "")] pub min_free_space: String, @@ -374,6 +374,27 @@ impl MinFreeSpace { } } + /// Go's util.MinFreeSpaceReleaseMarginPercent. + pub const RELEASE_MARGIN_PERCENT: u64 = 1; + + /// Mirrors Go's MinFreeSpace.IsLowFrom: a location that was low stays low + /// until free space is RELEASE_MARGIN_PERCENT of the disk above the limit. + pub fn is_low_from(&self, was_low: bool, free_bytes: u64, total_bytes: u64) -> bool { + let low = self.is_low(free_bytes, total_bytes); + if !was_low || low { + return low; + } + match self { + MinFreeSpace::Percent(pct) => { + free_bytes as f64 / total_bytes as f64 * 100.0 + < *pct + Self::RELEASE_MARGIN_PERCENT as f64 + } + MinFreeSpace::Bytes(min) => { + free_bytes < min.saturating_add(total_bytes / 100 * Self::RELEASE_MARGIN_PERCENT) + } + } + } + /// Free bytes above the floor; mirrors Go's MinFreeSpace.AvailableSpace. pub fn available_space(&self, free_bytes: u64, total_bytes: u64) -> u64 { let floor = match self { @@ -1717,6 +1738,46 @@ mod tests { } } + #[test] + fn test_min_free_space_is_low_from_holds_until_margin() { + let pct = MinFreeSpace::Percent(7.0); + let total = 10_000u64; + for (was_low, free, want) in [ + (false, 699, true), + (false, 702, false), + (true, 702, true), + (true, 799, true), + (true, 800, false), + (false, 799, false), + ] { + assert_eq!( + pct.is_low_from(was_low, free, total), + want, + "percent was_low={was_low} free={free}" + ); + } + + let gib = 1u64 << 30; + let bytes = MinFreeSpace::Bytes(70 * gib); + let total = 1000 * gib; + for (was_low, free, want) in [ + (false, 70 * gib - 1, true), + (false, 70 * gib, false), + (true, 70 * gib + 1, true), + (true, 80 * gib - 1, true), + (true, 80 * gib, false), + ] { + assert_eq!( + bytes.is_low_from(was_low, free, total), + want, + "bytes was_low={was_low} free={free}" + ); + } + + let near_max = MinFreeSpace::Bytes(u64::MAX - 1); + assert!(near_max.is_low_from(true, u64::MAX - 1, u64::MAX)); + } + #[test] fn test_parse_min_free_spaces_percent() { let result = parse_min_free_spaces("", "1").unwrap(); diff --git a/seaweed-volume/src/storage/disk_location.rs b/seaweed-volume/src/storage/disk_location.rs index fb668a39fc..0a460939ab 100644 --- a/seaweed-volume/src/storage/disk_location.rs +++ b/seaweed-volume/src/storage/disk_location.rs @@ -905,6 +905,15 @@ impl DiskLocation { unused } + /// Mirrors Go's DiskLocation.updateDiskSpaceLow for a reading with space + /// values. + fn update_disk_space_low(&self, free: u64, total: u64) -> bool { + let was_low = self.is_disk_space_low.load(Ordering::Relaxed); + let is_low = self.min_free_space.is_low_from(was_low, free, total); + self.is_disk_space_low.store(is_low, Ordering::Relaxed); + is_low + } + /// Check disk space against min_free_space and update is_disk_space_low. pub fn check_disk_space(&self) { let (total, free) = get_disk_stats(&self.directory); @@ -912,8 +921,7 @@ impl DiskLocation { return; } let used = total.saturating_sub(free); - let is_low = self.min_free_space.is_low(free, total); - self.is_disk_space_low.store(is_low, Ordering::Relaxed); + self.update_disk_space_low(free, total); // Go's DiskLocation.AvailableSpace counts only free space above the // -volume.minFreeSpace floor, so space checks stay above it too. self.available_space.store( @@ -1701,6 +1709,40 @@ mod tests { assert_eq!(loc.available_space.load(Ordering::Relaxed), 0); } + // Mirrors Go's TestDiskSpaceLowStaysUntilFreeSpaceIsClearlyBack: a + // location that went low stays low until free space clears the margin. + #[test] + fn test_disk_space_low_stays_until_free_space_is_clearly_back() { + let tmp = TempDir::new().unwrap(); + let dir = tmp.path().to_str().unwrap(); + let loc = DiskLocation::new( + dir, + dir, + 0, + DiskType::HardDrive, + MinFreeSpace::Percent(7.0), + Vec::new(), + ) + .unwrap(); + let total = 10_000u64; + for (free, want) in [ + (699, true), + (702, true), + (698, true), + (760, true), + (800, false), + (702, false), + (699, true), + ] { + assert_eq!( + loc.update_disk_space_low(free, total), + want, + "free {free} of {total}" + ); + assert_eq!(loc.is_disk_space_low.load(Ordering::Relaxed), want); + } + } + // Mirrors Go's CheckDiskSpace pending subtraction: an in-flight copy's // charge stays out of the cache across a probe, so another copy cannot // re-spend the headroom the live reading still shows as free. diff --git a/weed/command/server.go b/weed/command/server.go index 1c539708fe..bd62093f71 100644 --- a/weed/command/server.go +++ b/weed/command/server.go @@ -71,7 +71,7 @@ var ( volumeDataFolders = cmdServer.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...") volumeMaxDataVolumeCounts = cmdServer.Flag.String("volume.max", "10", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured as free disk space divided by volume size.") volumeMinFreeSpacePercent = cmdServer.Flag.String("volume.minFreeSpacePercent", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes as ReadOnly (deprecated, use minFreeSpace instead).") - volumeMinFreeSpace = cmdServer.Flag.String("volume.minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly.") + volumeMinFreeSpace = cmdServer.Flag.String("volume.minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly, until free space is 1% of the disk above the limit.") serverMetricsHttpPort = cmdServer.Flag.Int("metricsPort", 0, "Prometheus metrics listen port") serverMetricsHttpIp = cmdServer.Flag.String("metricsIp", "", "metrics listen ip. If empty, default to same as -ip.bind option.") serverGrpcLocalSocketDir = cmdServer.Flag.String("grpc.localSocketDir", "/tmp", "directory for the local gRPC Unix sockets; default to /tmp. Point it at a directory a temp cleaner does not sweep, such as /run/seaweedfs") diff --git a/weed/command/volume.go b/weed/command/volume.go index d6a224fbd0..5bfa66a0ec 100644 --- a/weed/command/volume.go +++ b/weed/command/volume.go @@ -271,7 +271,7 @@ var ( maxVolumeCounts = cmdVolume.Flag.String("max", "10", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured as free disk space divided by volume size.") volumeWhiteListOption = cmdVolume.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.") minFreeSpacePercent = cmdVolume.Flag.String("minFreeSpacePercent", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes as ReadOnly (deprecated, use minFreeSpace instead).") - minFreeSpace = cmdVolume.Flag.String("minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly.") + minFreeSpace = cmdVolume.Flag.String("minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly, until free space is 1% of the disk above the limit.") ) func runVolume(cmd *Command, args []string) bool { diff --git a/weed/storage/disk_location.go b/weed/storage/disk_location.go index a1887980dd..d435ed4a36 100644 --- a/weed/storage/disk_location.go +++ b/weed/storage/disk_location.go @@ -14,6 +14,7 @@ import ( "github.com/google/uuid" "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb" "github.com/seaweedfs/seaweedfs/weed/stats" "github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding" "github.com/seaweedfs/seaweedfs/weed/storage/needle" @@ -70,7 +71,9 @@ type DiskLocation struct { // the guard already serializes it, and consulting the hook would skip it. loadGuard func(vid needle.VolumeId) (release func(), skip bool) - isDiskSpaceLow atomic.Bool + isDiskSpaceLow atomic.Bool + // lowVerdict: last verdict from a reading with space values. + lowVerdict atomic.Bool isDiskUnavailable atomic.Bool // readOnlyMount: dir or idxDir is on a read-only filesystem. Volumes load // read-only and the location offers no free slots. Fixed at startup. @@ -806,6 +809,21 @@ func (l *DiskLocation) UnUsedSpace(volumeSizeLimit uint64) (unUsedSpace uint64) return } +// updateDiskSpaceLow applies MinFreeSpace.IsLowFrom to a reading. Only the +// disk check goroutine writes the flag. A reading without space values (All +// is 0) is judged by IsLow alone and leaves the remembered verdict alone. +func (l *DiskLocation) updateDiskSpaceLow(s *volume_server_pb.DiskStatus) (isLow bool, desc string) { + if s.All == 0 { + isLow, desc = l.MinFreeSpace.IsLow(s.Free, s.PercentFree) + l.isDiskSpaceLow.Store(isLow) + return isLow, desc + } + isLow, desc = l.MinFreeSpace.IsLowFrom(l.lowVerdict.Load(), s.Free, s.All, s.PercentFree) + l.lowVerdict.Store(isLow) + l.isDiskSpaceLow.Store(isLow) + return isLow, desc +} + // newDiskStatus is a seam letting a test observe the config CheckDiskSpace probes with. var newDiskStatus = stats.NewDiskStatusOnStart @@ -833,13 +851,10 @@ func (l *DiskLocation) CheckDiskSpace(config stats.DiskIOProbeConfig) { } l.diskTotalBytes.Store(s.All) l.diskFreeBytes.Store(s.Free) - isLow, desc := l.MinFreeSpace.IsLow(s.Free, s.PercentFree) - if isLow != l.isDiskSpaceLow.Load() { - l.isDiskSpaceLow.Store(isLow) - } + isLow, desc := l.updateDiskSpaceLow(s) logLevel := glog.Level(4) - if l.isDiskSpaceLow.Load() { + if isLow { logLevel = glog.Level(0) } diff --git a/weed/storage/disk_location_minfree_test.go b/weed/storage/disk_location_minfree_test.go new file mode 100644 index 0000000000..81a0a628e9 --- /dev/null +++ b/weed/storage/disk_location_minfree_test.go @@ -0,0 +1,150 @@ +package storage + +import ( + "sync" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb" + "github.com/seaweedfs/seaweedfs/weed/storage/types" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +const minFreeTestDiskBytes = uint64(1000) << 30 + +// readingAt is a disk reading with the given percentage of free space. +func readingAt(percent float64) *volume_server_pb.DiskStatus { + return &volume_server_pb.DiskStatus{ + All: minFreeTestDiskBytes, + Free: uint64(float64(minFreeTestDiskBytes) * percent / 100), + PercentFree: float32(percent), + } +} + +func newMinFreeTestLocation() *DiskLocation { + return &DiskLocation{ + DiskType: types.HardDriveType, + MinFreeSpace: util.MinFreeSpace{Type: util.AsPercent, Percent: 7}, + } +} + +// A disk whose free space hovers at -minFreeSpacePercent must not turn its +// volumes read-only and writable again on every check. +func TestDiskSpaceLowStaysUntilFreeSpaceIsClearlyBack(t *testing.T) { + location := newMinFreeTestLocation() + + steps := []struct { + percent float64 + wantLow bool + }{ + {7.50, false}, + {6.99, true}, // writes take it under the limit + {7.02, true}, // a delete gives a little back + {6.98, true}, // more writes + {7.05, true}, // vacuum gives back more + {6.99, true}, + {7.60, true}, // still inside the margin + {8.00, false}, // clearly back + {7.50, false}, // writes after the release do not trigger it above the limit + {6.99, true}, // crossing the limit again does + } + flips := 0 + prev := false + for i, step := range steps { + isLow, desc := location.updateDiskSpaceLow(readingAt(step.percent)) + if isLow != step.wantLow || location.isDiskSpaceLow.Load() != step.wantLow { + t.Fatalf("check %d (%.2f%% free): low = %v, flag = %v, want %v (%s)", + i, step.percent, isLow, location.isDiskSpaceLow.Load(), step.wantLow, desc) + } + if isLow != prev { + flips++ + prev = isLow + } + } + if flips != 3 { + t.Fatalf("state flipped %d times over the sequence, want 3 (enter, leave, enter)", flips) + } +} + +// A reading without space values (statfs failed before any good reading) is +// low, as on a disk with no space, but that verdict is not remembered: the +// next good reading above the limit releases the location at once. +func TestDiskSpaceLowFromFailedReadingIsNotHeld(t *testing.T) { + location := newMinFreeTestLocation() + + if isLow, _ := location.updateDiskSpaceLow(&volume_server_pb.DiskStatus{Error: "statfs timeout"}); !isLow { + t.Fatal("a reading without space values must still be low") + } + if !location.isDiskSpaceLow.Load() { + t.Fatal("flag not set by a reading without space values") + } + // 7.5% is above the 7% limit but inside the 1% margin. + if isLow, desc := location.updateDiskSpaceLow(readingAt(7.5)); isLow { + t.Fatalf("a good reading above the limit stayed low after a failed one: %s", desc) + } + if location.isDiskSpaceLow.Load() { + t.Fatal("flag still set after a good reading above the limit") + } + + // A held verdict survives a failed reading in between. + location.updateDiskSpaceLow(readingAt(6.9)) + location.updateDiskSpaceLow(&volume_server_pb.DiskStatus{Error: "statfs timeout"}) + if isLow, desc := location.updateDiskSpaceLow(readingAt(7.5)); !isLow { + t.Fatalf("a failed reading between two good ones dropped the held verdict: %s", desc) + } +} + +// A byte limit is held the same way. +func TestDiskSpaceLowStaysUntilFreeSpaceIsClearlyBackForByteLimit(t *testing.T) { + const limit = uint64(70) << 30 + location := &DiskLocation{ + DiskType: types.HardDriveType, + MinFreeSpace: util.MinFreeSpace{Type: util.AsBytes, Bytes: limit, Raw: "70GiB"}, + } + at := func(free uint64) *volume_server_pb.DiskStatus { + return &volume_server_pb.DiskStatus{All: minFreeTestDiskBytes, Free: free, PercentFree: float32(float64(free) / float64(minFreeTestDiskBytes) * 100)} + } + margin := minFreeTestDiskBytes / 100 + for i, step := range []struct { + free uint64 + wantLow bool + }{ + {limit + 1, false}, + {limit - 1, true}, + {limit + 1, true}, + {limit + margin - 1, true}, + {limit + margin, false}, + {limit + 1, false}, + } { + if isLow, desc := location.updateDiskSpaceLow(at(step.free)); isLow != step.wantLow { + t.Fatalf("check %d (free %d): low = %v, want %v (%s)", i, step.free, isLow, step.wantLow, desc) + } + } +} + +// The flag is read by the heartbeat, the write path and the volumes' read-only +// reports while the disk check updates it. +func TestDiskSpaceLowIsSafeToReadWhileItIsUpdated(t *testing.T) { + location := newMinFreeTestLocation() + + done := make(chan struct{}) + var readers sync.WaitGroup + for i := 0; i < 4; i++ { + readers.Add(1) + go func() { + defer readers.Done() + for { + select { + case <-done: + return + default: + _ = location.isDiskSpaceLow.Load() + } + } + }() + } + for i := 0; i < 1000; i++ { + location.updateDiskSpaceLow(readingAt([]float64{6.9, 7.1, 7.5, 8.2, 7.1}[i%5])) + } + close(done) + readers.Wait() +} diff --git a/weed/util/minfreespace.go b/weed/util/minfreespace.go index d73e26f8cb..7d2aea29ad 100644 --- a/weed/util/minfreespace.go +++ b/weed/util/minfreespace.go @@ -45,6 +45,38 @@ func (s MinFreeSpace) IsLow(freeBytes uint64, freePercent float32) (yes bool, de return false, "" } +// MinFreeSpaceReleaseMarginPercent is how far above the limit, in percent of +// the disk, free space must climb before a low location is writable again. +const MinFreeSpaceReleaseMarginPercent = 1 + +// IsLowFrom is IsLow with memory: a location that was low stays low until free +// space is MinFreeSpaceReleaseMarginPercent of the disk above the limit, so a +// disk hovering at the limit does not flip read-only on every check. +func (s MinFreeSpace) IsLowFrom(wasLow bool, freeBytes, totalBytes uint64, freePercent float32) (yes bool, desc string) { + yes, desc = s.IsLow(freeBytes, freePercent) + if !wasLow || yes { + return yes, desc + } + switch s.Type { + case AsPercent: + release := s.Percent + MinFreeSpaceReleaseMarginPercent + if freePercent < release { + return true, fmt.Sprintf("disk free %.2f%% >= required %.2f%% but still below %.2f%% needed to leave the low-disk state", + freePercent, s.Percent, release) + } + case AsBytes: + release := s.Bytes + totalBytes/100*MinFreeSpaceReleaseMarginPercent + if release < s.Bytes { // overflow + release = math.MaxUint64 + } + if freeBytes < release { + return true, fmt.Sprintf("disk free %s >= required %s but still below %s needed to leave the low-disk state", + BytesToHumanReadable(freeBytes), BytesToHumanReadable(s.Bytes), BytesToHumanReadable(release)) + } + } + return false, desc +} + func (s MinFreeSpace) AvailableSpace(freeBytes uint64, totalBytes uint64) uint64 { var minFreeSpaceBytes uint64 switch s.Type { diff --git a/weed/util/minfreespace_test.go b/weed/util/minfreespace_test.go index 496a50b563..abc1c0b4ff 100644 --- a/weed/util/minfreespace_test.go +++ b/weed/util/minfreespace_test.go @@ -29,3 +29,96 @@ func TestParseMinFreeSpace(t *testing.T) { } } } + +// A location that went low must not flip back on every reading that touches +// the limit; it is released only once free space is the margin above it. +func TestMinFreeSpaceIsLowFromPercent(t *testing.T) { + const total = uint64(1000) << 30 + s := MinFreeSpace{Type: AsPercent, Percent: 7} + free := func(percent float64) (uint64, uint64, float32) { + return uint64(float64(total) * percent / 100), total, float32(percent) + } + + // readings, as free percent, and the verdict wanted after each check. + readings := []struct { + percent float64 + wantLow bool + }{ + {7.50, false}, // above the limit + {7.00, false}, // exactly at the limit is not low + {6.99, true}, // crosses the limit + {7.01, true}, // a delete gives a little back: still low + {6.98, true}, + {7.40, true}, + {7.99, true}, // not yet the margin above the limit + {8.00, false}, + {7.60, false}, // released, and stays so until it crosses the limit again + {6.99, true}, + } + low := false + for i, r := range readings { + freeBytes, totalBytes, pct := free(r.percent) + var desc string + low, desc = s.IsLowFrom(low, freeBytes, totalBytes, pct) + if low != r.wantLow { + t.Fatalf("reading %d (%.2f%% free): low = %v, want %v (%s)", i, r.percent, low, r.wantLow, desc) + } + } +} + +func TestMinFreeSpaceIsLowFromBytes(t *testing.T) { + const total = uint64(10) << 40 // 10 TiB: the margin is 1% of it + const limit = uint64(100) << 30 + margin := total / 100 + s := MinFreeSpace{Type: AsBytes, Bytes: limit, Raw: "100GiB"} + + steps := []struct { + free uint64 + wasLow bool + wantLow bool + }{ + {limit + 1, false, false}, + {limit, false, false}, + {limit - 1, false, true}, + {limit + 1, true, true}, + {limit + margin - 1, true, true}, + {limit + margin, true, false}, + {limit + margin + 1, true, false}, + // Not low before: the margin plays no part in going low. + {limit + margin - 1, false, false}, + } + for i, st := range steps { + got, desc := s.IsLowFrom(st.wasLow, st.free, total, float32(float64(st.free)/float64(total)*100)) + if got != st.wantLow { + t.Errorf("step %d (free %d, wasLow %v): low = %v, want %v (%s)", i, st.free, st.wasLow, got, st.wantLow, desc) + } + } +} + +// Without a previous low verdict IsLowFrom is IsLow. +func TestMinFreeSpaceIsLowFromMatchesIsLowWhenNotLow(t *testing.T) { + for _, s := range []MinFreeSpace{ + {Type: AsPercent, Percent: 7}, + {Type: AsBytes, Bytes: 10 << 30}, + {}, + } { + for _, free := range []uint64{0, 5 << 30, 10 << 30, 70 << 30, 71 << 30, 500 << 30} { + const total = uint64(1000) << 30 + pct := float32(float64(free) / float64(total) * 100) + want, _ := s.IsLow(free, pct) + got, _ := s.IsLowFrom(false, free, total, pct) + if got != want { + t.Errorf("%v free %d: IsLowFrom(false) = %v, IsLow = %v", s, free, got, want) + } + } + } +} + +// A byte limit larger than the disk's headroom to MaxUint64 must not wrap the +// release level around to a small value. +func TestMinFreeSpaceIsLowFromBytesOverflow(t *testing.T) { + s := MinFreeSpace{Type: AsBytes, Bytes: ^uint64(0) - 10} + if low, _ := s.IsLowFrom(true, ^uint64(0)-5, ^uint64(0), 100); !low { + t.Fatal("a wrapped release level released a low location") + } +}