use std::path::Path;
use super::{STATUS_FILE, UNIT};
const MENU: &str = "This cloud computer: diagnostics\n\n\
Usage: ssh <user>@<computer> <command>\n\n\
status The service, the meter, the users, disk and memory\n\
help This menu\n";
pub(crate) fn run(args: &[String]) -> i32 {
let request = std::env::var("SSH_ORIGINAL_COMMAND").unwrap_or_else(|_| args.join(" "));
let words: Vec<&str> = request.split_whitespace().collect();
match words.as_slice() {
[] | ["status"] => {
print!("{}", status_text());
0
}
["help" | "--help" | "-h"] => {
print!("{MENU}");
0
}
_ => {
eprint!("Unknown diagnostic command.\n\n{MENU}");
2
}
}
}
fn status_text() -> String {
let mut out = String::from("This cloud computer\n");
out.push_str(&format!(" service {}\n", service_state()));
let owner = super::service_uid();
match owner.and_then(|uid| read_status(Path::new(STATUS_FILE), uid)) {
Some(status) => out.push_str(&status),
None => out.push_str(" status not written yet (service starting or stopped)\n"),
}
if let Some(disk) = disk_line() {
out.push_str(&disk);
}
if let Some(memory) = memory_line() {
out.push_str(&memory);
}
out
}
fn service_state() -> String {
let out = std::process::Command::new("/usr/bin/systemctl")
.args(["is-active", UNIT])
.env_clear()
.stdin(std::process::Stdio::null())
.output();
match out {
Ok(out) => {
let word: String = String::from_utf8_lossy(&out.stdout)
.trim()
.chars()
.filter(char::is_ascii_alphabetic)
.take(20)
.collect();
if word.is_empty() {
"unknown".into()
} else {
word
}
}
Err(_) => "unknown".into(),
}
}
fn read_status(path: &Path, owner: u32) -> Option<String> {
let bytes = super::secret_file::read_checked(
path,
owner,
super::secret_file::Exposure::Readable,
16 * 1024,
)
.ok()?;
let status: super::Status = serde_json::from_slice(&bytes).ok()?;
Some(status.lines())
}
#[cfg(unix)]
fn disk_line() -> Option<String> {
let root = std::ffi::CString::new("/").ok()?;
let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
if unsafe { libc::statvfs(root.as_ptr(), &raw mut st) } != 0 {
return None;
}
#[allow(clippy::unnecessary_cast, clippy::cast_lossless)]
let (block, blocks, avail) = (st.f_frsize as u64, st.f_blocks as u64, st.f_bavail as u64);
let (total, free) = (
blocks.saturating_mul(block.max(1)),
avail.saturating_mul(block.max(1)),
);
Some(format!(
" disk {} free of {}\n",
gib(free),
gib(total)
))
}
#[cfg(not(unix))]
fn disk_line() -> Option<String> {
None
}
fn memory_line() -> Option<String> {
let meminfo = std::fs::read_to_string("/proc/meminfo").ok()?;
let field = |name: &str| {
meminfo.lines().find_map(|l| {
l.strip_prefix(name)?
.trim()
.trim_end_matches("kB")
.trim()
.parse::<u64>()
.ok()
})
};
let total = field("MemTotal:")?;
let available = field("MemAvailable:")?;
Some(format!(
" memory {} available of {}\n",
gib(available * 1024),
gib(total * 1024)
))
}
fn gib(bytes: u64) -> String {
#[allow(clippy::cast_precision_loss)]
let gib = bytes as f64 / (1024.0 * 1024.0 * 1024.0);
format!("{gib:.1} GiB")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sizes_read_in_gib() {
assert_eq!(gib(0), "0.0 GiB");
assert_eq!(gib(3 * 1024 * 1024 * 1024 / 2), "1.5 GiB");
}
}