Server half of sccache-dash
Polls sccache's counters every 10 s, keeps a JSON-lines history, and serves the page and its API on 127.0.0.1: one difference-with-reset mechanism behind every range, per-language time saved, problems, a copyable summary, and extra tables for multi-level and distributed caches. The page is embedded from crates/ui/dist when it exists, with a placeholder until then. POST /api/zero refuses foreign Host and Origin headers. Tests run against a stand-in sccache script; sample fixtures for the multi-level and distributed shapes are made up.
This commit is contained in:
1 parent
a8e7bd66cf
commit
3cbc02e631
18 files changed
+3654
No files matched your search
@@ -0,0 +1,295 @@
|
||||
//! What the service knows right now, and how it is kept up to date.
|
||||
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::io::{ErrorKind, Read};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use sccache_dash_api::{Range, View};
|
||||
use serde_json::Value;
|
||||
use wait_timeout::ChildExt;
|
||||
|
||||
use crate::history::{self, Reading};
|
||||
use crate::stats::{self, Counters, Snapshot};
|
||||
use crate::view;
|
||||
|
||||
/// How often sccache is asked for its counters.
|
||||
pub const POLL: Duration = Duration::from_secs(10);
|
||||
/// A line is saved when the counters change, and at least this often besides, so that time
|
||||
/// with the service running can be told from time it was not.
|
||||
pub const HEARTBEAT_SECS: i64 = 600;
|
||||
/// Never more than one saved line per minute.
|
||||
pub const MIN_LINE_SECS: i64 = 60;
|
||||
/// A sccache command that takes longer than this counts as failed.
|
||||
const COMMAND_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
const PRUNE_EVERY: Duration = Duration::from_secs(86_400);
|
||||
|
||||
pub struct Config {
|
||||
/// The sccache command the service runs.
|
||||
pub sccache: OsString,
|
||||
/// Where the history is saved.
|
||||
pub history: PathBuf,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// `SCCACHE_DASH_SCCACHE` names the sccache command (`sccache` when unset); the history
|
||||
/// lives in `$XDG_DATA_HOME/sccache-dash`.
|
||||
pub fn from_env() -> Result<Config, String> {
|
||||
let sccache = std::env::var_os("SCCACHE_DASH_SCCACHE").unwrap_or_else(|| "sccache".into());
|
||||
let dir = dirs::data_dir()
|
||||
.ok_or("cannot find the data directory ($XDG_DATA_HOME, or ~/.local/share)")?;
|
||||
Ok(Config {
|
||||
sccache,
|
||||
history: dir.join("sccache-dash").join("history.jsonl"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unix_now() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs() as i64)
|
||||
}
|
||||
|
||||
/// What happened between two consecutive saved readings, dated when the later one was taken.
|
||||
pub struct Interval {
|
||||
pub end: i64,
|
||||
/// sccache's counters went back to zero in this interval.
|
||||
pub reset: bool,
|
||||
pub delta: Counters,
|
||||
}
|
||||
|
||||
/// The last reading sccache answered.
|
||||
pub struct Live {
|
||||
pub at: i64,
|
||||
pub snapshot: Snapshot,
|
||||
/// sccache's output, exactly as it printed it.
|
||||
pub raw_text: String,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct State {
|
||||
/// The saved readings, oldest first.
|
||||
pub readings: Vec<Reading>,
|
||||
/// One per reading after the first.
|
||||
pub intervals: Vec<Interval>,
|
||||
pub live: Option<Live>,
|
||||
/// sccache's output of the last good reading, as JSON.
|
||||
pub raw: Option<Value>,
|
||||
pub client_version: Option<String>,
|
||||
/// Why there is no live reading.
|
||||
pub error: Option<String>,
|
||||
/// Whether a failure to save has already been reported.
|
||||
pub warned: bool,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// Adds a reading to the end of the history, with what changed since the one before it.
|
||||
pub fn push(&mut self, reading: Reading) {
|
||||
if let Some(last) = self.readings.last() {
|
||||
let (delta, reset) = reading.c.since(&last.c);
|
||||
self.intervals.push(Interval {
|
||||
end: reading.t,
|
||||
reset,
|
||||
delta,
|
||||
});
|
||||
}
|
||||
self.readings.push(reading);
|
||||
}
|
||||
|
||||
/// Works out again what changed between the saved readings, after they were pruned.
|
||||
pub fn relink(&mut self) {
|
||||
self.intervals = self
|
||||
.readings
|
||||
.windows(2)
|
||||
.map(|w| {
|
||||
let (delta, reset) = w[1].c.since(&w[0].c);
|
||||
Interval {
|
||||
end: w[1].t,
|
||||
reset,
|
||||
delta,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct App {
|
||||
pub cfg: Config,
|
||||
state: Mutex<State>,
|
||||
pruned: Mutex<Instant>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// Loads the saved history, deleting what is older than 30 days.
|
||||
pub fn new(cfg: Config, now: i64) -> Result<App, String> {
|
||||
let mut state = State {
|
||||
readings: history::load(&cfg.history),
|
||||
..State::default()
|
||||
};
|
||||
history::prune(&mut state.readings, &cfg.history, now)
|
||||
.map_err(|e| format!("cannot prune {}: {e}", cfg.history.display()))?;
|
||||
state.relink();
|
||||
let pruned = Mutex::new(Instant::now());
|
||||
Ok(App {
|
||||
cfg,
|
||||
state: Mutex::new(state),
|
||||
pruned,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn lock(&self) -> MutexGuard<'_, State> {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
pub fn view(&self, range: Range) -> View {
|
||||
view::build(&self.lock(), range, unix_now())
|
||||
}
|
||||
|
||||
pub fn poll(&self) {
|
||||
self.poll_at(unix_now());
|
||||
}
|
||||
|
||||
/// Asks sccache for its counters and version, and saves a line when one is due.
|
||||
pub fn poll_at(&self, now: i64) {
|
||||
let version = run(&self.cfg.sccache, &["--version"])
|
||||
.ok()
|
||||
.and_then(|text| {
|
||||
text.split_whitespace()
|
||||
.find(|w| w.starts_with(|c: char| c.is_ascii_digit()))
|
||||
.map(str::to_owned)
|
||||
});
|
||||
let read = run(
|
||||
&self.cfg.sccache,
|
||||
&["--show-stats", "--stats-format", "json"],
|
||||
)
|
||||
.and_then(|text| stats::parse(&text).map(|snapshot| (text, snapshot)));
|
||||
let mut state = self.lock();
|
||||
state.client_version = version;
|
||||
match read {
|
||||
Ok((text, snapshot)) => {
|
||||
let live = Live {
|
||||
at: now,
|
||||
snapshot,
|
||||
raw_text: text,
|
||||
};
|
||||
state.raw = serde_json::from_str(&live.raw_text).ok();
|
||||
let due = match state.readings.last() {
|
||||
None => true,
|
||||
Some(last) => {
|
||||
last.c != live.snapshot.counters || now - last.t >= HEARTBEAT_SECS
|
||||
}
|
||||
};
|
||||
let too_soon = state
|
||||
.readings
|
||||
.last()
|
||||
.is_some_and(|last| now - last.t < MIN_LINE_SECS);
|
||||
state.error = None;
|
||||
state.live = Some(live);
|
||||
if due && !too_soon {
|
||||
self.save(&mut state, now);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
state.error = Some(e);
|
||||
state.live = None;
|
||||
state.raw = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn save(&self, state: &mut State, now: i64) {
|
||||
let reading = Reading {
|
||||
t: now,
|
||||
c: state
|
||||
.live
|
||||
.as_ref()
|
||||
.map_or_else(Counters::default, |l| l.snapshot.counters.clone()),
|
||||
};
|
||||
match history::append(&self.cfg.history, &reading) {
|
||||
Ok(()) => state.push(reading),
|
||||
Err(e) => {
|
||||
if !state.warned {
|
||||
state.warned = true;
|
||||
eprintln!(
|
||||
"sccache-dash: cannot save history to {}: {e}",
|
||||
self.cfg.history.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `sccache --zero-stats`; the saved history stays as it is.
|
||||
pub fn zero(&self) -> Result<(), String> {
|
||||
run(&self.cfg.sccache, &["--zero-stats"])?;
|
||||
self.poll();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Asks sccache for its counters every [`POLL`] and prunes the history once a day, until
|
||||
/// the process ends.
|
||||
pub fn keep_updated(self: Arc<Self>) {
|
||||
thread::spawn(move || loop {
|
||||
self.poll();
|
||||
let mut pruned = self.pruned.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if pruned.elapsed() >= PRUNE_EVERY {
|
||||
*pruned = Instant::now();
|
||||
let mut state = self.lock();
|
||||
match history::prune(&mut state.readings, &self.cfg.history, unix_now()) {
|
||||
Ok(_) => state.relink(),
|
||||
Err(e) if !state.warned => {
|
||||
state.warned = true;
|
||||
eprintln!(
|
||||
"sccache-dash: cannot prune {}: {e}",
|
||||
self.cfg.history.display()
|
||||
);
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
thread::sleep(POLL);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs sccache and returns what it printed; `Err` says why when it is missing, fails or hangs.
|
||||
fn run(sccache: &OsStr, args: &[&str]) -> Result<String, String> {
|
||||
let mut child = Command::new(sccache)
|
||||
.args(args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.map_err(|e| match e.kind() {
|
||||
ErrorKind::NotFound => format!(
|
||||
"`{} {}`: command not found",
|
||||
sccache.to_string_lossy(),
|
||||
args.join(" ")
|
||||
),
|
||||
_ => format!("`{} {}`: {e}", sccache.to_string_lossy(), args.join(" ")),
|
||||
})?;
|
||||
let named = format!("`{} {}`", sccache.to_string_lossy(), args.join(" "));
|
||||
match child.wait_timeout(COMMAND_TIMEOUT) {
|
||||
Ok(Some(status)) if status.success() => {}
|
||||
Ok(Some(status)) => return Err(format!("{named} exited with {status}")),
|
||||
Ok(None) => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(format!(
|
||||
"{named} did not answer within {} seconds",
|
||||
COMMAND_TIMEOUT.as_secs()
|
||||
));
|
||||
}
|
||||
Err(e) => return Err(format!("{named}: {e}")),
|
||||
}
|
||||
let mut text = String::new();
|
||||
if let Some(mut out) = child.stdout.take() {
|
||||
out.read_to_string(&mut text)
|
||||
.map_err(|e| format!("{named}: {e}"))?;
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//! The saved history: one compact JSON line per reading, oldest first.
|
||||
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{self, Write};
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::stats::Counters;
|
||||
|
||||
/// Readings older than this are deleted.
|
||||
pub const KEEP_DAYS: i64 = 30;
|
||||
|
||||
/// sccache's counters at one moment.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Reading {
|
||||
/// Unix seconds.
|
||||
pub t: i64,
|
||||
#[serde(default)]
|
||||
pub c: Counters,
|
||||
}
|
||||
|
||||
/// The saved readings; a line that cannot be read is skipped, not fatal.
|
||||
pub fn load(path: &Path) -> Vec<Reading> {
|
||||
std::fs::read_to_string(path)
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.filter_map(read_line)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One saved line. A counter the line does not have (it was written by another version of this
|
||||
/// program) reads as zero rather than making the whole line unreadable.
|
||||
fn read_line(line: &str) -> Option<Reading> {
|
||||
let mut value: Value = serde_json::from_str(line).ok()?;
|
||||
let defaults = serde_json::to_value(Counters::default()).ok()?;
|
||||
if let Some(counters) = value.get_mut("c") {
|
||||
fill_in(counters, &defaults);
|
||||
}
|
||||
serde_json::from_value(value).ok()
|
||||
}
|
||||
|
||||
/// Adds the keys of `defaults` that `value` lacks, recursively.
|
||||
fn fill_in(value: &mut Value, defaults: &Value) {
|
||||
let (Some(value), Some(defaults)) = (value.as_object_mut(), defaults.as_object()) else {
|
||||
return;
|
||||
};
|
||||
for (key, default) in defaults {
|
||||
match value.get_mut(key) {
|
||||
None => {
|
||||
value.insert(key.clone(), default.clone());
|
||||
}
|
||||
Some(found) => fill_in(found, default),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds one line to the end.
|
||||
pub fn append(path: &Path, reading: &Reading) -> io::Result<()> {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let mut line = serde_json::to_string(reading)?;
|
||||
line.push('\n');
|
||||
OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(path)?
|
||||
.write_all(line.as_bytes())
|
||||
}
|
||||
|
||||
/// Deletes the readings older than [`KEEP_DAYS`], rewriting the file, and says how many went.
|
||||
pub fn prune(readings: &mut Vec<Reading>, path: &Path, now: i64) -> io::Result<usize> {
|
||||
let cutoff = now - KEEP_DAYS * 86_400;
|
||||
let keep = readings.iter().filter(|r| r.t >= cutoff).count();
|
||||
let removed = readings.len() - keep;
|
||||
if removed == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
readings.drain(..removed);
|
||||
let mut text = String::new();
|
||||
for r in readings.iter() {
|
||||
text.push_str(&serde_json::to_string(r)?);
|
||||
text.push('\n');
|
||||
}
|
||||
let tmp = path.with_extension("jsonl.tmp");
|
||||
std::fs::write(&tmp, text)?;
|
||||
std::fs::rename(&tmp, path)?;
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn reading(t: i64, requests: u64) -> Reading {
|
||||
Reading {
|
||||
t,
|
||||
c: Counters {
|
||||
totals: sccache_dash_api::Totals {
|
||||
requests,
|
||||
..Default::default()
|
||||
},
|
||||
..Counters::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_lines_are_deleted_at_startup() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("history.jsonl");
|
||||
let (day, now) = (86_400, 1_764_000_000);
|
||||
for (t, n) in [
|
||||
(now - 31 * day, 1),
|
||||
(now - 30 * day + 3600, 2),
|
||||
(now - 3600, 3),
|
||||
(now, 4),
|
||||
] {
|
||||
append(&path, &reading(t, n)).unwrap();
|
||||
}
|
||||
|
||||
let mut readings = load(&path);
|
||||
assert_eq!(readings.len(), 4);
|
||||
assert_eq!(prune(&mut readings, &path, now).unwrap(), 1);
|
||||
assert_eq!(
|
||||
readings,
|
||||
vec![
|
||||
reading(now - 30 * day + 3600, 2),
|
||||
reading(now - 3600, 3),
|
||||
reading(now, 4)
|
||||
]
|
||||
);
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let lines: Vec<_> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 3, "the file itself was rewritten");
|
||||
assert!(lines[0].contains("\"requests\":2"));
|
||||
assert!(
|
||||
!path.with_extension("jsonl.tmp").exists(),
|
||||
"the temporary file is gone"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
prune(&mut readings, &path, now).unwrap(),
|
||||
0,
|
||||
"nothing more to delete"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_or_damaged_file_is_not_fatal() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("nested").join("history.jsonl");
|
||||
assert!(load(&path).is_empty(), "no file yet");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(
|
||||
&path,
|
||||
"{\"t\":1,\"c\":{\"totals\":{\"requests\":7}}}\nnot json\n{\"t\":2}\n",
|
||||
)
|
||||
.unwrap();
|
||||
let readings = load(&path);
|
||||
assert_eq!(readings.len(), 2, "the unreadable line is skipped");
|
||||
assert_eq!(readings[0].c.totals.requests, 7);
|
||||
assert_eq!(
|
||||
readings[1],
|
||||
Reading {
|
||||
t: 2,
|
||||
c: Counters::default()
|
||||
},
|
||||
"missing counters read as zero"
|
||||
);
|
||||
assert_eq!(
|
||||
prune(&mut readings.clone(), &path, 1_764_000_000).unwrap(),
|
||||
2,
|
||||
"both are older than 30 days"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&path).unwrap(),
|
||||
"",
|
||||
"and the file is emptied"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
//! The HTTP side: three routes and the page's files, on 127.0.0.1 only.
|
||||
|
||||
use std::io::Cursor;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
|
||||
use include_dir::{include_dir, Dir};
|
||||
use sccache_dash_api::Range;
|
||||
use serde_json::Value;
|
||||
use tiny_http::{Header, Request, Response, Server};
|
||||
|
||||
use crate::app::App;
|
||||
use crate::pretty;
|
||||
|
||||
/// The page as `trunk build` wrote it to crates/ui/dist, or a placeholder saying it is not built
|
||||
/// (the build script names the folder in `DASH_SITE`).
|
||||
static SITE: Dir<'_> = include_dir!("$DASH_SITE");
|
||||
|
||||
type Reply = Response<Cursor<Vec<u8>>>;
|
||||
|
||||
/// Serves until the process ends.
|
||||
pub fn serve(app: Arc<App>, port: u16) -> Result<(), String> {
|
||||
answer(listen(port)?, app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Binds 127.0.0.1 and nothing else; port 0 picks a free one.
|
||||
pub fn listen(port: u16) -> Result<Server, String> {
|
||||
Server::http(SocketAddr::from(([127, 0, 0, 1], port)))
|
||||
.map_err(|e| format!("cannot listen on 127.0.0.1:{port}: {e}"))
|
||||
}
|
||||
|
||||
/// The port a listening server answers on.
|
||||
pub fn port_of(server: &Server) -> u16 {
|
||||
server.server_addr().to_ip().map_or(0, |a| a.port())
|
||||
}
|
||||
|
||||
/// Answers requests until the process ends.
|
||||
pub fn answer(server: Server, app: Arc<App>) {
|
||||
let port = port_of(&server);
|
||||
for mut request in server.incoming_requests() {
|
||||
let app = Arc::clone(&app);
|
||||
thread::spawn(move || {
|
||||
let response = handle(&app, port, &mut request);
|
||||
let _ = request.respond(response);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn handle(app: &App, port: u16, req: &mut Request) -> Reply {
|
||||
let url = req.url();
|
||||
let (path, query) = url.split_once('?').unwrap_or((url, ""));
|
||||
match (req.method().as_str(), path) {
|
||||
("GET", "/api/view") => match range_of(query) {
|
||||
Some(range) => reply(
|
||||
200,
|
||||
"application/json",
|
||||
serde_json::to_vec(&app.view(range)).unwrap_or_default(),
|
||||
)
|
||||
.with_header(header("Cache-Control", "no-store")),
|
||||
None => text(400, "unknown range: use 1h, 24h, 7d, 30d or reset"),
|
||||
},
|
||||
("GET" | "HEAD", "/api/export") => export(app),
|
||||
("POST", "/api/zero") => zero(app, port, req),
|
||||
(_, "/api/zero") => text(405, "use POST"),
|
||||
("GET" | "HEAD", _) => site_file(path),
|
||||
_ => text(404, "not found"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `range=24h` in the query string.
|
||||
fn range_of(query: &str) -> Option<Range> {
|
||||
let value = query.split('&').find_map(|p| p.strip_prefix("range="))?;
|
||||
serde_json::from_value(Value::String(value.to_owned())).ok()
|
||||
}
|
||||
|
||||
/// sccache's output exactly as it printed it, as a download.
|
||||
fn export(app: &App) -> Reply {
|
||||
let state = app.lock();
|
||||
match &state.live {
|
||||
Some(live) => reply(200, "application/json", live.raw_text.clone().into_bytes())
|
||||
.with_header(header(
|
||||
"Content-Disposition",
|
||||
&format!(
|
||||
"attachment; filename=\"sccache-stats-{}.json\"",
|
||||
pretty::stamp(live.at)
|
||||
),
|
||||
)),
|
||||
None => text(
|
||||
502,
|
||||
&format!(
|
||||
"sccache did not answer: {}",
|
||||
state.error.as_deref().unwrap_or("no reading yet")
|
||||
),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `sccache --zero-stats`. Only this machine's own dashboard may ask for that.
|
||||
fn zero(app: &App, port: u16, req: &Request) -> Reply {
|
||||
if !from_own_page(req, port) {
|
||||
return text(
|
||||
403,
|
||||
"refused: only the dashboard's own page, on this machine, may zero the stats",
|
||||
);
|
||||
}
|
||||
match app.zero() {
|
||||
Ok(()) => text(
|
||||
200,
|
||||
"sccache's counters were zeroed; the saved history is kept",
|
||||
),
|
||||
Err(e) => text(502, &format!("could not zero the stats: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a request comes from the dashboard itself: its `Host` is localhost, and when a web
|
||||
/// page sent it (it carries an `Origin`) that page is this server. A page anywhere else must
|
||||
/// not be able to zero the stats, and neither may a host name that merely resolves here.
|
||||
fn from_own_page(req: &Request, port: u16) -> bool {
|
||||
let header = |name: &'static str| {
|
||||
req.headers()
|
||||
.iter()
|
||||
.find(|h| h.field.equiv(name))
|
||||
.map(|h| h.value.as_str())
|
||||
};
|
||||
// `name` or `name:port`, with a port made of digits and nothing else.
|
||||
let host_is_local = |host: &str| {
|
||||
let mut parts = host.splitn(2, ':');
|
||||
let name = parts.next().unwrap_or_default();
|
||||
let port = parts.next().unwrap_or("");
|
||||
(name.eq_ignore_ascii_case("127.0.0.1") || name.eq_ignore_ascii_case("localhost"))
|
||||
&& port.bytes().all(|b| b.is_ascii_digit())
|
||||
};
|
||||
let own_origins = [
|
||||
format!("http://127.0.0.1:{port}"),
|
||||
format!("http://localhost:{port}"),
|
||||
];
|
||||
header("Host").is_some_and(host_is_local)
|
||||
&& header("Origin").is_none_or(|origin| own_origins.iter().any(|own| own == origin))
|
||||
}
|
||||
|
||||
/// A file of the page; `/` is its index.
|
||||
fn site_file(path: &str) -> Reply {
|
||||
let name = path.trim_start_matches('/');
|
||||
let name = if name.is_empty() { "index.html" } else { name };
|
||||
match SITE.get_file(name) {
|
||||
Some(file) => reply(200, content_type(name), file.contents().to_vec()),
|
||||
None => text(404, "not found"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Content types by file extension, as the page's own files need them.
|
||||
fn content_type(path: &str) -> &'static str {
|
||||
match path.rsplit_once('.').map(|(_, ext)| ext) {
|
||||
Some("html") => "text/html; charset=utf-8",
|
||||
Some("js" | "mjs") => "text/javascript; charset=utf-8",
|
||||
Some("wasm") => "application/wasm",
|
||||
Some("css") => "text/css; charset=utf-8",
|
||||
Some("json" | "map") => "application/json",
|
||||
Some("svg") => "image/svg+xml",
|
||||
Some("png") => "image/png",
|
||||
Some("jpg" | "jpeg") => "image/jpeg",
|
||||
Some("gif") => "image/gif",
|
||||
Some("webp") => "image/webp",
|
||||
Some("ico") => "image/x-icon",
|
||||
Some("woff") => "font/woff",
|
||||
Some("woff2") => "font/woff2",
|
||||
Some("ttf") => "font/ttf",
|
||||
Some("otf") => "font/otf",
|
||||
Some("txt" | "md") => "text/plain; charset=utf-8",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
}
|
||||
|
||||
fn header(name: &'static str, value: &str) -> Header {
|
||||
Header::from_bytes(name.as_bytes(), value.as_bytes()).expect("a header made of plain ASCII")
|
||||
}
|
||||
|
||||
fn reply(code: u16, content_type: &str, body: Vec<u8>) -> Reply {
|
||||
Response::from_data(body)
|
||||
.with_status_code(code)
|
||||
.with_header(header("Content-Type", content_type))
|
||||
}
|
||||
|
||||
fn text(code: u16, body: &str) -> Reply {
|
||||
reply(code, "text/plain; charset=utf-8", body.as_bytes().to_vec())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_page_or_its_placeholder_is_in_the_binary() {
|
||||
assert!(
|
||||
SITE.get_file("index.html").is_some(),
|
||||
"`/` must answer with a page"
|
||||
);
|
||||
assert!(
|
||||
SITE.get_file("../Cargo.toml").is_none(),
|
||||
"nothing outside the page is served"
|
||||
);
|
||||
assert!(SITE.get_file("no-such-file").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_types_are_what_browsers_need() {
|
||||
assert_eq!(content_type("index.html"), "text/html; charset=utf-8");
|
||||
assert_eq!(
|
||||
content_type("app-a1b2c3.js"),
|
||||
"text/javascript; charset=utf-8"
|
||||
);
|
||||
assert_eq!(content_type("app-a1b2c3.wasm"), "application/wasm");
|
||||
assert_eq!(content_type("app.css"), "text/css; charset=utf-8");
|
||||
assert_eq!(content_type("icons/sccache.svg"), "image/svg+xml");
|
||||
assert_eq!(content_type("data"), "application/octet-stream");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_range_comes_from_the_query_string() {
|
||||
for (query, expected) in [
|
||||
("range=1h", Some(Range::Hour)),
|
||||
("range=24h", Some(Range::Day)),
|
||||
("range=7d", Some(Range::Week)),
|
||||
("range=30d", Some(Range::Month)),
|
||||
("range=reset", Some(Range::SinceReset)),
|
||||
("other=1&range=24h", Some(Range::Day)),
|
||||
("", None),
|
||||
("range=all", None),
|
||||
] {
|
||||
assert_eq!(range_of(query), expected, "{query:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//! The server half of sccache-dash: it asks sccache for its counters, keeps their history and
|
||||
//! serves the page that draws them.
|
||||
|
||||
pub mod app;
|
||||
pub mod history;
|
||||
pub mod http;
|
||||
pub mod pretty;
|
||||
pub mod stats;
|
||||
pub mod systemd;
|
||||
pub mod view;
|
||||
@@ -0,0 +1,163 @@
|
||||
//! `sccache-dash`: serves the dashboard, or installs itself as a user service.
|
||||
|
||||
use std::process::{Command as Process, Stdio};
|
||||
use std::sync::Arc;
|
||||
|
||||
use sccache_dash::app::{unix_now, App, Config};
|
||||
use sccache_dash::{http, systemd};
|
||||
|
||||
const USAGE: &str = "\
|
||||
sccache-dash [--port N] [--no-open] serve the dashboard on http://127.0.0.1:8226 and open it
|
||||
sccache-dash install start it at login, as a systemd user service
|
||||
sccache-dash uninstall remove that service again";
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if let Err(e) = run(&args) {
|
||||
eprintln!("sccache-dash: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn run(args: &[String]) -> Result<(), String> {
|
||||
match parse(args)? {
|
||||
Command::Help => println!("{USAGE}"),
|
||||
Command::Install => systemd::install()?,
|
||||
Command::Uninstall => systemd::uninstall()?,
|
||||
Command::Serve { port, open } => serve(port, open)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What the command line asks for.
|
||||
#[derive(Debug)]
|
||||
enum Command {
|
||||
Serve { port: u16, open: bool },
|
||||
Install,
|
||||
Uninstall,
|
||||
Help,
|
||||
}
|
||||
|
||||
fn parse(args: &[String]) -> Result<Command, String> {
|
||||
let mut serve = Command::Serve {
|
||||
port: sccache_dash_api::DEFAULT_PORT,
|
||||
open: true,
|
||||
};
|
||||
let mut i = 0;
|
||||
while let Some(arg) = args.get(i) {
|
||||
i += 1;
|
||||
match arg.as_str() {
|
||||
"--no-open" => {
|
||||
if let Command::Serve { open, .. } = &mut serve {
|
||||
*open = false;
|
||||
}
|
||||
}
|
||||
"--help" | "-h" => return Ok(Command::Help),
|
||||
"install" => return Ok(Command::Install),
|
||||
"uninstall" => return Ok(Command::Uninstall),
|
||||
a if a == "--port" || a.starts_with("--port=") => {
|
||||
let value = match a.strip_prefix("--port=") {
|
||||
Some(value) => value.to_owned(),
|
||||
None => {
|
||||
i += 1;
|
||||
args.get(i - 1)
|
||||
.ok_or("--port needs a number, as in --port 8226")?
|
||||
.clone()
|
||||
}
|
||||
};
|
||||
let port = value
|
||||
.parse()
|
||||
.map_err(|_| format!("`{value}` is not a port number"))?;
|
||||
if let Command::Serve { port: p, .. } = &mut serve {
|
||||
*p = port;
|
||||
}
|
||||
}
|
||||
a => return Err(format!("unknown argument `{a}`\n\n{USAGE}")),
|
||||
}
|
||||
}
|
||||
Ok(serve)
|
||||
}
|
||||
|
||||
fn serve(port: u16, open: bool) -> Result<(), String> {
|
||||
let app = Arc::new(App::new(Config::from_env()?, unix_now())?);
|
||||
let server = http::listen(port)?;
|
||||
let port = http::port_of(&server);
|
||||
let url = format!("http://127.0.0.1:{port}");
|
||||
println!(
|
||||
"sccache-dash: serving {url}, history in {}",
|
||||
app.cfg.history.display()
|
||||
);
|
||||
app.clone().keep_updated();
|
||||
if open {
|
||||
// Left to finish on its own: a browser that will not open is not worth stopping for.
|
||||
let browser = Process::new("xdg-open")
|
||||
.arg(&url)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn();
|
||||
if let Ok(mut browser) = browser {
|
||||
std::thread::spawn(move || {
|
||||
let _ = browser.wait();
|
||||
});
|
||||
}
|
||||
}
|
||||
http::answer(server, app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse_args(args: &[&str]) -> Result<Command, String> {
|
||||
parse(&args.iter().map(|a| a.to_string()).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_line() {
|
||||
assert!(matches!(
|
||||
parse_args(&[]),
|
||||
Ok(Command::Serve {
|
||||
port: 8226,
|
||||
open: true
|
||||
})
|
||||
));
|
||||
assert!(matches!(
|
||||
parse_args(&["--port", "18226"]),
|
||||
Ok(Command::Serve {
|
||||
port: 18226,
|
||||
open: true
|
||||
})
|
||||
));
|
||||
assert!(matches!(
|
||||
parse_args(&["--port=9000", "--no-open"]),
|
||||
Ok(Command::Serve {
|
||||
port: 9000,
|
||||
open: false
|
||||
})
|
||||
));
|
||||
assert!(matches!(
|
||||
parse_args(&["--no-open", "--port", "1"]),
|
||||
Ok(Command::Serve {
|
||||
port: 1,
|
||||
open: false
|
||||
})
|
||||
));
|
||||
assert!(matches!(parse_args(&["install"]), Ok(Command::Install)));
|
||||
assert!(matches!(parse_args(&["uninstall"]), Ok(Command::Uninstall)));
|
||||
assert!(matches!(parse_args(&["--help"]), Ok(Command::Help)));
|
||||
assert!(parse_args(&["18226"])
|
||||
.unwrap_err()
|
||||
.starts_with("unknown argument `18226`"));
|
||||
assert!(parse_args(&["--port"])
|
||||
.unwrap_err()
|
||||
.contains("--port needs a number"));
|
||||
assert!(parse_args(&["--port", "x"])
|
||||
.unwrap_err()
|
||||
.contains("`x` is not a port number"));
|
||||
assert!(parse_args(&["--port", "70000"])
|
||||
.unwrap_err()
|
||||
.contains("is not a port number"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! How numbers, times and sizes are written for people.
|
||||
|
||||
/// `2815` as "2,815".
|
||||
pub fn thousands(n: u64) -> String {
|
||||
let digits = n.to_string();
|
||||
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
|
||||
for (i, c) in digits.chars().enumerate() {
|
||||
if i > 0 && (digits.len() - i).is_multiple_of(3) {
|
||||
out.push(',');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A share as a percentage with one decimal, dropping a needless ".0": `0.076` as "7.6", `1.0` as "100".
|
||||
pub fn pct(share: f64) -> String {
|
||||
let s = format!("{:.1}", share * 100.0);
|
||||
s.strip_suffix(".0").unwrap_or(&s).to_owned()
|
||||
}
|
||||
|
||||
/// Seconds rounded down to minutes, the way the summary says them: "3h 05m", "48m", "<1m".
|
||||
pub fn hours_and_minutes(secs: f64) -> String {
|
||||
let mins = (secs / 60.0).floor() as u64;
|
||||
match mins {
|
||||
0 => "<1m".to_owned(),
|
||||
1..=59 => format!("{mins}m"),
|
||||
_ => format!("{}h {:02}m", mins / 60, mins % 60),
|
||||
}
|
||||
}
|
||||
|
||||
/// A short length of time: "210 ms", "0.9 s", "7.8 s", "20 min".
|
||||
pub fn short(secs: f64) -> String {
|
||||
if secs < 1.0 {
|
||||
format!("{:.0} ms", secs * 1000.0)
|
||||
} else if secs < 600.0 {
|
||||
let s = format!("{secs:.1}");
|
||||
format!("{} s", s.strip_suffix(".0").unwrap_or(&s))
|
||||
} else {
|
||||
format!("{:.0} min", secs / 60.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Two sizes as one phrase: sccache's 10G limit reads "10.0 of 10.0 GB", and sizes in different
|
||||
/// units read "900.0 MB of 10.0 GB".
|
||||
pub fn bytes_of(size: u64, max: u64) -> String {
|
||||
let (a, au) = amount(size);
|
||||
let (b, bu) = amount(max);
|
||||
if au == bu {
|
||||
format!("{a} of {b} {au}")
|
||||
} else {
|
||||
format!("{a} {au} of {b} {bu}")
|
||||
}
|
||||
}
|
||||
|
||||
fn amount(b: u64) -> (String, &'static str) {
|
||||
const K: f64 = 1024.0;
|
||||
let b = b as f64;
|
||||
if b >= K * K * K * K {
|
||||
(format!("{:.1}", b / (K * K * K * K)), "TB")
|
||||
} else if b >= K * K * K {
|
||||
(format!("{:.1}", b / (K * K * K)), "GB")
|
||||
} else if b >= K * K {
|
||||
(format!("{:.1}", b / (K * K)), "MB")
|
||||
} else {
|
||||
(format!("{b:.0}"), "KB")
|
||||
}
|
||||
}
|
||||
|
||||
/// Unix seconds as a file-name-friendly UTC time: `0` as "19700101-000000".
|
||||
pub fn stamp(secs: i64) -> String {
|
||||
let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
|
||||
// Days since 1970-01-01 to a date, by Howard Hinnant's algorithm.
|
||||
let z = days + 719_468;
|
||||
let (era, doe) = (z.div_euclid(146_097), z.rem_euclid(146_097));
|
||||
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let y = yoe + era * 400 + i64::from(m <= 2);
|
||||
format!(
|
||||
"{y:04}{m:02}{d:02}-{:02}{:02}{:02}",
|
||||
rem / 3600,
|
||||
rem % 3600 / 60,
|
||||
rem % 60
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn numbers_as_written() {
|
||||
assert_eq!(thousands(0), "0");
|
||||
assert_eq!(thousands(2815), "2,815");
|
||||
assert_eq!(thousands(1_234_567), "1,234,567");
|
||||
assert_eq!(pct(0.076), "7.6");
|
||||
assert_eq!(pct(0.5018), "50.2");
|
||||
assert_eq!(pct(1.0), "100");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn times_as_written() {
|
||||
assert_eq!(hours_and_minutes(11100.0), "3h 05m");
|
||||
assert_eq!(hours_and_minutes(48.4 * 60.0), "48m");
|
||||
assert_eq!(hours_and_minutes(20.0), "<1m");
|
||||
assert_eq!(short(0.21), "210 ms");
|
||||
assert_eq!(short(0.9), "900 ms");
|
||||
assert_eq!(short(10.0), "10 s");
|
||||
assert_eq!(short(60.0), "60 s");
|
||||
assert_eq!(short(1200.0), "20 min");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes_and_dates_as_written() {
|
||||
assert_eq!(
|
||||
bytes_of(10 * 1024 * 1024 * 1024, 10 * 1024 * 1024 * 1024),
|
||||
"10.0 of 10.0 GB"
|
||||
);
|
||||
assert_eq!(bytes_of(1024 * 1024, 1024 * 1024), "1.0 of 1.0 MB");
|
||||
assert_eq!(bytes_of(10_726_353_131, 10_737_418_240), "10.0 of 10.0 GB");
|
||||
assert_eq!(
|
||||
bytes_of(9 * 1024 * 1024 * 1024, 10 * 1024 * 1024 * 1024),
|
||||
"9.0 of 10.0 GB"
|
||||
);
|
||||
assert_eq!(
|
||||
bytes_of(900 * 1024 * 1024, 10 * 1024 * 1024 * 1024),
|
||||
"900.0 MB of 10.0 GB"
|
||||
);
|
||||
assert_eq!(stamp(0), "19700101-000000");
|
||||
assert_eq!(stamp(1_764_000_000), "20251124-160000"); // what `date -u -d @1764000000` says
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,579 @@
|
||||
//! sccache's counters: reading them out of its JSON and telling two readings apart.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use sccache_dash_api::{Extra, Totals};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::pretty;
|
||||
|
||||
/// Positions in [`Counters::ns`].
|
||||
pub const HIT_READ: usize = 0;
|
||||
pub const CACHE_WRITE: usize = 1;
|
||||
pub const COMPILE: usize = 2;
|
||||
|
||||
/// sccache's counters at one moment. Each only grows, until sccache resets them.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Counters {
|
||||
#[serde(default)]
|
||||
pub totals: Totals,
|
||||
/// Compiler runs: misses, plus compiles that could not be cached or failed.
|
||||
#[serde(default)]
|
||||
pub compilations: u64,
|
||||
/// Nanoseconds spent reading hits, writing cache entries and running compilers.
|
||||
#[serde(default)]
|
||||
pub ns: [u64; 3],
|
||||
/// (language, [hits, misses, errors]) by name, for languages that have counted something.
|
||||
#[serde(default)]
|
||||
pub langs: Vec<(String, [u64; 3])>,
|
||||
/// (reason, count) by name, for reasons that have counted something.
|
||||
#[serde(default)]
|
||||
pub not_cached: Vec<(String, u64)>,
|
||||
}
|
||||
|
||||
impl Counters {
|
||||
/// What happened between `older` and `self`, and whether sccache reset its counters in between.
|
||||
///
|
||||
/// A counter that went down can only mean sccache zeroed its counters (a new server, or
|
||||
/// `--zero-stats`), and it zeroes all of them at once: every difference is then the new value.
|
||||
pub fn since(&self, older: &Counters) -> (Counters, bool) {
|
||||
let mut reset = false;
|
||||
let mut sub = |a: u64, b: u64| {
|
||||
if b < a {
|
||||
reset = true;
|
||||
}
|
||||
b.saturating_sub(a)
|
||||
};
|
||||
let (a, b) = (&older.totals, &self.totals);
|
||||
let totals = Totals {
|
||||
requests: sub(a.requests, b.requests),
|
||||
executed: sub(a.executed, b.executed),
|
||||
hits: sub(a.hits, b.hits),
|
||||
misses: sub(a.misses, b.misses),
|
||||
not_cacheable: sub(a.not_cacheable, b.not_cacheable),
|
||||
unsupported_compiler: sub(a.unsupported_compiler, b.unsupported_compiler),
|
||||
not_compile: sub(a.not_compile, b.not_compile),
|
||||
timeouts: sub(a.timeouts, b.timeouts),
|
||||
read_errors: sub(a.read_errors, b.read_errors),
|
||||
write_errors: sub(a.write_errors, b.write_errors),
|
||||
other_errors: sub(a.other_errors, b.other_errors),
|
||||
compile_fails: sub(a.compile_fails, b.compile_fails),
|
||||
forced_recaches: sub(a.forced_recaches, b.forced_recaches),
|
||||
cache_writes: sub(a.cache_writes, b.cache_writes),
|
||||
};
|
||||
let compilations = sub(older.compilations, self.compilations);
|
||||
let mut ns = [0; 3];
|
||||
for (d, (a, b)) in ns.iter_mut().zip(older.ns.iter().zip(self.ns.iter())) {
|
||||
*d = sub(*a, *b);
|
||||
}
|
||||
let langs = self
|
||||
.langs
|
||||
.iter()
|
||||
.filter_map(|(name, v)| {
|
||||
let o = older
|
||||
.langs
|
||||
.iter()
|
||||
.find(|(k, _)| k == name)
|
||||
.map_or([0; 3], |(_, o)| *o);
|
||||
let mut d = [0; 3];
|
||||
for (d, (a, b)) in d.iter_mut().zip(o.iter().zip(v.iter())) {
|
||||
*d = sub(*a, *b);
|
||||
}
|
||||
(d != [0; 3]).then(|| (name.clone(), d))
|
||||
})
|
||||
.collect();
|
||||
let not_cached = self
|
||||
.not_cached
|
||||
.iter()
|
||||
.filter_map(|(name, v)| {
|
||||
let o = older
|
||||
.not_cached
|
||||
.iter()
|
||||
.find(|(k, _)| k == name)
|
||||
.map_or(0, |(_, o)| *o);
|
||||
let d = sub(o, *v);
|
||||
(d > 0).then(|| (name.clone(), d))
|
||||
})
|
||||
.collect();
|
||||
let diff = Counters {
|
||||
totals,
|
||||
compilations,
|
||||
ns,
|
||||
langs,
|
||||
not_cached,
|
||||
};
|
||||
(if reset { self.clone() } else { diff }, reset)
|
||||
}
|
||||
|
||||
/// Adds another set of counters into this one.
|
||||
pub fn add(&mut self, other: &Counters) {
|
||||
macro_rules! sum {
|
||||
($($f:ident),* $(,)?) => { $( self.totals.$f += other.totals.$f; )* };
|
||||
}
|
||||
sum!(
|
||||
requests,
|
||||
executed,
|
||||
hits,
|
||||
misses,
|
||||
not_cacheable,
|
||||
unsupported_compiler,
|
||||
not_compile,
|
||||
timeouts,
|
||||
read_errors,
|
||||
write_errors,
|
||||
other_errors,
|
||||
compile_fails,
|
||||
forced_recaches,
|
||||
cache_writes,
|
||||
);
|
||||
self.compilations += other.compilations;
|
||||
for (n, x) in self.ns.iter_mut().zip(other.ns.iter()) {
|
||||
*n += x;
|
||||
}
|
||||
for (name, v) in &other.langs {
|
||||
match self.langs.iter_mut().find(|(k, _)| k == name) {
|
||||
Some((_, have)) => {
|
||||
for (h, x) in have.iter_mut().zip(v.iter()) {
|
||||
*h += x;
|
||||
}
|
||||
}
|
||||
None => self.langs.push((name.clone(), *v)),
|
||||
}
|
||||
}
|
||||
for (name, v) in &other.not_cached {
|
||||
match self.not_cached.iter_mut().find(|(k, _)| k == name) {
|
||||
Some((_, have)) => *have += v,
|
||||
None => self.not_cached.push((name.clone(), *v)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One level of a multi-level cache, as sccache 0.18 reports it in `stats.multi_level`.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Level {
|
||||
pub name: String,
|
||||
pub location: String,
|
||||
pub hits: u64,
|
||||
pub misses: u64,
|
||||
pub writes: u64,
|
||||
pub write_failures: u64,
|
||||
pub backfills_from: u64,
|
||||
pub backfills_to: u64,
|
||||
pub hit_ns: u64,
|
||||
pub write_ns: u64,
|
||||
}
|
||||
|
||||
/// What one run of `sccache --show-stats --stats-format json` said.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Snapshot {
|
||||
pub counters: Counters,
|
||||
pub version: Option<String>,
|
||||
pub cache_location: Option<String>,
|
||||
pub cache_size: Option<u64>,
|
||||
pub max_cache_size: Option<u64>,
|
||||
pub multi_level: Vec<Level>,
|
||||
/// (server, compiles) by server, sorted by server.
|
||||
pub dist_compiles: Vec<(String, u64)>,
|
||||
pub dist_errors: u64,
|
||||
}
|
||||
|
||||
/// Reads sccache's JSON. Unknown fields are ignored and missing ones read as zero, so a new
|
||||
/// sccache cannot break this; only output that is not JSON with a `stats` object is an error.
|
||||
pub fn parse(text: &str) -> Result<Snapshot, String> {
|
||||
let root: Value =
|
||||
serde_json::from_str(text).map_err(|e| format!("sccache's output is not JSON ({e})"))?;
|
||||
let stats = root
|
||||
.get("stats")
|
||||
.ok_or("sccache's output has no \"stats\" object")?;
|
||||
|
||||
let (hits, misses, errors) = (
|
||||
counts(stats, "cache_hits"),
|
||||
counts(stats, "cache_misses"),
|
||||
counts(stats, "cache_errors"),
|
||||
);
|
||||
let mut by_lang: BTreeMap<&str, [u64; 3]> = BTreeMap::new();
|
||||
for (map, i) in [(&hits, 0), (&misses, 1), (&errors, 2)] {
|
||||
for (name, n) in map {
|
||||
by_lang.entry(name.as_str()).or_default()[i] = *n;
|
||||
}
|
||||
}
|
||||
let n = |field: &str| num(stats.get(field));
|
||||
let totals = Totals {
|
||||
requests: n("compile_requests"),
|
||||
executed: n("requests_executed"),
|
||||
hits: hits.values().sum(),
|
||||
misses: misses.values().sum(),
|
||||
not_cacheable: n("requests_not_cacheable"),
|
||||
unsupported_compiler: n("requests_unsupported_compiler"),
|
||||
not_compile: n("requests_not_compile"),
|
||||
timeouts: n("cache_timeouts"),
|
||||
read_errors: n("cache_read_errors"),
|
||||
write_errors: n("cache_write_errors"),
|
||||
other_errors: errors.values().sum(),
|
||||
compile_fails: n("compile_fails"),
|
||||
forced_recaches: n("forced_recaches"),
|
||||
cache_writes: n("cache_writes"),
|
||||
};
|
||||
let counters = Counters {
|
||||
totals,
|
||||
compilations: n("compilations"),
|
||||
ns: [
|
||||
nanos(stats.get("cache_read_hit_duration")),
|
||||
nanos(stats.get("cache_write_duration")),
|
||||
nanos(stats.get("compiler_write_duration")),
|
||||
],
|
||||
langs: by_lang
|
||||
.into_iter()
|
||||
.map(|(name, v)| (name.to_owned(), v))
|
||||
.collect(),
|
||||
not_cached: pairs(stats.get("not_cached")).into_iter().collect(),
|
||||
};
|
||||
let text = |field: &str| root.get(field).and_then(Value::as_str).map(str::to_owned);
|
||||
let multi_level = stats
|
||||
.get("multi_level")
|
||||
.and_then(Value::as_array)
|
||||
.map(|levels| {
|
||||
levels
|
||||
.iter()
|
||||
.filter_map(|l| {
|
||||
let s = |f: &str| Some(l.get(f)?.as_str()?.to_owned());
|
||||
Some(Level {
|
||||
name: s("name")?,
|
||||
location: s("location")?,
|
||||
hits: num(l.get("hits")),
|
||||
misses: num(l.get("misses")),
|
||||
writes: num(l.get("writes")),
|
||||
write_failures: num(l.get("write_failures")),
|
||||
backfills_from: num(l.get("backfills_from")),
|
||||
backfills_to: num(l.get("backfills_to")),
|
||||
hit_ns: nanos(l.get("hit_duration")),
|
||||
write_ns: nanos(l.get("write_duration")),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
Ok(Snapshot {
|
||||
counters,
|
||||
version: text("version"),
|
||||
cache_location: text("cache_location"),
|
||||
cache_size: root.get("cache_size").and_then(Value::as_u64),
|
||||
max_cache_size: root.get("max_cache_size").and_then(Value::as_u64),
|
||||
multi_level,
|
||||
dist_compiles: pairs(stats.get("dist_compiles"))
|
||||
.into_iter()
|
||||
.filter(|(_, n)| *n > 0)
|
||||
.collect(),
|
||||
dist_errors: n("dist_errors"),
|
||||
})
|
||||
}
|
||||
|
||||
/// A number as sccache writes it; anything else reads as zero.
|
||||
fn num(v: Option<&Value>) -> u64 {
|
||||
v.and_then(Value::as_u64).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// `{"secs": 1, "nanos": 2}` as nanoseconds.
|
||||
fn nanos(v: Option<&Value>) -> u64 {
|
||||
let o = v.and_then(Value::as_object);
|
||||
let get = |k: &str| {
|
||||
o.and_then(|o| o.get(k))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0)
|
||||
};
|
||||
get("secs") * 1_000_000_000 + get("nanos")
|
||||
}
|
||||
|
||||
/// A JSON object of counts as a sorted map.
|
||||
fn pairs(v: Option<&Value>) -> BTreeMap<String, u64> {
|
||||
v.and_then(Value::as_object)
|
||||
.map(|o| {
|
||||
o.iter()
|
||||
.filter_map(|(k, v)| Some((k.clone(), v.as_u64()?)))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `{"counts": {...}}` as a sorted map.
|
||||
fn counts(parent: &Value, field: &str) -> BTreeMap<String, u64> {
|
||||
pairs(parent.get(field).and_then(|f| f.get("counts")))
|
||||
}
|
||||
|
||||
/// The tables for what sccache reports beyond the usual counters, empty when it reports nothing.
|
||||
pub fn extras(s: &Snapshot) -> Vec<Extra> {
|
||||
let mut out = Vec::new();
|
||||
if !s.multi_level.is_empty() {
|
||||
let rows = s
|
||||
.multi_level
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let per = |total: u64, n: u64| (n > 0).then(|| total as f64 / n as f64 / 1e9);
|
||||
(
|
||||
format!("{} \u{2014} {}", l.name, l.location),
|
||||
format!(
|
||||
"{} hits \u{b7} {} misses \u{b7} {} writes, {} failed \u{b7} backfilled {} in, {} out \u{b7} avg hit read {} \u{b7} avg write {}",
|
||||
pretty::thousands(l.hits),
|
||||
pretty::thousands(l.misses),
|
||||
pretty::thousands(l.writes),
|
||||
pretty::thousands(l.write_failures),
|
||||
pretty::thousands(l.backfills_from),
|
||||
pretty::thousands(l.backfills_to),
|
||||
per(l.hit_ns, l.hits).map_or_else(|| "\u{2014}".to_owned(), pretty::short),
|
||||
per(l.write_ns, l.writes).map_or_else(|| "\u{2014}".to_owned(), pretty::short),
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
out.push(Extra {
|
||||
title: "Multi-level cache".to_owned(),
|
||||
rows,
|
||||
});
|
||||
}
|
||||
if !s.dist_compiles.is_empty() || s.dist_errors > 0 {
|
||||
let mut rows: Vec<_> = s
|
||||
.dist_compiles
|
||||
.iter()
|
||||
.map(|(server, n)| (server.clone(), pretty::thousands(*n)))
|
||||
.collect();
|
||||
rows.push((
|
||||
"Errors (re-run locally)".to_owned(),
|
||||
pretty::thousands(s.dist_errors),
|
||||
));
|
||||
out.push(Extra {
|
||||
title: "Distributed compiles".to_owned(),
|
||||
rows,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json");
|
||||
const MULTILEVEL: &str = include_str!("../../../fixtures/sample-multilevel.json");
|
||||
const DIST: &str = include_str!("../../../fixtures/sample-dist.json");
|
||||
|
||||
fn counters(requests: u64, hits: u64, misses: u64) -> Counters {
|
||||
Counters {
|
||||
totals: Totals {
|
||||
requests,
|
||||
hits,
|
||||
misses,
|
||||
..Totals::default()
|
||||
},
|
||||
compilations: misses,
|
||||
langs: vec![("Rust".to_owned(), [hits, misses, 0])],
|
||||
..Counters::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_output_is_read_as_it_is() {
|
||||
let s = parse(LIVE).unwrap();
|
||||
assert_eq!(
|
||||
s.counters.totals,
|
||||
Totals {
|
||||
requests: 7351,
|
||||
executed: 6495,
|
||||
hits: 3197,
|
||||
misses: 3256,
|
||||
not_cacheable: 829,
|
||||
not_compile: 27,
|
||||
other_errors: 0,
|
||||
compile_fails: 39,
|
||||
cache_writes: 3256,
|
||||
..Totals::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(s.counters.compilations, 3256);
|
||||
assert_eq!(
|
||||
s.counters.ns,
|
||||
[2_190_691_578, 8_758_680_079, 25_343_119_040_435]
|
||||
);
|
||||
assert_eq!(
|
||||
s.counters.langs,
|
||||
vec![
|
||||
("Assembler".to_owned(), [886, 0, 0]),
|
||||
("C/C++".to_owned(), [2082, 0, 0]),
|
||||
("Rust".to_owned(), [229, 3256, 0]),
|
||||
]
|
||||
);
|
||||
assert_eq!(s.counters.not_cached.len(), 7);
|
||||
assert_eq!(s.counters.not_cached[0], ("-".to_owned(), 35));
|
||||
assert_eq!(s.version.as_deref(), Some("0.18.0"));
|
||||
assert_eq!(
|
||||
s.cache_location.as_deref(),
|
||||
Some("Local disk: \"/home/swaits/.cache/sccache\"")
|
||||
);
|
||||
assert_eq!(
|
||||
(s.cache_size, s.max_cache_size),
|
||||
(Some(10_726_353_131), Some(10_737_418_240))
|
||||
);
|
||||
assert!(s.multi_level.is_empty() && s.dist_compiles.is_empty() && s.dist_errors == 0);
|
||||
assert!(
|
||||
extras(&s).is_empty(),
|
||||
"nothing extra is reported, so there are no extra tables"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_line_is_small() {
|
||||
let reading = crate::history::Reading {
|
||||
t: 1_764_000_000,
|
||||
c: parse(LIVE).unwrap().counters,
|
||||
};
|
||||
let line = serde_json::to_string(&reading).unwrap();
|
||||
assert!(line.len() < 1024, "{} bytes: {line}", line.len());
|
||||
assert!(
|
||||
line.starts_with("{\"t\":1764000000,\"c\":{\"totals\":{\"requests\":7351"),
|
||||
"{line}"
|
||||
);
|
||||
assert!(line.ends_with("[\"multiple input files\",3]]}}"), "{line}");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<crate::history::Reading>(&line).unwrap(),
|
||||
reading
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_and_missing_fields_do_not_break_it() {
|
||||
let s = parse(
|
||||
"{\"stats\":{\"compile_requests\":\"many\",\"cache_hits\":{\"counts\":{\"Rust\":-1}},\"new_field\":1},\"extra\":2}",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(s.counters, Counters::default());
|
||||
assert_eq!(parse("{\"stats\":{}}").unwrap(), Snapshot::default());
|
||||
assert_eq!(
|
||||
parse("{\"stats\":null,\"version\":\"1.0\"}")
|
||||
.unwrap()
|
||||
.version
|
||||
.as_deref(),
|
||||
Some("1.0")
|
||||
);
|
||||
assert!(parse("not json").is_err());
|
||||
assert!(parse("{\"error\":\"no server\"}").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn differences_are_what_grew() {
|
||||
let (older, newer) = (counters(100, 60, 40), counters(130, 80, 50));
|
||||
let (diff, reset) = newer.since(&older);
|
||||
assert_eq!(diff.totals.requests, 30);
|
||||
assert_eq!(diff.totals.hits, 20);
|
||||
assert_eq!(diff.totals.misses, 10);
|
||||
assert_eq!(diff.langs, vec![("Rust".to_owned(), [20, 10, 0])]);
|
||||
assert!(!reset);
|
||||
let (same, _) = newer.since(&newer);
|
||||
assert!(same.totals == Totals::default() && same.langs.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_counter_going_down_zeroes_the_whole_reading() {
|
||||
let mut older = counters(100, 60, 40);
|
||||
older.not_cached.push(("crate-type".to_owned(), 9));
|
||||
older.ns[COMPILE] = 400;
|
||||
let mut newer = counters(130, 5, 0);
|
||||
newer.not_cached.push(("crate-type".to_owned(), 2));
|
||||
newer.not_cached.push(("-o".to_owned(), 1));
|
||||
newer.ns[COMPILE] = 7;
|
||||
let (diff, reset) = newer.since(&older);
|
||||
assert!(
|
||||
reset,
|
||||
"hits went down, so the counters were zeroed in between"
|
||||
);
|
||||
assert_eq!(
|
||||
diff, newer,
|
||||
"every difference is the new value, even where the counter grew"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sums_merge_languages_and_reasons() {
|
||||
let mut a = counters(10, 4, 6);
|
||||
a.not_cached.push(("crate-type".to_owned(), 1));
|
||||
let mut b = counters(1, 1, 0);
|
||||
b.compilations = 0;
|
||||
b.langs = vec![
|
||||
("C/C++".to_owned(), [1, 0, 0]),
|
||||
("Rust".to_owned(), [0, 0, 2]),
|
||||
];
|
||||
b.not_cached.push(("crate-type".to_owned(), 2));
|
||||
b.not_cached.push(("incremental".to_owned(), 1));
|
||||
a.add(&b);
|
||||
assert_eq!(a.totals.requests, 11);
|
||||
assert_eq!(a.totals.hits, 5);
|
||||
assert_eq!(a.compilations, 6);
|
||||
assert_eq!(
|
||||
a.langs,
|
||||
vec![
|
||||
("Rust".to_owned(), [4, 6, 2]),
|
||||
("C/C++".to_owned(), [1, 0, 0])
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
a.not_cached,
|
||||
vec![("crate-type".to_owned(), 3), ("incremental".to_owned(), 1)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multilevel_sample_becomes_a_table() {
|
||||
let s = parse(MULTILEVEL).unwrap();
|
||||
assert_eq!(s.multi_level.len(), 2);
|
||||
assert_eq!(s.multi_level[1].name, "L1 (s3)");
|
||||
assert_eq!(s.multi_level[0].hit_ns, 1_500_000_000);
|
||||
assert_eq!(s.multi_level[1].write_ns, 36_500_000_000);
|
||||
let extras = extras(&s);
|
||||
assert_eq!(extras.len(), 1);
|
||||
assert_eq!(extras[0].title, "Multi-level cache");
|
||||
assert_eq!(extras[0].rows.len(), 2);
|
||||
assert_eq!(
|
||||
extras[0].rows[0].0,
|
||||
"L0 (disk) \u{2014} Local disk: \"/home/me/.cache/sccache\""
|
||||
);
|
||||
assert_eq!(
|
||||
extras[0].rows[0].1,
|
||||
"1,500 hits \u{b7} 1,000 misses \u{b7} 1,400 writes, 2 failed \u{b7} backfilled 300 in, 0 out \u{b7} avg hit read 1 ms \u{b7} avg write 2 ms"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_sample_becomes_a_table() {
|
||||
let s = parse(DIST).unwrap();
|
||||
assert_eq!(
|
||||
s.dist_compiles,
|
||||
vec![
|
||||
("10.0.0.11:4226".to_owned(), 402),
|
||||
("10.0.0.12:4226".to_owned(), 379),
|
||||
("buildbox.local:4228".to_owned(), 9),
|
||||
]
|
||||
);
|
||||
assert_eq!(s.dist_errors, 7);
|
||||
let extras = extras(&s);
|
||||
assert_eq!(extras.len(), 1);
|
||||
assert_eq!(extras[0].title, "Distributed compiles");
|
||||
assert_eq!(
|
||||
extras[0].rows[2],
|
||||
("buildbox.local:4228".to_owned(), "9".to_owned())
|
||||
);
|
||||
assert_eq!(
|
||||
extras[0].rows[3],
|
||||
("Errors (re-run locally)".to_owned(), "7".to_owned())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_dist_errors_still_makes_a_table() {
|
||||
let mut s = parse(DIST).unwrap();
|
||||
s.dist_compiles.clear();
|
||||
assert_eq!(
|
||||
extras(&s)[0].rows,
|
||||
vec![("Errors (re-run locally)".to_owned(), "7".to_owned())]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
//! Living in systemd: the unit file, and installing or removing it.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
use sccache_dash_api::DEFAULT_PORT;
|
||||
|
||||
pub const UNIT: &str = "sccache-dash.service";
|
||||
|
||||
/// The unit file that runs this program from login on, without opening a browser.
|
||||
pub fn unit_file(exe: &str, path: &str) -> String {
|
||||
format!(
|
||||
"[Unit]\n\
|
||||
Description=sccache-dash, a dashboard for sccache's cache at http://127.0.0.1:{DEFAULT_PORT}\n\
|
||||
\n\
|
||||
[Service]\n\
|
||||
ExecStart={} --no-open\n\
|
||||
Environment={}\n\
|
||||
Restart=on-failure\n\
|
||||
RestartSec=5\n\
|
||||
\n\
|
||||
[Install]\n\
|
||||
WantedBy=default.target\n",
|
||||
quote(exe),
|
||||
quote(&format!("PATH={path}")),
|
||||
)
|
||||
}
|
||||
|
||||
/// Quotes a value the way systemd unit files read it; `%` would otherwise start a specifier.
|
||||
fn quote(value: &str) -> String {
|
||||
format!(
|
||||
"\"{}\"",
|
||||
value
|
||||
.replace('\\', "\\\\")
|
||||
.replace('"', "\\\"")
|
||||
.replace('%', "%%")
|
||||
)
|
||||
}
|
||||
|
||||
fn unit_path() -> Result<PathBuf, String> {
|
||||
let config = dirs::config_dir()
|
||||
.ok_or("cannot find the config directory ($XDG_CONFIG_HOME, or ~/.config)")?;
|
||||
Ok(config.join("systemd").join("user").join(UNIT))
|
||||
}
|
||||
|
||||
fn systemctl(args: &[&str]) -> Result<(), String> {
|
||||
let output = Command::new("systemctl")
|
||||
.args(args)
|
||||
.output()
|
||||
.map_err(|e| format!("cannot run systemctl: {e}"))?;
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_owned();
|
||||
Err(format!(
|
||||
"systemctl {} failed: {}",
|
||||
args.join(" "),
|
||||
[stdout, stderr].join(" ").trim()
|
||||
))
|
||||
}
|
||||
|
||||
/// Writes the unit file for the program as it is running right now, then starts it.
|
||||
pub fn install() -> Result<(), String> {
|
||||
let exe =
|
||||
std::env::current_exe().map_err(|e| format!("cannot find where this program is: {e}"))?;
|
||||
let path = std::env::var("PATH").unwrap_or_default();
|
||||
let unit = unit_path()?;
|
||||
if let Some(dir) = unit.parent() {
|
||||
std::fs::create_dir_all(dir)
|
||||
.map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
||||
}
|
||||
std::fs::write(&unit, unit_file(&exe.to_string_lossy(), &path))
|
||||
.map_err(|e| format!("cannot write {}: {e}", unit.display()))?;
|
||||
systemctl(&["--user", "daemon-reload"])?;
|
||||
systemctl(&["--user", "enable", "--now", UNIT])?;
|
||||
println!(
|
||||
"Installed {}. The dashboard is at http://127.0.0.1:{DEFAULT_PORT}",
|
||||
unit.display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stops the service and deletes the unit file.
|
||||
pub fn uninstall() -> Result<(), String> {
|
||||
let unit = unit_path()?;
|
||||
if unit.exists() {
|
||||
systemctl(&["--user", "disable", "--now", UNIT])?;
|
||||
std::fs::remove_file(&unit)
|
||||
.map_err(|e| format!("cannot remove {}: {e}", unit.display()))?;
|
||||
} else {
|
||||
println!("{} is not installed; nothing to remove.", unit.display());
|
||||
}
|
||||
systemctl(&["--user", "daemon-reload"])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_unit_runs_this_binary_without_a_browser_and_with_the_shell_s_path() {
|
||||
let unit = unit_file("/home/me/bin/sccache-dash", "/usr/bin:/home/me/.cargo/bin");
|
||||
assert_eq!(
|
||||
unit,
|
||||
"[Unit]\n\
|
||||
Description=sccache-dash, a dashboard for sccache's cache at http://127.0.0.1:8226\n\
|
||||
\n\
|
||||
[Service]\n\
|
||||
ExecStart=\"/home/me/bin/sccache-dash\" --no-open\n\
|
||||
Environment=\"PATH=/usr/bin:/home/me/.cargo/bin\"\n\
|
||||
Restart=on-failure\n\
|
||||
RestartSec=5\n\
|
||||
\n\
|
||||
[Install]\n\
|
||||
WantedBy=default.target\n"
|
||||
);
|
||||
assert!(unit_file("/a b/sccache-dash", "/x")
|
||||
.contains("ExecStart=\"/a b/sccache-dash\" --no-open\n"));
|
||||
assert!(
|
||||
unit_file("/x", "/a%b\"c").contains("Environment=\"PATH=/a%%b\\\"c\"\n"),
|
||||
"% and quotes cannot change what systemd reads"
|
||||
);
|
||||
assert!(
|
||||
unit_file("relative/sccache-dash", "/x")
|
||||
.contains("ExecStart=\"relative/sccache-dash\""),
|
||||
"quoting is the caller's path, verbatim"
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user