use std::path::PathBuf;
use super::Step;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MemberFacts {
pub index: u32,
pub device: String,
pub partition: String,
pub disk_bytes: u64,
pub set_bytes: u64,
pub offered_bytes: u64,
pub larger: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SurveyFacts {
pub verdict: String,
pub raid_disks: u32,
pub members: Vec<MemberFacts>,
pub eligible: bool,
pub target_sectors: Option<u64>,
pub set_uuid: String,
pub description: String,
}
impl SurveyFacts {
pub fn describe(&self) -> String {
if self.description.is_empty() {
format!(
"{} ({} of {})",
self.verdict,
self.members.len(),
self.raid_disks
)
} else {
self.description.clone()
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct IdentityFacts {
pub documents: usize,
pub bytes: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ResumeFacts {
pub documents_matched: usize,
pub drift: Vec<String>,
pub off_stripe_ms: i64,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Grown {
pub grew: bool,
pub array_bytes: u64,
pub refusal: Option<String>,
pub xfs: String,
}
impl Grown {
pub fn describe(&self) -> String {
let mut parts = vec![format!("array {} B", self.array_bytes)];
if self.grew {
parts.push("grown (G6)".into());
}
if let Some(r) = &self.refusal {
parts.push(format!("engine refused: {r}"));
}
if !self.xfs.is_empty() {
parts.push(format!("xfs: {}", self.xfs));
}
parts.join("; ")
}
}
pub trait World: Send + Sync + 'static {
fn engine_present(&self) -> bool;
fn hotplug(&self) -> bool {
crate::dashboard::probe::pci_hotplug().present
}
fn journal_path(&self) -> PathBuf;
fn journal_present(&self) -> bool {
self.journal_path().exists()
}
fn serving(&self) -> bool;
fn mounted_bytes(&self) -> u64;
fn pause_admission(&self);
fn unpause_admission(&self);
fn flush_replication(&self, ceiling: std::time::Duration) -> FlushVerdict {
let _ = ceiling;
FlushVerdict::NoStandby(
"this build links no replicator, so there is no standby to flush to".to_owned(),
)
}
fn in_flight(&self) -> u64;
fn starting(&self) -> Option<String> {
None
}
fn suspend_identity(&self, why: &str) -> Result<IdentityFacts, String>;
fn resume_identity(&self) -> Result<ResumeFacts, String>;
fn close_stores(&self) -> Result<(), String>;
fn reopen_stores(&self) -> Result<(), String>;
fn sync_and_unmount(&self) -> Result<(), String>;
fn stop_array(&self) -> Result<(), String>;
fn rescan(&self) -> Result<(), String>;
fn survey(&self) -> SurveyFacts;
fn grow_and_mount(&self) -> Result<Grown, String>;
fn epoch_for(&self, target_sectors: u64) -> u64;
fn note(&self, epoch: u64, target_sectors: u64, step: Step) -> Result<(), String>;
fn remember_nonce(&self, nonce: &str) -> Result<bool, String>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FlushVerdict {
NoStandby(String),
CaughtUp { standbys: u64, waited_ms: u64 },
Behind {
pending: u64,
needs_full_resync: bool,
why: String,
},
CouldNotLook(String),
}
pub fn twin_verdict(
members: &[String],
rows: &[gunnar_proto::TwinHeartbeat],
head: u64,
) -> Result<(u64, u64), FlushVerdict> {
if members.is_empty() {
return Ok((0, 0));
}
for m in members {
let Some(r) = rows.iter().find(|r| &r.principal == m) else {
return Err(FlushVerdict::CouldNotLook(format!(
"twin '{m}' is enrolled in group `twin` and has no heartbeat row at all"
)));
};
if r.last_seen_unix_ms == 0 {
return Err(FlushVerdict::CouldNotLook(format!(
"twin '{m}' has reported no position since this server started, so what it has applied is \
unknown; nothing says it holds this set. Wait for its next poll (every few seconds while it \
follows)"
)));
}
if r.seen_ago_ms > r.silent_after_ms {
return Err(FlushVerdict::CouldNotLook(format!(
"twin '{m}' last reported {} s ago (bound {} s), so its position is stale and says nothing about \
the set as it stands now",
r.seen_ago_ms / 1000,
r.silent_after_ms / 1000
)));
}
if head == 0 || r.applied_seq < head {
return Err(FlushVerdict::Behind {
pending: head.saturating_sub(r.applied_seq),
needs_full_resync: false,
why: format!(
"twin '{m}' has applied {} of this box's head {head}; a twin that has not taken the log cannot \
restore what is about to be unmounted",
r.applied_seq
),
});
}
}
Ok((members.len() as u64, head))
}
pub fn await_twins(
ceiling: std::time::Duration,
every: std::time::Duration,
mut look: impl FnMut() -> Result<(u64, u64), FlushVerdict>,
) -> Result<(u64, u64), FlushVerdict> {
let started = std::time::Instant::now();
loop {
match look() {
Err(FlushVerdict::Behind { .. }) if started.elapsed() < ceiling => {
std::thread::sleep(every)
}
other => return other,
}
}
}
#[derive(Debug, Default)]
pub struct NoEngine;
impl World for NoEngine {
fn engine_present(&self) -> bool {
false
}
fn journal_path(&self) -> PathBuf {
PathBuf::from(gunnar_grpc::grow_journal::JOURNAL_PATH)
}
fn serving(&self) -> bool {
true
}
fn mounted_bytes(&self) -> u64 {
0
}
fn pause_admission(&self) {}
fn unpause_admission(&self) {}
fn in_flight(&self) -> u64 {
0
}
fn suspend_identity(&self, _why: &str) -> Result<IdentityFacts, String> {
Err("no engine".into())
}
fn resume_identity(&self) -> Result<ResumeFacts, String> {
Err("no engine".into())
}
fn close_stores(&self) -> Result<(), String> {
Err("no engine".into())
}
fn reopen_stores(&self) -> Result<(), String> {
Ok(())
}
fn sync_and_unmount(&self) -> Result<(), String> {
Err("no engine".into())
}
fn stop_array(&self) -> Result<(), String> {
Err("no engine".into())
}
fn rescan(&self) -> Result<(), String> {
Ok(())
}
fn survey(&self) -> SurveyFacts {
SurveyFacts {
verdict: "none".into(),
description: "no runtime grow engine in this build".into(),
..Default::default()
}
}
fn grow_and_mount(&self) -> Result<Grown, String> {
Err("no engine".into())
}
fn epoch_for(&self, _target_sectors: u64) -> u64 {
0
}
fn note(&self, _epoch: u64, _target_sectors: u64, _step: Step) -> Result<(), String> {
Err("no engine".into())
}
fn remember_nonce(&self, _nonce: &str) -> Result<bool, String> {
Err("no engine".into())
}
}
pub const NONCE_LEDGER_FILE: &str = "grow-go-aheads";
pub fn remember_nonce_in(ledger: &std::path::Path, nonce: &str) -> Result<bool, String> {
use std::io::Write as _;
let text = std::fs::read_to_string(ledger).unwrap_or_default();
if text.lines().any(|l| l.trim() == nonce) {
return Ok(false);
}
let mut f = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(ledger)
.map_err(|e| format!("open {}: {e}", ledger.display()))?;
f.write_all(format!("{nonce}\n").as_bytes())
.and_then(|_| f.sync_all())
.map_err(|e| format!("append {}: {e}", ledger.display()))?;
Ok(true)
}
#[cfg(feature = "grow-runtime")]
pub use real::BoxWorld;
#[cfg(feature = "grow-runtime")]
mod real {
use super::*;
use std::sync::{Arc, Mutex};
use korp_installer::grow::{self as engine, runtime};
pub struct BoxWorld {
admission: Arc<gunnar_ssh::Admission>,
stores: Arc<crate::stores::ServerStores>,
db: Arc<gunnar_core::ControlDb>,
replication: Option<Arc<crate::mirror::ReplicationSlot>>,
heartbeats: Option<Arc<gunnar_grpc::heartbeat::Registry>>,
journal: Mutex<Option<engine::Journal>>,
mountpoint: PathBuf,
}
impl BoxWorld {
pub fn new(
admission: Arc<gunnar_ssh::Admission>,
stores: Arc<crate::stores::ServerStores>,
) -> Self {
let db = stores.control_db();
BoxWorld {
admission,
stores,
db,
replication: None,
heartbeats: None,
journal: Mutex::new(None),
mountpoint: runtime::data_mountpoint().to_path_buf(),
}
}
pub fn with_replication(mut self, slot: Arc<crate::mirror::ReplicationSlot>) -> Self {
self.replication = Some(slot);
self
}
pub fn with_heartbeats(mut self, registry: Arc<gunnar_grpc::heartbeat::Registry>) -> Self {
self.heartbeats = Some(registry);
self
}
fn twins_caught_up(&self, barrier: u64) -> Result<(u64, u64), FlushVerdict> {
let Some(hb) = self.heartbeats.as_ref() else {
return Err(FlushVerdict::CouldNotLook(
"no twin heartbeat registry was handed to the grow world, so what any twin has applied cannot be read on this box"
.to_owned(),
));
};
let members = self.stores.auth().members_of(crate::twin::TWIN_GROUP).map_err(|e| {
FlushVerdict::CouldNotLook(format!(
"the identity table could not be read for group `{}`, so which twins exist is unknown: {e}",
crate::twin::TWIN_GROUP
))
})?;
if members.is_empty() {
return Ok((0, 0));
}
let head = barrier;
let now = estate_clock::now_unix_ms();
let rows = hb.view(&members, now);
twin_verdict(&members, &rows, head)
}
fn with_journal<T>(
&self,
f: impl FnOnce(&mut engine::Journal) -> Result<T, String>,
) -> Result<T, String> {
let mut guard = self.journal.lock().unwrap_or_else(|p| p.into_inner());
if guard.is_none() {
let path = engine::journal_path();
let j = engine::Journal::open(&path).map_err(|e| {
format!(
"open the grow journal {}: {e} — is /serialdat mounted?",
path.display()
)
})?;
*guard = Some(j);
}
f(guard.as_mut().expect("opened above"))
}
fn log(line: &str) {
tracing::info!(target: super::super::TARGET, event = "grow.engine", "{line}");
}
}
impl World for BoxWorld {
fn engine_present(&self) -> bool {
true
}
fn journal_path(&self) -> PathBuf {
engine::journal_path()
}
fn serving(&self) -> bool {
runtime::is_mounted(&self.mountpoint) && !self.stores.suspended()
}
fn flush_replication(&self, ceiling: std::time::Duration) -> FlushVerdict {
if self.stores.is_twin() {
return FlushVerdict::NoStandby("this box is a twin: its set is a copy of its primary's, which is where it is pulled back from".to_owned());
}
let barrier = self.stores.txlog().head_seq();
let twins = match await_twins(ceiling, std::time::Duration::from_millis(250), || {
self.twins_caught_up(barrier)
}) {
Ok(t) => t,
Err(verdict) => return verdict,
};
let Some(slot) = self.replication.as_ref() else {
if twins.0 > 0 {
return FlushVerdict::CaughtUp {
standbys: twins.0,
waited_ms: 0,
};
}
return FlushVerdict::NoStandby(
"this box has no replication slot, so there is no standby to flush to"
.to_owned(),
);
};
let Some(replicator) = slot.replicator() else {
if twins.0 > 0 {
return FlushVerdict::CaughtUp {
standbys: twins.0,
waited_ms: 0,
};
}
return FlushVerdict::NoStandby(
"no replicator is running on this box (no standby configured, or this box is not a primary); there is nothing to flush and nothing to prove".to_owned(),
);
};
let started = std::time::Instant::now();
let deadline = started + ceiling;
loop {
if replicator.status().iter().all(|s| s.pending == 0)
|| std::time::Instant::now() >= deadline
{
break;
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
let status = replicator.status();
let waited_ms = started.elapsed().as_millis() as u64;
let pending: u64 = status.iter().map(|s| s.pending as u64).sum();
let needs_full_resync = status.iter().any(|s| s.needs_full_resync);
if pending == 0 && !needs_full_resync {
return FlushVerdict::CaughtUp {
standbys: status.len() as u64 + twins.0,
waited_ms,
};
}
FlushVerdict::Behind {
pending,
needs_full_resync,
why: format!(
"waited {waited_ms} ms of the {} ms the drain allows, over {} standby(s)",
ceiling.as_millis(),
status.len()
),
}
}
fn mounted_bytes(&self) -> u64 {
if !runtime::is_mounted(&self.mountpoint) {
return 0;
}
rustix::fs::statvfs(&self.mountpoint)
.map(|s| s.f_blocks * s.f_frsize)
.unwrap_or(0)
}
fn pause_admission(&self) {
self.admission.pause(gunnar_ssh::Pause::Growing);
if self.stores.is_twin() {
crate::twin::maintenance::hold(self.stores.root());
}
}
fn unpause_admission(&self) {
self.admission.unpause();
if self.stores.is_twin() {
crate::twin::maintenance::release(self.stores.root());
}
}
fn in_flight(&self) -> u64 {
self.admission.in_flight()
}
fn starting(&self) -> Option<String> {
(!crate::readiness::is_ready()).then(crate::readiness::detail)
}
fn suspend_identity(&self, why: &str) -> Result<IdentityFacts, String> {
let copy = self.db.suspend(why).map_err(|e| e.to_string())?;
Ok(IdentityFacts {
documents: copy.documents(),
bytes: copy.bytes(),
})
}
fn resume_identity(&self) -> Result<ResumeFacts, String> {
let r = self.db.resume().map_err(|e| e.to_string())?;
Ok(ResumeFacts {
documents_matched: r.documents_matched,
drift: r.drift,
off_stripe_ms: r.off_stripe_ms,
})
}
fn close_stores(&self) -> Result<(), String> {
self.stores.suspend_repos("the data set is being grown");
self.stores.txlog().release().map_err(|e| {
format!(
"release the transaction log's files under {}: {e}",
self.mountpoint.display()
)
})
}
fn reopen_stores(&self) -> Result<(), String> {
let taken = self.stores.txlog().reacquire().map_err(|e| {
format!(
"take the transaction log's files back under {}: {e}",
self.mountpoint.display()
)
});
self.stores.resume_repos();
taken
}
fn sync_and_unmount(&self) -> Result<(), String> {
runtime::unmount(&self.mountpoint)?;
nix::mount::mount(
Some("none"),
&self.mountpoint,
Some("tmpfs"),
nix::mount::MsFlags::MS_RDONLY,
Some("size=64k"),
)
.map_err(|e| format!("guard tmpfs over {}: {e}", self.mountpoint.display()))
}
fn stop_array(&self) -> Result<(), String> {
runtime::stop_array(std::time::Duration::from_secs(10))
}
fn rescan(&self) -> Result<(), String> {
runtime::pci_rescan()
}
fn survey(&self) -> SurveyFacts {
let s = runtime::survey();
SurveyFacts {
verdict: s.verdict.clone(),
raid_disks: s.raid_disks,
eligible: s.eligible(),
target_sectors: s.target_sectors(),
set_uuid: s.set_uuid.clone(),
description: s.describe(),
members: s
.members
.iter()
.map(|m| MemberFacts {
index: m.index,
device: m.disk.clone(),
partition: m.partition.clone(),
disk_bytes: m.disk_sectors * 512,
set_bytes: m.set_sectors * 512,
offered_bytes: m.device_offers * 512,
larger: m.larger,
})
.collect(),
}
}
fn grow_and_mount(&self) -> Result<Grown, String> {
if runtime::is_mounted(&self.mountpoint) {
nix::mount::umount2(&self.mountpoint, nix::mount::MntFlags::empty())
.map_err(|e| format!("unguard {}: {e}", self.mountpoint.display()))?;
}
let mountpoint = self.mountpoint.clone();
let mounted =
self.with_journal(|j| runtime::grow_and_mount(j, &mountpoint, &mut Self::log))?;
Ok(Grown {
grew: mounted.grew,
array_bytes: mounted.array_bytes,
refusal: mounted.refusal,
xfs: match &mounted.xfs {
None => String::new(),
Some(Ok((plan, after))) => format!("{plan:?} → {after} blocks"),
Some(Err(e)) => format!("FAILED: {e}"),
},
})
}
fn epoch_for(&self, target_sectors: u64) -> u64 {
self.with_journal(|j| Ok(j.epoch_for(target_sectors)))
.unwrap_or(0)
}
fn note(&self, epoch: u64, target_sectors: u64, step: Step) -> Result<(), String> {
let step = match step {
Step::Drain => engine::Step::Drain,
Step::Unmount => engine::Step::Unmount,
Step::Stop => engine::Step::Stop,
Step::Wait => engine::Step::Wait,
Step::Rescan => engine::Step::Rescan,
Step::Reopen => engine::Step::Reopen,
Step::Abort => engine::Step::Abort,
Step::Fail => engine::Step::Fail,
};
self.with_journal(|j| runtime::note(j, epoch, target_sectors, step).map(|_| ()))
}
fn remember_nonce(&self, nonce: &str) -> Result<bool, String> {
let ledger = engine::journal_path().with_file_name(NONCE_LEDGER_FILE);
remember_nonce_in(&ledger, nonce)
}
}
}
#[cfg(test)]
mod twin_verdict_tests {
use super::*;
fn row(
principal: &str,
applied: u64,
head: u64,
seen_ago_ms: u64,
last_seen: i64,
) -> gunnar_proto::TwinHeartbeat {
gunnar_proto::TwinHeartbeat {
principal: principal.to_owned(),
applied_seq: applied,
head_seq: head,
lag_entries: head.saturating_sub(applied),
last_seen_unix_ms: last_seen,
seen_ago_ms,
silent_after_ms: 60_000,
..Default::default()
}
}
fn twin() -> Vec<String> {
vec!["gunnar-twin".to_owned()]
}
#[test]
fn a_twin_reporting_zero_of_zero_is_never_caught_up() {
let rows = [row("gunnar-twin", 0, 0, 500, 1_790_000_000_000)];
assert_eq!(rows[0].lag_entries, 0, "the trap: lag zero");
match twin_verdict(&twin(), &rows, 318) {
Err(FlushVerdict::Behind { pending, why, .. }) => {
assert_eq!(pending, 318);
assert!(why.contains("applied 0 of this box's head 318"), "{why}");
}
other => panic!("a twin holding nothing must never be caught up: {other:?}"),
}
}
#[test]
fn a_twin_past_the_barrier_is_caught_up() {
let rows = [row("gunnar-twin", 320, 321, 500, 1_790_000_000_000)];
assert_eq!(twin_verdict(&twin(), &rows, 318), Ok((1, 318)));
let behind = [row("gunnar-twin", 317, 321, 500, 1_790_000_000_000)];
assert!(matches!(
twin_verdict(&twin(), &behind, 318),
Err(FlushVerdict::Behind { pending: 1, .. })
));
}
#[test]
fn a_twin_applied_up_to_the_head_is_caught_up() {
let rows = [row("gunnar-twin", 318, 318, 500, 1_790_000_000_000)];
assert_eq!(twin_verdict(&twin(), &rows, 318), Ok((1, 318)));
}
#[test]
fn a_twin_one_entry_behind_is_behind() {
let rows = [row("gunnar-twin", 317, 318, 500, 1_790_000_000_000)];
assert!(matches!(
twin_verdict(&twin(), &rows, 318),
Err(FlushVerdict::Behind { pending: 1, .. })
));
}
#[test]
fn a_twin_that_never_reported_could_not_be_looked_at() {
let rows = [row("gunnar-twin", 0, 0, 0, 0)];
match twin_verdict(&twin(), &rows, 318) {
Err(FlushVerdict::CouldNotLook(why)) => {
assert!(
why.contains("reported no position since this server started"),
"{why}"
);
assert!(why.contains("gunnar-twin"), "{why}");
}
other => panic!("expected CouldNotLook: {other:?}"),
}
}
#[test]
fn a_stale_position_could_not_be_looked_at() {
let rows = [row("gunnar-twin", 318, 318, 120_000, 1_790_000_000_000)];
assert!(matches!(
twin_verdict(&twin(), &rows, 318),
Err(FlushVerdict::CouldNotLook(_))
));
}
#[test]
fn an_enrolled_twin_with_no_row_could_not_be_looked_at() {
assert!(matches!(
twin_verdict(&twin(), &[], 318),
Err(FlushVerdict::CouldNotLook(_))
));
}
#[test]
fn a_head_of_zero_is_not_a_flush() {
let rows = [row("gunnar-twin", 0, 0, 500, 1_790_000_000_000)];
assert!(
twin_verdict(&twin(), &rows, 0).is_err(),
"applied == head == 0 must not pass"
);
}
#[test]
fn no_enrolled_twin_is_nothing_to_prove() {
assert_eq!(twin_verdict(&[], &[], 318), Ok((0, 0)));
}
#[test]
fn one_lagging_twin_among_two_refuses() {
let members = vec!["twin-a".to_owned(), "twin-b".to_owned()];
let rows = [
row("twin-a", 318, 318, 500, 1_790_000_000_000),
row("twin-b", 12, 318, 500, 1_790_000_000_000),
];
match twin_verdict(&members, &rows, 318) {
Err(FlushVerdict::Behind { why, .. }) => assert!(why.contains("twin-b"), "{why}"),
other => panic!("expected twin-b to refuse: {other:?}"),
}
}
}
#[cfg(all(test, feature = "grow-runtime"))]
mod twin_flush_tests {
use super::*;
use std::sync::Arc;
#[test]
fn a_twin_has_no_standby_to_flush_to() {
let d = tempfile::tempdir().unwrap();
let stores = Arc::new(crate::stores::ServerStores::open(d.path()).unwrap());
stores.mark_twin();
let w = BoxWorld::new(Arc::new(gunnar_ssh::Admission::new(None, None)), stores);
match w.flush_replication(std::time::Duration::from_millis(50)) {
FlushVerdict::NoStandby(why) => assert!(why.contains("this box is a twin"), "{why}"),
other => panic!("a twin must answer NoStandby: {other:?}"),
}
}
}