Merge server: polling, SQLite history, views, HTTP, service install

This commit is contained in:
swaits committed 2026-11-28 11:46:54 -07:00
commit 90a6302149
18 files changed
+3982

No files matched your search

+176
View File
@@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 sccache-dash contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+64
View File
@@ -0,0 +1,64 @@
# sccache-dash
A small Linux program in the manner of Syncthing: one binary that watches the local
[sccache](https://github.com/mozilla/sccache) compiler cache, remembers what it did, and serves
a dashboard for it at <http://127.0.0.1:8226>. It listens on this machine only.
It asks sccache for its counters every 10 seconds, works out hit rates, time saved and what looks
wrong, and sends the page one `View` to draw (the contract is `crates/api`).
## Install
```
just build # builds the page (trunk) and then the server
sccache-dash # serves http://127.0.0.1:8226 and opens it
sccache-dash install # the same, as a systemd user service that starts at login
sccache-dash uninstall
```
`sccache-dash [--port N] [--no-open]` serves. `install` writes
`~/.config/systemd/user/sccache-dash.service` with the absolute path of the binary and the `PATH`
of the shell that ran it, so that `sccache` is found; the service never opens a browser.
`SCCACHE_DASH_SCCACHE` names the sccache command when it is not simply `sccache` on `PATH`.
Until the page has been built (`crates/ui/dist`), the server serves a placeholder saying so; its
API answers either way.
## Routes
| Route | What it does |
| --- | --- |
| `GET /api/view?range=1h\|24h\|7d\|30d\|reset` | one `View`: totals, the period before, timing, time saved, languages, buckets, problems, a summary |
| `GET /api/export` | sccache's current stats exactly as `sccache --show-stats --stats-format json` prints them, as a download |
| `POST /api/zero` | runs `sccache --zero-stats`; the saved history is kept |
| `GET /` | the page |
`/api/zero` is refused unless the request's `Host` is localhost and, when it has an `Origin`,
that origin is this server, so a web page elsewhere cannot zero the stats.
## Where history lives
`$XDG_DATA_HOME/sccache-dash/history.db` (`~/.local/share/...` by default): one SQLite file. Its
`readings` table holds one row a minute at most, and only when sccache's counters changed; each
row is the difference since the row before it, so a range total is one indexed query. Per-language
counts and not-cacheable reasons sit in their own tables, and `build_obs` holds what the polls saw
of how long a build of each language takes. A stretch without rows is a gap. Rows older than 30
days are deleted at startup and once a day. Deleting the file loses the history and nothing else.
The five views (one per range) are made after every poll and kept in memory, so a request never
waits for the database.
A counter that goes down means sccache reset its counters (`--zero-stats`, or its server
restarted): the range counts start again from zero there and the chart marks the spot. The first
reading ever is a baseline and counts for nothing.
## Notes on sccache
While sccache's server is running, being asked for its stats every 10 seconds keeps it from its
10-minute idle shutdown. When it is not running, `sccache --show-stats` does not start it (it
prints empty counters) and neither does this program; the next compile starts it, as usual.
## Licence
MIT or Apache-2.0, at your choice (`LICENSE-MIT`, `LICENSE-APACHE`).
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "sccache-dash"
description = "Records sccache's counters and serves a dashboard for them on localhost"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
sccache-dash-api = { path = "../api" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tiny_http = "0.12"
rusqlite = { version = "0.37", features = ["bundled"] }
wait-timeout = "0.2"
dirs = "6"
include_dir = "0.7"
[dev-dependencies]
tempfile = "3"
+37
View File
@@ -0,0 +1,37 @@
//! Puts the page into the binary. The page is what `trunk build --release` writes to
//! `crates/ui/dist`; until it has been built, a placeholder page stands in for it.
use std::path::Path;
const PLACEHOLDER: &str = "<!doctype html>
<meta charset=\"utf-8\">
<title>sccache-dash</title>
<body style=\"font: 16px sans-serif; margin: 3em auto; max-width: 34em;\">
<h1>The sccache dashboard page is not built</h1>
<p>The server is running and its <a href=\"/api/view?range=24h\">API</a> answers, but the page
that draws it is missing. Run <code>just build</code> in the repository (it runs
<code>trunk build --release</code> in <code>crates/ui</code>) and start sccache-dash again.
";
fn main() {
let crates = Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap())
.parent()
.expect("crates/server has a parent")
.to_path_buf();
let dist = crates.join("ui").join("dist");
// Checked on every build, so the page is picked up as soon as `trunk build` has made it.
println!(
"cargo:rerun-if-changed={}",
dist.join("index.html").display()
);
let site = if dist.join("index.html").is_file() {
dist
} else {
let out = Path::new(&std::env::var("OUT_DIR").unwrap()).join("site");
std::fs::create_dir_all(&out).unwrap();
std::fs::write(out.join("index.html"), PLACEHOLDER).unwrap();
out
};
println!("cargo:rustc-env=DASH_SITE={}", site.display());
}
+283
View File
@@ -0,0 +1,283 @@
//! 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::mpsc::{channel, Receiver, Sender};
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::{History, Tracker};
use crate::stats::{self, Snapshot};
use crate::view;
/// How often sccache is asked for its counters.
pub const POLL: Duration = Duration::from_secs(10);
/// 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);
/// The ranges a view is kept for, in the order they are cached.
pub const RANGES: [Range; 5] = [
Range::Hour,
Range::Day,
Range::Week,
Range::Month,
Range::SinceReset,
];
pub struct Config {
/// The sccache command the service runs.
pub sccache: OsString,
/// The SQLite file the history is saved in.
pub history: PathBuf,
}
impl Config {
/// `SCCACHE_DASH_SCCACHE` names the sccache command (`sccache` when unset); the history
/// lives in `$XDG_DATA_HOME/sccache-dash/history.db`.
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.db"),
})
}
}
pub fn unix_now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64)
}
/// 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 {
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>,
/// What the previous poll and the last saved row saw.
pub tracker: Tracker,
/// One view per range of [`RANGES`], made after every poll.
pub views: Vec<View>,
/// How long making those views took at the last poll.
pub views_took: Duration,
/// Whether a failure to save, and the first timing, have already been reported.
pub reported: bool,
}
pub struct App {
pub cfg: Config,
state: Mutex<State>,
/// Wakes the polling task, as `/api/zero` needs: only that task holds the database.
wake: (Sender<()>, Mutex<Option<Receiver<()>>>),
}
impl App {
pub fn new(cfg: Config) -> App {
let (send, receive) = channel();
App {
cfg,
state: Mutex::new(State::default()),
wake: (send, Mutex::new(Some(receive))),
}
}
pub fn lock(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
/// The view made for `range` at the last poll. A request never touches the database.
pub fn view(&self, range: Range) -> View {
let state = self.lock();
match state.views.get(index(range)) {
Some(view) => view.clone(),
None => View {
range: Some(range),
..View::default()
},
}
}
/// Opens the history for the polling task: what is too old is deleted, and what the
/// previous run remembered is taken over.
pub fn open_history(&self, now: i64) -> Result<History, String> {
let file = self.cfg.history.display().to_string();
let history =
History::open(&self.cfg.history).map_err(|e| format!("cannot open {file}: {e}"))?;
history
.prune(now)
.map_err(|e| format!("cannot prune {file}: {e}"))?;
self.lock().tracker = history.tracker();
Ok(history)
}
pub fn poll(&self, history: &History) {
self.poll_at(history, unix_now());
}
/// Asks sccache for its counters and version, records what changed, and makes the views.
pub fn poll_at(&self, history: &History, 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)) => {
state.error = None;
state.raw = serde_json::from_str(&text).ok();
state.live = Some(Live {
at: now,
snapshot,
raw_text: text,
});
}
Err(e) => {
state.error = Some(e);
state.live = None;
state.raw = None;
}
}
let file = self.cfg.history.display().to_string();
if let Some(counters) = state.live.as_ref().map(|l| l.snapshot.counters.clone()) {
match history.record(&mut state.tracker, &counters, now) {
Ok(()) => {}
Err(e) if !state.reported => {
state.reported = true;
eprintln!("sccache-dash: cannot save history to {file}: {e}");
}
Err(_) => {}
}
}
let started = Instant::now();
state.views = view::all(history, &state, now);
state.views_took = started.elapsed();
if !state.reported {
state.reported = true;
eprintln!(
"sccache-dash: {} rows of history in {}; the five views take {:.2} ms per poll",
history.row_count().unwrap_or(0),
file,
state.views_took.as_secs_f64() * 1e3
);
}
}
/// Runs `sccache --zero-stats`; the saved history stays as it is.
pub fn zero(&self) -> Result<(), String> {
run(&self.cfg.sccache, &["--zero-stats"])?;
// The counters are read again right away by the polling task, which owns the database.
let _ = self.wake.0.send(());
Ok(())
}
/// Polls sccache every [`POLL`] (sooner when woken) and prunes the history once a day,
/// until the process ends. This task alone holds the database.
pub fn keep_updated(self: Arc<Self>) {
thread::spawn(move || {
let history = match self.open_history(unix_now()) {
Ok(history) => history,
Err(e) => {
eprintln!("sccache-dash: {e}");
std::process::exit(1);
}
};
let wake = self
.wake
.1
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take();
let mut pruned = Instant::now();
loop {
self.poll(&history);
if pruned.elapsed() >= PRUNE_EVERY {
pruned = Instant::now();
if let Err(e) = history.prune(unix_now()) {
eprintln!(
"sccache-dash: cannot prune {}: {e}",
self.cfg.history.display()
);
}
}
match &wake {
Some(receiver) => {
let _ = receiver.recv_timeout(POLL);
}
None => thread::sleep(POLL),
}
}
});
}
}
/// Where a range's view is kept.
fn index(range: Range) -> usize {
RANGES.iter().position(|r| *r == range).unwrap_or(1)
}
/// 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)
}
+371
View File
@@ -0,0 +1,371 @@
//! The saved history in one SQLite file. Each row holds what changed since the row before it,
//! so that a range total is one indexed `SELECT SUM(...)`. Rows come at most one a minute and
//! only when sccache's counters changed; a stretch without rows is a gap.
use std::collections::BTreeMap;
use std::path::Path;
use std::time::Duration;
use rusqlite::{params, params_from_iter, Connection, OptionalExtension};
use sccache_dash_api::Totals;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use crate::stats::{Counters, COMPILE};
/// Rows older than this are deleted.
pub const KEEP_DAYS: i64 = 30;
/// Never more than one saved row per minute.
pub const MIN_ROW_SECS: i64 = 60;
const NANOS: f64 = 1e9;
/// The counters of a reading, each visited once: every query goes through this list.
macro_rules! each {
($m:ident!($($a:tt)*)) => {
$m!(requests, executed, hits, misses, not_cacheable, unsupported_compiler, not_compile,
timeouts, read_errors, write_errors, other_errors, compile_fails, forced_recaches,
cache_writes; $($a)*)
};
}
macro_rules! names {
($($c:ident),* ;) => { concat!($(",", stringify!($c)),*) };
}
macro_rules! defs {
($($c:ident),* ;) => { concat!($(",", stringify!($c), " INTEGER NOT NULL DEFAULT 0"),*) };
}
macro_rules! sums {
($($c:ident),* ;) => { concat!($(", SUM(", stringify!($c), ") AS ", stringify!($c)),*) };
}
macro_rules! totals_of {
($($c:ident),* ; $row:expr) => { Totals { $( $c: $row.get::<_, i64>(stringify!($c))?.max(0) as u64, )* } };
}
macro_rules! push {
($($c:ident),* ; $t:expr, $v:expr) => { $( $v.push(Box::new($t.$c as i64) as Box<dyn rusqlite::ToSql>); )* };
}
const NAMES: &str = each!(names!());
const DEFS: &str = each!(defs!());
const SUMS: &str = each!(sums!());
/// One point of the histogram of build times: the builds of one language that finished between
/// two polls ten seconds apart.
#[derive(Clone, Debug, PartialEq)]
pub struct BuildObs {
pub t: i64,
pub language: String,
pub compiles: u64,
pub seconds: f64,
}
/// What is remembered between polls, so that differences survive a restart of sccache-dash.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Tracker {
/// The running totals at the previous poll.
pub last_poll: Option<Counters>,
/// The running totals when the last row was saved.
pub row_base: Option<Counters>,
/// When the last row was saved.
pub row_at: i64,
}
/// One saved row: when it was written, and what had changed since the row before.
#[derive(Clone, Debug, PartialEq)]
pub struct Row {
pub t: i64,
/// sccache's counters went back to zero before this row.
pub reset: bool,
pub delta: Counters,
}
pub struct History {
conn: Connection,
}
impl History {
/// Opens (or creates) the file in WAL mode. The connection belongs to the task that polls.
pub fn open(path: &Path) -> Result<History, String> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
}
Self::init(Connection::open(path).map_err(|e| format!("{}: {e}", path.display()))?)
.map_err(|e| e.to_string())
}
/// An empty history that is never written to disk, for tests.
pub fn memory() -> rusqlite::Result<History> {
Self::init(Connection::open_in_memory()?)
}
fn init(conn: Connection) -> rusqlite::Result<History> {
let _: String = conn.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))?;
conn.busy_timeout(Duration::from_secs(5))?;
conn.execute_batch(&format!(
"CREATE TABLE IF NOT EXISTS readings (t INTEGER PRIMARY KEY, reset INTEGER NOT NULL DEFAULT 0{DEFS}, \
compilations INTEGER NOT NULL DEFAULT 0, hit_read REAL NOT NULL DEFAULT 0, \
cache_write REAL NOT NULL DEFAULT 0, compile REAL NOT NULL DEFAULT 0);\n{OTHER_TABLES}"
))?;
Ok(History { conn })
}
/// Deletes the rows older than [`KEEP_DAYS`], and says how many went.
pub fn prune(&self, now: i64) -> rusqlite::Result<usize> {
let cutoff = now - KEEP_DAYS * 86_400;
let mut gone = 0;
for table in ["readings", "reading_languages", "not_cached", "build_obs"] {
gone += self
.conn
.execute(&format!("DELETE FROM {table} WHERE t < ?1"), [cutoff])?;
}
Ok(gone)
}
fn state<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
let text: Option<String> = self
.conn
.query_row("SELECT value FROM state WHERE key = ?1", [key], |row| {
row.get(0)
})
.optional()
.ok()?;
text.and_then(|text| serde_json::from_str(&text).ok())
}
fn set_state<T: Serialize>(&self, key: &str, value: &T) -> rusqlite::Result<()> {
let value = serde_json::to_string(value)
.map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?;
self.conn.execute(
"INSERT INTO state (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
params![key, value],
)?;
Ok(())
}
/// What the previous run of sccache-dash remembered, so that it carries on where it stopped.
pub fn tracker(&self) -> Tracker {
self.state("tracker").unwrap_or_default()
}
/// Records what a poll saw at `now`: a build-time observation when one language's builds
/// finished since the previous poll, a row when one is due and something changed, and the
/// totals for next time.
pub fn record(&self, tracker: &mut Tracker, c: &Counters, now: i64) -> rusqlite::Result<()> {
if let Some(previous) = &tracker.last_poll {
let (since, _) = c.since(previous);
if let Some((language, _)) = since.one_missed_language() {
let seconds = since.ns[COMPILE] as f64 / NANOS;
self.conn.execute(
"INSERT OR REPLACE INTO build_obs (t, language, compiles, seconds) VALUES (?1, ?2, ?3, ?4)",
params![now, language, since.compilations as i64, seconds],
)?;
}
}
// The first reading ever is a baseline. After it: a row a minute at most, and only when something changed.
match &tracker.row_base {
None => {
tracker.row_base = Some(c.clone());
tracker.row_at = now;
}
Some(base) => {
let (diff, reset) = c.since(base);
let changed = diff != Counters::default() || reset;
if changed && now - tracker.row_at >= MIN_ROW_SECS {
self.save(now, &diff, reset)?;
tracker.row_base = Some(c.clone());
tracker.row_at = now;
}
}
}
tracker.last_poll = Some(c.clone());
self.set_state("tracker", tracker)
}
/// Writes what changed since the row before.
fn save(&self, t: i64, diff: &Counters, reset: bool) -> rusqlite::Result<()> {
let mut values: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(t), Box::new(reset)];
each!(push!(diff.totals, values));
values.push(Box::new(diff.compilations as i64));
for n in diff.ns {
values.push(Box::new(n as f64 / NANOS));
}
let marks = vec!["?"; NAMES.matches(',').count()].join(", ");
let sql = format!(
"INSERT INTO readings (t, reset{NAMES}, compilations, hit_read, cache_write, compile) VALUES (?, ?, {marks}, ?, ?, ?, ?)"
);
self.conn
.execute(&sql, params_from_iter(values.iter().map(|v| v.as_ref())))?;
let mut langs = self.conn.prepare(
"INSERT INTO reading_languages (t, language, hits, misses, errors) VALUES (?1, ?2, ?3, ?4, ?5)",
)?;
for (name, v) in &diff.langs {
langs.execute(params![t, name, v[0] as i64, v[1] as i64, v[2] as i64])?;
}
let mut reasons = self
.conn
.prepare("INSERT INTO not_cached (t, reason, count) VALUES (?1, ?2, ?3)")?;
for (reason, count) in &diff.not_cached {
reasons.execute(params![t, reason, *count as i64])?;
}
Ok(())
}
/// The totals of the rows from `from` (inclusive) to `to` (exclusive): one indexed query.
/// `None` when there is no row in that time.
pub fn sums(&self, from: i64, to: i64) -> rusqlite::Result<Option<Totals>> {
let sql = format!("SELECT COUNT(*){SUMS} FROM readings WHERE t >= ?1 AND t < ?2");
self.conn.query_row(&sql, params![from, to], |row| {
let rows: i64 = row.get(0)?;
Ok(if rows > 0 {
Some(each!(totals_of!(row)))
} else {
None
})
})
}
/// The rows from `from` (inclusive) to `to` (exclusive), oldest first.
pub fn rows(&self, from: i64, to: i64) -> rusqlite::Result<Vec<Row>> {
let sql = format!(
"SELECT t, reset{NAMES}, compilations, hit_read, cache_write, compile FROM readings WHERE t >= ?1 AND t < ?2 ORDER BY t"
);
let mut stmt = self.conn.prepare(&sql)?;
let rows = stmt.query_map(params![from, to], |row| {
let nanos = |name: &str| -> rusqlite::Result<u64> {
Ok((row.get::<_, f64>(name)? * NANOS).round().max(0.0) as u64)
};
Ok(Row {
t: row.get("t")?,
reset: row.get::<_, i64>("reset")? != 0,
delta: Counters {
totals: each!(totals_of!(row)),
compilations: row.get::<_, i64>("compilations")?.max(0) as u64,
ns: [nanos("hit_read")?, nanos("cache_write")?, nanos("compile")?],
..Counters::default()
},
})
})?;
rows.collect()
}
/// (language, hits, misses, errors) summed over the rows from `from` to `to`.
pub fn languages(&self, from: i64, to: i64) -> rusqlite::Result<Vec<(String, [u64; 3])>> {
let mut stmt = self.conn.prepare(
"SELECT language, SUM(hits), SUM(misses), SUM(errors) FROM reading_languages WHERE t >= ?1 AND t < ?2 GROUP BY language ORDER BY language",
)?;
let out = stmt.query_map(params![from, to], |row| {
Ok((
row.get(0)?,
[
row.get::<_, i64>(1)?.max(0) as u64,
row.get::<_, i64>(2)?.max(0) as u64,
row.get::<_, i64>(3)?.max(0) as u64,
],
))
})?;
out.collect()
}
/// (t, language, hits, misses) of the rows from `from` to `to`, for the chart.
pub fn language_rows(
&self,
from: i64,
to: i64,
) -> rusqlite::Result<Vec<(i64, String, u64, u64)>> {
let mut stmt = self.conn.prepare(
"SELECT t, language, hits, misses FROM reading_languages WHERE t >= ?1 AND t < ?2 ORDER BY t",
)?;
let out = stmt.query_map(params![from, to], |row| {
Ok((
row.get(0)?,
row.get(1)?,
row.get::<_, i64>(2)?.max(0) as u64,
row.get::<_, i64>(3)?.max(0) as u64,
))
})?;
out.collect()
}
/// (reason, count) summed over the rows from `from` to `to`.
pub fn reasons(&self, from: i64, to: i64) -> rusqlite::Result<Vec<(String, u64)>> {
let mut stmt = self.conn.prepare(
"SELECT reason, SUM(count) FROM not_cached WHERE t >= ?1 AND t < ?2 GROUP BY reason ORDER BY reason",
)?;
let out = stmt.query_map(params![from, to], |row| {
Ok((row.get(0)?, row.get::<_, i64>(1)?.max(0) as u64))
})?;
out.collect()
}
/// `requests` summed over the rows from `from` on.
pub fn requests_since(&self, from: i64) -> rusqlite::Result<u64> {
let sum: i64 = self.conn.query_row(
"SELECT COALESCE(SUM(requests), 0) FROM readings WHERE t >= ?1",
[from],
|row| row.get(0),
)?;
Ok(sum.max(0) as u64)
}
/// When the counters were last seen to be zeroed; `None` when they never were.
pub fn last_reset(&self) -> rusqlite::Result<Option<i64>> {
self.conn
.query_row("SELECT MAX(t) FROM readings WHERE reset != 0", [], |row| {
row.get(0)
})
}
/// The oldest row there is.
pub fn first_row(&self) -> rusqlite::Result<Option<i64>> {
self.conn
.query_row("SELECT MIN(t) FROM readings", [], |row| row.get(0))
}
/// How many rows there are, all told.
pub fn row_count(&self) -> rusqlite::Result<usize> {
self.conn
.query_row("SELECT COUNT(*) FROM readings", [], |row| row.get(0))
}
/// (seconds spent compiling, compiles) seen for each language, from the build observations.
pub fn build_time_totals(&self) -> rusqlite::Result<BTreeMap<String, (f64, u64)>> {
let mut stmt = self.conn.prepare(
"SELECT language, SUM(seconds), SUM(compiles) FROM build_obs GROUP BY language",
)?;
let out = stmt.query_map([], |row| {
Ok((
row.get(0)?,
(row.get::<_, f64>(1)?, row.get::<_, i64>(2)?.max(0) as u64),
))
})?;
out.collect()
}
/// The build-time observations, per language and oldest first: the raw data of the histogram.
pub fn build_observations(&self) -> rusqlite::Result<BTreeMap<String, Vec<BuildObs>>> {
let mut stmt = self
.conn
.prepare("SELECT t, language, compiles, seconds FROM build_obs ORDER BY language, t")?;
let out = stmt.query_map([], |row| {
Ok(BuildObs {
t: row.get(0)?,
language: row.get(1)?,
compiles: row.get::<_, i64>(2)?.max(0) as u64,
seconds: row.get(3)?,
})
})?;
let mut by_language: BTreeMap<String, Vec<BuildObs>> = BTreeMap::new();
for obs in out {
let obs = obs?;
by_language
.entry(obs.language.clone())
.or_default()
.push(obs);
}
Ok(by_language)
}
}
const OTHER_TABLES: &str = "
CREATE TABLE IF NOT EXISTS reading_languages (t INTEGER NOT NULL, language TEXT NOT NULL, hits INTEGER NOT NULL, misses INTEGER NOT NULL, errors INTEGER NOT NULL, PRIMARY KEY (t, language)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS not_cached (t INTEGER NOT NULL, reason TEXT NOT NULL, count INTEGER NOT NULL, PRIMARY KEY (t, reason)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS build_obs (t INTEGER NOT NULL, language TEXT NOT NULL, compiles INTEGER NOT NULL, seconds REAL NOT NULL, PRIMARY KEY (t, language)) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS build_obs_language ON build_obs (language);
CREATE TABLE IF NOT EXISTS state (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;";
+235
View File
@@ -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:?}");
}
}
}
+10
View File
@@ -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;
+163
View File
@@ -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::{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()?));
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"));
}
}
+135
View File
@@ -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
}
}
+576
View File
@@ -0,0 +1,576 @@
//! 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)
}
/// The language of the misses when they were all of one language: (name, misses).
pub fn one_missed_language(&self) -> Option<(&str, u64)> {
let mut with_misses = self.langs.iter().filter(|(_, v)| v[1] > 0);
let (name, v) = with_misses.next()?;
with_misses.next().is_none().then(|| (name.as_str(), v[1]))
}
/// 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 counters_survive_the_round_trip_through_saved_state() {
// The totals sccache-dash remembers between polls are saved as JSON.
let counters = parse(LIVE).unwrap().counters;
let text = serde_json::to_string(&counters).unwrap();
assert_eq!(serde_json::from_str::<Counters>(&text).unwrap(), counters);
assert!(text.len() < 1024, "{} bytes: {text}", text.len());
}
#[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())]
);
}
}
+130
View File
@@ -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
+408
View File
@@ -0,0 +1,408 @@
//! The server as seen from a socket, with a stand-in for sccache so that the real one is never touched.
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use std::sync::Arc;
use std::thread;
use sccache_dash::app::{unix_now, App, Config};
use sccache_dash::history::History;
use sccache_dash::stats;
use sccache_dash_api::{Range, Status, Totals, View};
const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json");
const ZEROED: &str = "{\"stats\":{\"compile_requests\":0,\"cache_hits\":{\"counts\":{},\"adv_counts\":{}},\"cache_misses\":{\"counts\":{},\"adv_counts\":{}},\"cache_errors\":{\"counts\":{},\"adv_counts\":{}}},\"version\":\"0.18.0\"}";
const NOW: i64 = 1_764_000_000;
/// A script that answers like sccache: it prints a fixture for `--show-stats` and swaps in
/// `ZEROED` when asked to zero the stats. Every call is logged.
struct Fake {
dir: tempfile::TempDir,
script: PathBuf,
log: PathBuf,
history: PathBuf,
}
impl Fake {
fn new() -> Fake {
let dir = tempfile::tempdir().unwrap();
let script = dir.path().join("sccache");
std::fs::write(
&script,
r#"#!/bin/sh
printf '%s\n' "$*" >> "$0.log"
case "$1" in
--version) echo 'sccache 0.18.0' ;;
--zero-stats) cp "$0.zeroed" "$0.out" ;;
*) cat "$0.out" ;;
esac
"#,
)
.unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(dir.path().join("sccache.out"), LIVE).unwrap();
std::fs::write(dir.path().join("sccache.zeroed"), ZEROED).unwrap();
Fake {
log: dir.path().join("sccache.log"),
history: dir.path().join("data").join("history.db"),
dir,
script,
}
}
/// What `--show-stats` prints from now on.
fn answers(&self, text: &str) {
std::fs::write(self.dir.path().join("sccache.out"), text).unwrap();
}
/// The arguments of every call so far, one entry per call.
fn calls(&self) -> Vec<String> {
std::fs::read_to_string(&self.log)
.unwrap_or_default()
.lines()
.map(str::to_owned)
.collect()
}
fn config(&self) -> Config {
Config {
sccache: self.script.clone().into(),
history: self.history.clone(),
}
}
}
/// A server on a free port next to an empty history, polled once, answering in the background.
/// The test stands in for the polling task: it holds the history and polls by hand.
fn start(fake: &Fake) -> (Arc<App>, History, SocketAddr) {
let app = Arc::new(App::new(fake.config()));
let history = History::memory().unwrap();
app.poll_at(&history, NOW);
let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
let addr = server.server_addr().to_ip().unwrap();
let answering = Arc::clone(&app);
thread::spawn(move || sccache_dash::http::answer(server, answering));
(app, history, addr)
}
/// Sends one raw request (`{port}` stands for the server's port) and returns the whole response.
fn send(addr: SocketAddr, request: &str) -> String {
let request = request.replace("{port}", &addr.port().to_string());
let mut stream = TcpStream::connect(addr).unwrap();
stream.write_all(request.as_bytes()).unwrap();
let mut response = String::new();
stream.read_to_string(&mut response).unwrap();
response
}
const GET: &str = " HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n";
/// `POST /api/zero` with the given `Host` and `Origin` headers; returns the status and the response.
fn zero(addr: SocketAddr, host: Option<&str>, origin: Option<&str>) -> (u16, String) {
let mut request = String::from("POST /api/zero HTTP/1.1\r\n");
for (name, value) in [("Host:", host), ("Origin:", origin)] {
if let Some(value) = value {
request.push_str(&format!("{name} {value}\r\n"));
}
}
request.push_str("Content-Length: 0\r\nConnection: close\r\n\r\n");
let response = send(addr, &request);
let code = response
.split_whitespace()
.nth(1)
.and_then(|c| c.parse().ok());
(code.unwrap_or(0), response)
}
#[test]
fn zero_is_refused_for_a_foreign_origin_or_host() {
let fake = Fake::new();
let (app, history, addr) = start(&fake);
// A page anywhere else, in any shape: a bare host, another port, or "null".
for origin in [
"https://evil.example",
"http://127.0.0.1:1",
"http://localhost.evil.example:{port}",
"null",
] {
let (code, response) = zero(addr, Some("127.0.0.1:{port}"), Some(origin));
assert_eq!(
(code, response.contains("refused")),
(403, true),
"Origin {origin}"
);
}
// A host name that merely leads here (DNS rebinding) or is not plainly localhost.
for host in [
"evil.example:{port}",
"127.0.0.1.evil.example:{port}",
"localhost:{port}@evil.example",
"[::1]:{port}",
] {
let (code, _) = zero(addr, Some(host), None);
assert_eq!(code, 403, "Host {host}");
}
let (code, _) = zero(addr, None, None);
assert_eq!(code, 403, "no Host at all");
assert!(
!fake.calls().iter().any(|c| c == "--zero-stats"),
"sccache was never asked to zero: {:?}",
fake.calls()
);
assert_eq!(
history.row_count().unwrap(),
0,
"and nothing was written to the history"
);
assert_eq!(
app.lock().tracker.row_base.as_ref().unwrap().totals,
stats::parse(LIVE).unwrap().counters.totals
);
}
#[test]
fn zero_from_the_dashboard_zeroes_sccache_and_keeps_the_history() {
let fake = Fake::new();
let (app, history, addr) = start(&fake);
let (code, response) = zero(
addr,
Some("127.0.0.1:{port}"),
Some("http://127.0.0.1:{port}"),
);
assert_eq!(
(code, response.contains("the saved history is kept")),
(200, true),
"{response}"
);
assert_eq!(
zero(addr, Some("localhost:{port}"), None).0,
200,
"no Origin, as from curl"
);
// What the polling task then does, woken by the request: it reads the counters again.
app.poll_at(&history, unix_now());
let calls = fake.calls();
assert_eq!(calls.iter().filter(|c| *c == "--zero-stats").count(), 2);
assert_eq!(calls.last().unwrap(), "--show-stats --stats-format json");
assert_eq!(
history.row_count().unwrap(),
1,
"the history stays, and the zeroing is one more row"
);
let row = &history.rows(0, i64::MAX).unwrap()[0];
assert!(row.reset, "the zeroing shows in the history as a reset");
assert_eq!(
row.delta,
stats::Counters::default(),
"nothing has been compiled since"
);
assert_eq!(history.last_reset().unwrap(), Some(row.t));
let v = app.view(Range::SinceReset);
assert_eq!(
v.totals,
Totals::default(),
"sccache's counters read zero now"
);
assert!(
v.buckets[0].reset,
"and its chart starts at the reset: {:?}",
v.buckets
);
}
#[test]
fn view_export_and_the_page_answer() {
let fake = Fake::new();
let (_app, _history, addr) = start(&fake);
let response = send(addr, &format!("GET /api/view?range=reset{GET}"));
assert!(
response.starts_with("HTTP/1.1 200 OK\r\n")
&& response.contains("Content-Type: application/json\r\n"),
"{response}"
);
let body = response.split("\r\n\r\n").nth(1).unwrap();
let v: View = serde_json::from_str(body).unwrap();
assert_eq!(v.totals, stats::parse(LIVE).unwrap().counters.totals);
assert_eq!(
(v.range, v.server.status),
(Some(Range::SinceReset), Status::Idle)
);
assert_eq!(
(
v.server.version.as_deref(),
v.server.client_version.as_deref()
),
(Some("0.18.0"), Some("0.18.0"))
);
assert!(v
.summary_markdown
.starts_with("**sccache, since last reset**\n"));
for range in ["1h", "24h", "7d", "30d"] {
let response = send(addr, &format!("GET /api/view?range={range}{GET}"));
let v: View = serde_json::from_str(response.split("\r\n\r\n").nth(1).unwrap()).unwrap();
assert_eq!(v.buckets.len(), 120, "{range}");
}
let response = send(addr, &format!("GET /api/export{GET}"));
assert!(
response.contains("Content-Type: application/json\r\n"),
"{response}"
);
assert!(
response.contains(&format!(
"Content-Disposition: attachment; filename=\"sccache-stats-{}.json\"",
sccache_dash::pretty::stamp(NOW)
)),
"{response}"
);
assert!(response.ends_with(LIVE), "exactly as sccache printed it");
let response = send(addr, &format!("GET /{GET}"));
assert!(
response.starts_with("HTTP/1.1 200 OK\r\n")
&& response.contains("Content-Type: text/html; charset=utf-8\r\n"),
"{response}"
);
assert!(send(addr, &format!("HEAD /{GET}")).starts_with("HTTP/1.1 200 OK\r\n"));
assert!(send(addr, &format!("GET /api/view?range=bogus{GET}")).starts_with("HTTP/1.1 400"));
assert!(
send(addr, &format!("GET /api/view{GET}")).starts_with("HTTP/1.1 400"),
"no range at all"
);
assert!(send(addr, &format!("GET /../Cargo.toml{GET}")).starts_with("HTTP/1.1 404"));
assert!(send(addr, &format!("GET /no-such-file.wasm{GET}")).starts_with("HTTP/1.1 404"));
assert!(send(addr, &format!("PUT /api/zero{GET}")).starts_with("HTTP/1.1 405"));
}
#[test]
fn rows_are_saved_when_counters_change_and_at_most_once_a_minute() {
let fake = Fake::new();
let app = App::new(fake.config());
let history = History::memory().unwrap();
let rows = || history.row_count().unwrap();
app.poll_at(&history, NOW);
assert_eq!(rows(), 0, "the first reading is a baseline, not a row");
app.poll_at(&history, NOW + 10);
assert_eq!(rows(), 0, "nothing changed");
fake.answers(&LIVE.replace("\"compile_requests\":7351", "\"compile_requests\":7352"));
app.poll_at(&history, NOW + 30);
assert_eq!(
rows(),
0,
"changed, but less than a minute after the baseline"
);
app.poll_at(&history, NOW + 60);
assert_eq!(rows(), 1, "a minute on, the change is saved");
let row = &history.rows(0, i64::MAX).unwrap()[0];
assert_eq!(
(row.t, row.delta.totals.requests, row.reset),
(NOW + 60, 1, false)
);
app.poll_at(&history, NOW + 700);
assert_eq!(
rows(),
1,
"unchanged: nothing more is saved, however long the quiet lasts"
);
assert!(
history.build_observations().unwrap().is_empty(),
"and with no misses there is no build observation"
);
assert_eq!(app.lock().views.len(), 5, "every poll makes the five views");
}
#[test]
fn the_history_survives_a_restart_in_its_file() {
let fake = Fake::new();
let app = App::new(fake.config());
let path = fake.history.clone();
// The first run sees the baseline and a change, then stops.
let history = History::open(&path).unwrap();
history.prune(NOW).unwrap();
let mut tracker = history.tracker();
assert_eq!(tracker, Default::default(), "a new file remembers nothing");
let (a, b) = (
stats::parse(LIVE).unwrap().counters,
stats::parse(LIVE).unwrap().counters,
);
history.record(&mut tracker, &a, NOW).unwrap();
history.record(&mut tracker, &b, NOW + 10).unwrap();
drop(history);
// The next run picks up where it stopped: the difference is not lost or counted twice.
let history = History::open(&path).unwrap();
let mut tracker = history.tracker();
assert_eq!(
tracker.row_base,
Some(a.clone()),
"the totals at the baseline"
);
let mut c = b.clone();
c.totals.requests += 5;
history.record(&mut tracker, &c, NOW + 70).unwrap();
let rows = history.rows(0, i64::MAX).unwrap();
assert_eq!(rows.len(), 1);
assert_eq!((rows[0].t, rows[0].delta.totals.requests), (NOW + 70, 5));
assert_eq!(
app.view(Range::Day).range,
Some(Range::Day),
"and a server that has not polled yet answers with an empty view"
);
}
#[test]
fn old_rows_are_deleted_at_startup() {
let fake = Fake::new();
// A real file, as the service has, in WAL mode.
let history = History::open(&fake.history).unwrap();
let mut tracker = Default::default();
let day = 86_400;
let mut c = stats::Counters::default();
for (t, requests) in [
(NOW - 33 * day, 1),
(NOW - 31 * day, 2),
(NOW - 30 * day + 3600, 3),
(NOW - 3600, 4),
(NOW, 5),
] {
c.totals.requests = requests;
history.record(&mut tracker, &c, t).unwrap();
}
assert_eq!(
history.row_count().unwrap(),
4,
"rows carry differences; the first reading is the baseline"
);
assert_eq!(
history.prune(NOW).unwrap(),
1,
"the one row older than 30 days"
);
let left: Vec<i64> = history
.rows(0, i64::MAX)
.unwrap()
.iter()
.map(|r| r.t)
.collect();
assert_eq!(left, vec![NOW - 30 * day + 3600, NOW - 3600, NOW]);
assert_eq!(history.prune(NOW).unwrap(), 0, "nothing more to delete");
assert!(
fake.history.with_extension("db-wal").exists()
|| fake.history.with_extension("db-shm").exists(),
"WAL mode is on"
);
}
+1
View File
@@ -0,0 +1 @@
{"stats":{"compile_requests":820,"requests_unsupported_compiler":0,"requests_not_compile":2,"requests_not_cacheable":18,"requests_executed":800,"cache_errors":{"counts":{},"adv_counts":{}},"cache_hits":{"counts":{"C/C++":3},"adv_counts":{"c [gcc]":3}},"cache_misses":{"counts":{"C/C++":797},"adv_counts":{"c [gcc]":797}},"cache_timeouts":0,"cache_read_errors":0,"non_cacheable_compilations":0,"forced_recaches":0,"cache_write_errors":0,"cache_writes":797,"cache_write_duration":{"secs":9,"nanos":0},"cache_read_hit_duration":{"secs":0,"nanos":3000000},"compilations":797,"compiler_write_duration":{"secs":1200,"nanos":0},"compile_fails":0,"not_cached":{},"dist_compiles":{"10.0.0.12:4226":379,"buildbox.local:4228":9,"10.0.0.11:4226":402},"dist_errors":7,"multi_level":null},"cache_location":"Local disk: \"/home/me/.cache/sccache\"","cache_size":107374182,"max_cache_size":1073741824,"use_preprocessor_cache_mode":false,"version":"0.18.0","basedirs":[]}
+1
View File
@@ -0,0 +1 @@
{"stats":{"compile_requests":5000,"requests_unsupported_compiler":0,"requests_not_compile":12,"requests_not_cacheable":150,"requests_executed":4838,"cache_errors":{"counts":{},"adv_counts":{}},"cache_hits":{"counts":{"C/C++":2100,"Rust":400},"adv_counts":{"c [gcc]":2100,"rust":400}},"cache_misses":{"counts":{"Rust":2300,"C/C++":38},"adv_counts":{"rust":2300,"c [gcc]":38}},"cache_timeouts":12,"cache_read_errors":0,"non_cacheable_compilations":0,"forced_recaches":0,"cache_write_errors":5,"cache_writes":2338,"cache_write_duration":{"secs":40,"nanos":0},"cache_read_hit_duration":{"secs":0,"nanos":600000000},"compilations":2338,"compiler_write_duration":{"secs":18000,"nanos":0},"compile_fails":0,"not_cached":{"crate-type":150},"dist_compiles":{},"dist_errors":0,"multi_level":[{"name":"L0 (disk)","location":"Local disk: \"/home/me/.cache/sccache\"","hits":1500,"misses":1000,"writes":1400,"write_failures":2,"backfills_from":300,"backfills_to":0,"hit_duration":{"secs":1,"nanos":500000000},"write_duration":{"secs":2,"nanos":500000000}},{"name":"L1 (s3)","location":"s3, name: bucket, prefix: /p/","hits":1000,"misses":1800,"writes":900,"write_failures":0,"backfills_from":0,"backfills_to":300,"hit_duration":{"secs":6,"nanos":0},"write_duration":{"secs":36,"nanos":500000000}}]},"cache_location":"Multi-level: \"L0 (disk)\" + \"L1 (s3)\"","cache_size":1234567890,"max_cache_size":10737418240,"use_preprocessor_cache_mode":true,"version":"0.18.0","basedirs":[]}
+10
View File
@@ -0,0 +1,10 @@
# Build the page first, then the server with the page inside it.
build:
cd crates/ui && trunk build --release
cargo build --release -p sccache-dash
test:
cargo test -p sccache-dash -p sccache-dash-api
run:
cargo run -p sccache-dash