diff --git a/other/metrics/grafana_seaweedfs.json b/other/metrics/grafana_seaweedfs.json index 36e17344f8..ba884011aa 100644 --- a/other/metrics/grafana_seaweedfs.json +++ b/other/metrics/grafana_seaweedfs.json @@ -5547,6 +5547,102 @@ } ], "pluginVersion": "10.3.1" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "title": "EC Shards Disagreeing With Disk", + "description": "Mounted EC shards whose file on disk is gone or replaced (ghost) or changed size since the mount (stale_size).", + "type": "timeseries", + "id": 270, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 150 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "drawStyle": "line", + "fillOpacity": 10, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 4, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "never", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "legend": { + "calcs": [ + "lastNotNull", + "max" + ], + "displayMode": "table", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum by (instance, reason) (SeaweedFS_volumeServer_ec_shard_disk_mismatch{cluster=~\"$cluster\"})", + "range": true, + "refId": "A", + "legendFormat": "{{instance}} {{reason}}" + } + ], + "pluginVersion": "10.3.1" } ] }, diff --git a/seaweed-volume/src/metrics.rs b/seaweed-volume/src/metrics.rs index add010a324..64aa6da9d5 100644 --- a/seaweed-volume/src/metrics.rs +++ b/seaweed-volume/src/metrics.rs @@ -122,6 +122,18 @@ pub static VOLUME_GAUGE: LazyLock = LazyLock::new(|| { .expect("metric can be created") }); +/// Mounted EC shards whose file on disk is gone or replaced (ghost) or changed size (stale_size). +pub static EC_SHARD_DISK_MISMATCH_GAUGE: LazyLock = LazyLock::new(|| { + GaugeVec::new( + Opts::new( + "SeaweedFS_volumeServer_ec_shard_disk_mismatch", + "Mounted EC shards whose file on disk is gone or replaced (ghost) or changed size (stale_size).", + ), + &["reason"], + ) + .expect("metric can be created") +}); + /// Read-only volumes per collection and type. pub static READ_ONLY_VOLUME_GAUGE: LazyLock = LazyLock::new(|| { GaugeVec::new( @@ -439,6 +451,7 @@ pub fn register_metrics() { Box::new(VACUUMING_DROPPED_NEEDLES_COUNTER.clone()), Box::new(VOLUME_GAUGE.clone()), Box::new(READ_ONLY_VOLUME_GAUGE.clone()), + Box::new(EC_SHARD_DISK_MISMATCH_GAUGE.clone()), Box::new(MAX_VOLUMES.clone()), Box::new(DISK_SIZE_GAUGE.clone()), Box::new(RESOURCE_GAUGE.clone()), diff --git a/seaweed-volume/src/server/heartbeat.rs b/seaweed-volume/src/server/heartbeat.rs index b85fe5a4aa..72d71ea720 100644 --- a/seaweed-volume/src/server/heartbeat.rs +++ b/seaweed-volume/src/server/heartbeat.rs @@ -6,7 +6,7 @@ use std::collections::{HashMap, HashSet}; use std::path::Path; use std::sync::Arc; -use std::sync::atomic::Ordering; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tokio::sync::broadcast; @@ -17,6 +17,7 @@ use super::volume_server::{VolumeServerState, to_http_address}; use crate::pb::master_pb; use crate::pb::volume_server_pb; use crate::remote_storage::s3_tier::{S3TierBackend, S3TierConfig}; +use crate::storage::erasure_coding::ec_shard::EcShardDiskCheck; use crate::storage::store::Store; use crate::storage::types::{NeedleId, VolumeId}; use crate::storage::volume_report::VolumeReportKey; @@ -1038,6 +1039,31 @@ async fn maybe_adjust_volume_max( .await } +static EC_SHARD_CHECK_RUNNING: AtomicBool = AtomicBool::new(false); + +/// Runs `check` over the mounted EC shards on its own thread, unless the +/// last one is still running; whether it started. +fn start_ec_shard_check(state: &Arc, check: fn(&[EcShardDiskCheck])) -> bool { + if EC_SHARD_CHECK_RUNNING.swap(true, Ordering::AcqRel) { + return false; + } + let state = state.clone(); + // A plain thread, not spawn_blocking: runtime shutdown waits for + // blocking tasks, and a stat on a hung disk may never return. + let spawned = std::thread::Builder::new() + .name("ec-shard-check".into()) + .spawn(move || { + let shards = state.store.read().unwrap().ec_shard_disk_checks(); + check(&shards); + EC_SHARD_CHECK_RUNNING.store(false, Ordering::Release); + }); + if spawned.is_err() { + EC_SHARD_CHECK_RUNNING.store(false, Ordering::Release); + return false; + } + true +} + /// The EC heartbeat and the shard list later deltas are diffed against, /// under one guard so no mount lands between them unreported. async fn ec_tick_pass( @@ -1050,6 +1076,9 @@ async fn ec_tick_pass( ), tokio::task::JoinError, > { + start_ec_shard_check(state, |shards| { + Store::check_mounted_ec_shards(shards); + }); off_runtime(config, state, |config, state| { let store = state.store.read().unwrap(); ( @@ -2694,6 +2723,73 @@ mod tests { assert_eq!(shards.len(), 1); } + static STALLED_CHECK_STARTED: AtomicBool = AtomicBool::new(false); + static STALLED_CHECK_RELEASED: AtomicBool = AtomicBool::new(false); + + fn stalled_ec_shard_check(_: &[EcShardDiskCheck]) { + STALLED_CHECK_STARTED.store(true, Ordering::SeqCst); + while !STALLED_CHECK_RELEASED.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(5)); + } + } + + // A disk check stuck on a hung disk holds no store guard: a writer gets + // the store, the tick still reports, and no second check starts. + #[tokio::test] + async fn test_ec_tick_pass_runs_past_a_stalled_disk_check() { + let temp_dir = tempfile::tempdir().unwrap(); + let dir = temp_dir.path().to_str().unwrap(); + let mut store = reporting_store(dir, 0); + std::fs::write(format!("{}/ec_tick_stalled_check_43.ec00", dir), b"shard").unwrap(); + std::fs::write(format!("{}/ec_tick_stalled_check_43.ecx", dir), [0u8; 16]).unwrap(); + store.locations[0] + .mount_ec_shards(VolumeId(43), "ec_tick_stalled_check", &[0], "") + .unwrap(); + let state = test_state_with_store(store); + + while !start_ec_shard_check(&state, stalled_ec_shard_check) { + tokio::time::sleep(Duration::from_millis(10)).await; + } + while !STALLED_CHECK_STARTED.load(Ordering::SeqCst) { + tokio::time::sleep(Duration::from_millis(10)).await; + } + + let (wrote_tx, wrote_rx) = std::sync::mpsc::channel(); + { + let state = state.clone(); + std::thread::spawn(move || { + drop(state.store.write().unwrap()); + let _ = wrote_tx.send(()); + }); + } + wrote_rx + .recv_timeout(Duration::from_secs(10)) + .expect("the stalled disk check kept the store guard"); + let (heartbeat, shards) = tokio::time::timeout( + Duration::from_secs(10), + ec_tick_pass(&test_config(), &state), + ) + .await + .expect("the EC tick waited for the stalled disk check") + .unwrap(); + let still_one_check = EC_SHARD_CHECK_RUNNING.load(Ordering::SeqCst); + STALLED_CHECK_RELEASED.store(true, Ordering::SeqCst); + + assert_eq!(heartbeat.ec_shards.len(), 1); + assert_eq!(shards.len(), 1); + assert!( + still_one_check, + "a second disk check ran beside the stalled one" + ); + tokio::time::timeout(Duration::from_secs(10), async { + while EC_SHARD_CHECK_RUNNING.load(Ordering::SeqCst) { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the released check did not finish"); + } + #[tokio::test] async fn test_volume_max_adjustment_waits_for_the_store_off_the_runtime() { let temp_dir = tempfile::tempdir().unwrap(); diff --git a/seaweed-volume/src/storage/erasure_coding/ec_shard.rs b/seaweed-volume/src/storage/erasure_coding/ec_shard.rs index bda6e2b8ab..d2b8d3e99b 100644 --- a/seaweed-volume/src/storage/erasure_coding/ec_shard.rs +++ b/seaweed-volume/src/storage/erasure_coding/ec_shard.rs @@ -30,6 +30,53 @@ pub fn shard_id_try_from(v: u32) -> Result { } } +pub const EC_SHARD_GHOST: &str = "ghost"; +pub const EC_SHARD_STALE_SIZE: &str = "stale_size"; + +/// What tells two files apart: (device, inode) on unix, (volume serial, +/// file index) on Windows. +#[cfg(unix)] +fn file_id(f: &File) -> io::Result<(u64, u64)> { + use std::os::unix::fs::MetadataExt; + let m = f.metadata()?; + Ok((m.dev(), m.ino())) +} + +#[cfg(windows)] +fn file_id(f: &File) -> io::Result<(u64, u64)> { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Storage::FileSystem::{ + BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle, + }; + // SAFETY: the handle stays open for the call and `info` is a valid out-param. + unsafe { + let mut info: BY_HANDLE_FILE_INFORMATION = std::mem::zeroed(); + if GetFileInformationByHandle(f.as_raw_handle() as _, &mut info) == 0 { + return Err(io::Error::last_os_error()); + } + Ok(( + info.dwVolumeSerialNumber as u64, + (info.nFileIndexHigh as u64) << 32 | info.nFileIndexLow as u64, + )) + } +} + +/// The file id and length of `path`, read without read access to the file. +#[cfg(unix)] +fn path_file_id(path: &str) -> io::Result<((u64, u64), u64)> { + use std::os::unix::fs::MetadataExt; + let m = std::fs::metadata(path)?; + Ok(((m.dev(), m.ino()), m.len())) +} + +#[cfg(windows)] +fn path_file_id(path: &str) -> io::Result<((u64, u64), u64)> { + use std::os::windows::fs::OpenOptionsExt; + // No access rights, as std::fs::metadata opens it. + let f = OpenOptions::new().access_mode(0).open(path)?; + Ok((file_id(&f)?, f.metadata()?.len())) +} + /// A single erasure-coded shard file. pub struct EcVolumeShard { pub volume_id: VolumeId, @@ -39,6 +86,7 @@ pub struct EcVolumeShard { pub disk_type: DiskType, ecd_file: Option, ecd_file_size: i64, + ecd_file_id: Option<(u64, u64)>, } impl EcVolumeShard { @@ -52,6 +100,7 @@ impl EcVolumeShard { disk_type: DiskType::default(), ecd_file: None, ecd_file_size: 0, + ecd_file_id: None, } } @@ -67,6 +116,7 @@ impl EcVolumeShard { let path = self.file_name(); let file = open_volume_file(OpenOptions::new().read(true), &path)?; self.ecd_file_size = file.metadata()?.len() as i64; + self.ecd_file_id = file_id(&file).ok(); self.ecd_file = Some(file); Ok(()) } @@ -84,6 +134,7 @@ impl EcVolumeShard { )?; self.ecd_file = Some(file); self.ecd_file_size = 0; + self.ecd_file_id = None; Ok(()) } @@ -112,6 +163,17 @@ impl EcVolumeShard { self.ecd_file_size } + pub fn disk_check(&self) -> EcShardDiskCheck { + EcShardDiskCheck { + volume_id: self.volume_id, + shard_id: self.shard_id, + dir: self.dir.clone(), + path: self.file_name(), + mounted_size: self.ecd_file_size, + mounted_id: self.ecd_file_id, + } + } + /// A duplicate of the mounted shard handle, for a reader that has to /// outlive the store guard. /// @@ -144,6 +206,7 @@ impl EcVolumeShard { let _ = file.sync_all(); } self.ecd_file = None; + self.ecd_file_id = None; } /// Delete the shard file from disk. @@ -153,6 +216,34 @@ impl EcVolumeShard { } } +/// What the disk check needs from a mounted shard, copied out under the +/// store guard so the file system calls run after it is released. +pub struct EcShardDiskCheck { + pub volume_id: VolumeId, + pub shard_id: ShardId, + pub dir: String, + pub mounted_size: i64, + path: String, + mounted_id: Option<(u64, u64)>, +} + +impl EcShardDiskCheck { + /// How the shard file on disk disagrees with the mount: `EC_SHARD_GHOST` + /// when the path is gone or names another file than the open one, + /// `EC_SHARD_STALE_SIZE` when its size changed since the mount. + pub fn disk_mismatch(&self) -> Option<&'static str> { + let (id, len) = match path_file_id(&self.path) { + Ok(v) => v, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Some(EC_SHARD_GHOST), + Err(_) => return None, + }; + if self.mounted_id.is_some_and(|mounted| mounted != id) { + return Some(EC_SHARD_GHOST); + } + (len as i64 != self.mounted_size).then_some(EC_SHARD_STALE_SIZE) + } +} + /// ShardBits: bitmap tracking which shards are present. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct ShardBits(pub u32); diff --git a/seaweed-volume/src/storage/store.rs b/seaweed-volume/src/storage/store.rs index c9fb7b2865..1ed7053eea 100644 --- a/seaweed-volume/src/storage/store.rs +++ b/seaweed-volume/src/storage/store.rs @@ -1113,6 +1113,47 @@ impl Store { .sum() } + /// Every mounted EC shard, for `check_mounted_ec_shards`. + pub fn ec_shard_disk_checks( + &self, + ) -> Vec { + self.locations + .iter() + .flat_map(|loc| loc.ec_volumes()) + .flat_map(|(_, ecv)| ecv.shards.iter().flatten()) + .map(|shard| shard.disk_check()) + .collect() + } + + /// Compares mounted EC shards with their files on disk, logs each + /// mismatch and returns the counts per reason. + pub fn check_mounted_ec_shards( + shards: &[crate::storage::erasure_coding::ec_shard::EcShardDiskCheck], + ) -> std::collections::HashMap<&'static str, usize> { + use crate::storage::erasure_coding::ec_shard::{EC_SHARD_GHOST, EC_SHARD_STALE_SIZE}; + let mut counts = + std::collections::HashMap::from([(EC_SHARD_GHOST, 0), (EC_SHARD_STALE_SIZE, 0)]); + for shard in shards { + if let Some(reason) = shard.disk_mismatch() { + *counts.entry(reason).or_default() += 1; + tracing::warn!( + volume_id = shard.volume_id.0, + shard_id = shard.shard_id, + dir = %shard.dir, + mounted_size = shard.mounted_size, + reason, + "mounted ec shard disagrees with its file on disk" + ); + } + } + for (reason, n) in &counts { + crate::metrics::EC_SHARD_DISK_MISMATCH_GAUGE + .with_label_values(&[reason]) + .set(*n as f64); + } + counts + } + /// Total EC shard count across all locations. pub fn ec_shard_count(&self) -> usize { self.locations.iter().map(|loc| loc.ec_shard_count()).sum() @@ -3463,6 +3504,86 @@ mod tests { assert!(!std::path::Path::new(&format!("{}/expired_ec_case_9.ec00", dir)).exists()); } + #[test] + fn test_check_mounted_ec_shards_finds_ghost_and_stale_size() { + use crate::storage::erasure_coding::ec_shard::{EC_SHARD_GHOST, EC_SHARD_STALE_SIZE}; + use std::collections::HashMap; + let tmp = TempDir::new().unwrap(); + let dir = tmp.path().to_str().unwrap(); + let mut store = make_test_store(&[dir]); + std::fs::write(format!("{}/col_42.ecx", dir), [0u8; 16]).unwrap(); + let shard_path = format!("{}/col_42.ec00", dir); + std::fs::write(&shard_path, b"shard bytes").unwrap(); + store.mount_ec_shards(VolumeId(42), "col", &[0]).unwrap(); + let counts = |ghost: usize, stale: usize| { + HashMap::from([(EC_SHARD_GHOST, ghost), (EC_SHARD_STALE_SIZE, stale)]) + }; + let check = |store: &Store| Store::check_mounted_ec_shards(&store.ec_shard_disk_checks()); + assert_eq!(check(&store), counts(0, 0)); + + let mut f = std::fs::OpenOptions::new() + .append(true) + .open(&shard_path) + .unwrap(); + std::io::Write::write_all(&mut f, b"grown").unwrap(); + drop(f); + assert_eq!(check(&store), counts(0, 1)); + + let replacement = format!("{}.new", shard_path); + std::fs::write(&replacement, b"shard bytes").unwrap(); + std::fs::rename(&replacement, &shard_path).unwrap(); + assert_eq!(check(&store), counts(1, 0)); + + assert!(store.locations[0].reopen_ec_shard(VolumeId(42), 0).unwrap()); + assert_eq!(check(&store), counts(0, 0)); + + std::fs::remove_file(&shard_path).unwrap(); + assert_eq!(check(&store), counts(1, 0)); + } + + #[cfg(unix)] + #[test] + fn test_check_mounted_ec_shards_finds_an_unreadable_replacement() { + use crate::storage::erasure_coding::ec_shard::EC_SHARD_GHOST; + use std::os::unix::fs::PermissionsExt; + let tmp = TempDir::new().unwrap(); + let dir = tmp.path().to_str().unwrap(); + let mut store = make_test_store(&[dir]); + std::fs::write(format!("{}/col_42.ecx", dir), [0u8; 16]).unwrap(); + let shard_path = format!("{}/col_42.ec00", dir); + std::fs::write(&shard_path, b"shard bytes").unwrap(); + store.mount_ec_shards(VolumeId(42), "col", &[0]).unwrap(); + + let replacement = format!("{}.new", shard_path); + std::fs::write(&replacement, b"shard bytes").unwrap(); + std::fs::set_permissions(&replacement, std::fs::Permissions::from_mode(0o000)).unwrap(); + std::fs::rename(&replacement, &shard_path).unwrap(); + let counts = Store::check_mounted_ec_shards(&store.ec_shard_disk_checks()); + assert_eq!(counts[EC_SHARD_GHOST], 1); + } + + #[test] + fn test_check_mounted_ec_shards_runs_while_a_writer_holds_the_store() { + use crate::storage::erasure_coding::ec_shard::EC_SHARD_GHOST; + let tmp = TempDir::new().unwrap(); + let dir = tmp.path().to_str().unwrap(); + let mut store = make_test_store(&[dir]); + std::fs::write(format!("{}/col_42.ecx", dir), [0u8; 16]).unwrap(); + let shard_path = format!("{}/col_42.ec00", dir); + std::fs::write(&shard_path, b"shard bytes").unwrap(); + store.mount_ec_shards(VolumeId(42), "col", &[0]).unwrap(); + let store = std::sync::RwLock::new(store); + + let shards = store.read().unwrap().ec_shard_disk_checks(); + let writer = store.write().unwrap(); + std::fs::remove_file(&shard_path).unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || tx.send(Store::check_mounted_ec_shards(&shards)).unwrap()); + let counts = rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap(); + assert_eq!(counts[EC_SHARD_GHOST], 1); + drop(writer); + } + #[test] fn test_store_volume_not_found() { let tmp = TempDir::new().unwrap(); diff --git a/weed/server/volume_grpc_client_to_master.go b/weed/server/volume_grpc_client_to_master.go index 4e5c45f942..c679531bf9 100644 --- a/weed/server/volume_grpc_client_to_master.go +++ b/weed/server/volume_grpc_client_to_master.go @@ -504,6 +504,12 @@ func (vs *VolumeServer) doHeartbeatWithRetry(masterAddress pb.ServerAddress, grp } case <-ecShardTickChan.C: glog.V(4).Infof("volume server %s:%d ec heartbeat", vs.store.Ip, vs.store.Port) + if vs.ecShardCheckRunning.CompareAndSwap(false, true) { + go func() { + defer vs.ecShardCheckRunning.Store(false) + vs.store.CheckMountedEcShards() + }() + } if err = stream.Send(vs.store.CollectErasureCodingHeartbeat()); err != nil { glog.V(0).Infof("Volume Server Failed to talk with master %s: %v", masterAddress, err) return "", err diff --git a/weed/server/volume_server.go b/weed/server/volume_server.go index 3bc3de3ce0..f629cb1599 100644 --- a/weed/server/volume_server.go +++ b/weed/server/volume_server.go @@ -46,6 +46,7 @@ type VolumeServer struct { // by a leader; before first registration the retry loop reconnects // promptly instead of pacing a full pulse. confirmedLeaderOnce atomic.Bool + ecShardCheckRunning atomic.Bool pulsePeriod time.Duration dataCenter string rack string diff --git a/weed/stats/metrics.go b/weed/stats/metrics.go index 7a5b29d0d0..297ad0bcde 100644 --- a/weed/stats/metrics.go +++ b/weed/stats/metrics.go @@ -548,6 +548,14 @@ var ( Help: "Number of read only volumes.", }, []string{"collection", "type"}) + VolumeServerEcShardDiskMismatchGauge = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: Namespace, + Subsystem: subsystemVolumeServer, + Name: "ec_shard_disk_mismatch", + Help: "Mounted EC shards whose file on disk is gone or replaced (ghost) or changed size (stale_size).", + }, []string{"reason"}) + VolumeServerMaxVolumeCounter = prometheus.NewGauge( prometheus.GaugeOpts{ Namespace: Namespace, @@ -1188,6 +1196,7 @@ func init() { Gather.MustRegister(VolumeServerVolumeGauge) Gather.MustRegister(VolumeServerMaxVolumeCounter) Gather.MustRegister(VolumeServerReadOnlyVolumeGauge) + Gather.MustRegister(VolumeServerEcShardDiskMismatchGauge) Gather.MustRegister(VolumeServerDiskSizeGauge) Gather.MustRegister(VolumeServerResourceGauge) Gather.MustRegister(VolumeServerDiskErrorGauge) diff --git a/weed/storage/erasure_coding/ec_shard.go b/weed/storage/erasure_coding/ec_shard.go index 99a950a2c9..c4dc9a9b13 100644 --- a/weed/storage/erasure_coding/ec_shard.go +++ b/weed/storage/erasure_coding/ec_shard.go @@ -108,6 +108,31 @@ func (shard *EcVolumeShard) Size() int64 { return shard.ecdFileSize } +const ( + EcShardGhost = "ghost" + EcShardStaleSize = "stale_size" +) + +// DiskMismatch names how the shard file on disk disagrees with the mount: +// EcShardGhost when the path is gone or names another file than the open one, +// EcShardStaleSize when the file size changed since the mount, "" otherwise. +func (shard *EcVolumeShard) DiskMismatch() string { + onDisk, err := os.Stat(shard.FileName() + ToExt(int(shard.ShardId))) + if err != nil { + if os.IsNotExist(err) { + return EcShardGhost + } + return "" + } + if open, err := shard.ecdFile.Stat(); err == nil && !os.SameFile(onDisk, open) { + return EcShardGhost + } + if onDisk.Size() != shard.ecdFileSize { + return EcShardStaleSize + } + return "" +} + func (shard *EcVolumeShard) String() string { return fmt.Sprintf("ec shard %v:%v, dir:%s, Collection:%s", shard.VolumeId, shard.ShardId, shard.dir, shard.Collection) } diff --git a/weed/storage/store_ec.go b/weed/storage/store_ec.go index f88894d33d..c18309dae5 100644 --- a/weed/storage/store_ec.go +++ b/weed/storage/store_ec.go @@ -230,6 +230,30 @@ func ecFreeShardCount(loc *DiskLocation, dataShardCount int) int32 { return free } +// CheckMountedEcShards compares every mounted EC shard with its file on disk, +// logs each mismatch and returns the counts per reason. +func (s *Store) CheckMountedEcShards() map[string]int { + counts := map[string]int{erasure_coding.EcShardGhost: 0, erasure_coding.EcShardStaleSize: 0} + for _, location := range s.Locations { + var shards []*erasure_coding.EcVolumeShard + location.ecVolumesLock.RLock() + for _, ecVolume := range location.ecVolumes { + shards = append(shards, ecVolume.Shards...) + } + location.ecVolumesLock.RUnlock() + for _, shard := range shards { + if reason := shard.DiskMismatch(); reason != "" { + counts[reason]++ + glog.Warningf("ec shard %d.%d on %s: mounted %d bytes, %s on disk", shard.VolumeId, shard.ShardId, location.Directory, shard.Size(), reason) + } + } + } + for reason, n := range counts { + stats.VolumeServerEcShardDiskMismatchGauge.WithLabelValues(reason).Set(float64(n)) + } + return counts +} + func (s *Store) CollectErasureCodingHeartbeat() *master_pb.Heartbeat { var ecShardMessages []*master_pb.VolumeEcShardInformationMessage collectionEcShardSize := make(map[string]int64) diff --git a/weed/storage/store_ec_disk_mismatch_test.go b/weed/storage/store_ec_disk_mismatch_test.go new file mode 100644 index 0000000000..ecc9188d07 --- /dev/null +++ b/weed/storage/store_ec_disk_mismatch_test.go @@ -0,0 +1,47 @@ +package storage + +import ( + "os" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding" + "github.com/seaweedfs/seaweedfs/weed/storage/needle" + "github.com/stretchr/testify/require" +) + +func TestCheckMountedEcShardsFindsGhostAndStaleSize(t *testing.T) { + store := newEcTargetTestStore(t, 1) + collection := "col" + vid := needle.VolumeId(42) + dataDir := store.Locations[0].Directory + + writeEcShard0(t, dataDir, collection, vid) + writeEcIndex(t, dataDir, collection, vid) + shardPath := erasure_coding.EcShardFileName(collection, dataDir, int(vid)) + erasure_coding.ToExt(0) + content := make([]byte, calculateExpectedShardSize(1024*1024, 10)) + require.NoError(t, os.WriteFile(shardPath, content, 0o644)) + require.NoError(t, store.MountEcShards(collection, vid, 0, "")) + + check := func() map[string]int { return store.CheckMountedEcShards() } + require.Equal(t, map[string]int{erasure_coding.EcShardGhost: 0, erasure_coding.EcShardStaleSize: 0}, check()) + + f, err := os.OpenFile(shardPath, os.O_APPEND|os.O_WRONLY, 0) + require.NoError(t, err) + _, err = f.Write([]byte("grown")) + require.NoError(t, err) + require.NoError(t, f.Close()) + require.Equal(t, 1, check()[erasure_coding.EcShardStaleSize]) + + replacement := shardPath + ".new" + require.NoError(t, os.WriteFile(replacement, content, 0o644)) + require.NoError(t, os.Rename(replacement, shardPath)) + require.Equal(t, map[string]int{erasure_coding.EcShardGhost: 1, erasure_coding.EcShardStaleSize: 0}, check()) + + reopened, err := store.Locations[0].ReopenEcShard(vid, 0) + require.NoError(t, err) + require.True(t, reopened) + require.Equal(t, 0, check()[erasure_coding.EcShardGhost]) + + require.NoError(t, os.Remove(shardPath)) + require.Equal(t, map[string]int{erasure_coding.EcShardGhost: 1, erasure_coding.EcShardStaleSize: 0}, check()) +}