OXYGENHUB

Coverage / crates/flow/src/images.rs 31.8%

68 of 214 lines run, 14 of 76 functions · run #201 on main · run missed

1
//! Images by hash with a hub (oxygenflow#39, docs/jetstream.md §8):
2
//! `flow rootfs push` sends an image's missing chunks and its manifest;
3
//! `flow rootfs pull`, and a runner that lacks a job's image, fetch the
4
//! manifest and the chunks they lack and write the image back, checked
5
//! against its hash. Fetched chunks stay in the home's chunk cache
6
//! (`chunks/`), so a rebuilt image costs only the chunks that changed.
7
8
use crate::home::Home;
9
use anyhow::{bail, Context, Result};
10
use jet::images::{self, Chunk, Manifest};
11
use std::collections::HashSet;
12
use std::path::{Path, PathBuf};
13
use std::sync::Mutex;
14
use std::time::{Duration, Instant};
15
16
/// Requests in flight at once.
17
const PARALLEL: usize = 8;
18
/// Chunk names per `missing` question.
19
const ASK: usize = 20_000;
20
21
/// A hub's image endpoints, with a token.
22
pub struct Client {
23
    root: String,
24
    base: String,
25
    token: String,
26
    agent: ureq::Agent,
27
}
28
29
/// What a push or a fetch moved.
30
pub struct Moved {
31
    pub chunks: usize,
32
    pub bytes: u64,
33
    /// Of `bytes`, those that came from peers rather than the hub.
34
    pub peer_bytes: u64,
35
    pub elapsed: Duration,
36
}
37
38
impl Client {
3910×
    pub fn new(hub: &str, token: &str, ca: Option<&Path>) -> Result<Client> {
4010×
        let tls = oxy_core::protocol::tls_client_config(ca).map_err(|e| anyhow::anyhow!("{e}"))?;
4110×
        let agent = ureq::AgentBuilder::new().tls_config(tls).timeout(Duration::from_secs(120)).build();
4210×
        let root = hub.trim_end_matches('/').to_string();
4310×
        Ok(Client { base: format!("{root}/api/v1"), root, token: token.into(), agent })
4410×
    }
45
46140×
    fn auth(&self) -> String {
47140×
        format!("Bearer {}", self.token)
48140×
    }
49
500×
    fn fail(url: &str, e: ureq::Error) -> anyhow::Error {
510×
        match e {
520×
            ureq::Error::Status(code, r) => {
530×
                let text = r.into_string().unwrap_or_default();
540×
                let detail = serde_json::from_str::<serde_json::Value>(&text)
550×
                    .ok()
560×
                    .and_then(|v| v["detail"].as_str().map(String::from))
570×
                    .unwrap_or(text);
580×
                anyhow::anyhow!("{url}: HTTP {code}: {detail}")
59
            }
600×
            e => anyhow::anyhow!("{url}: {e}"),
61
        }
620×
    }
63
64
    /// The hub's manifest of image `hash`, `None` when it does not hold it.
655×
    pub fn manifest(&self, hash: &str) -> Result<Option<Manifest>> {
665×
        let url = format!("{}/flow/images/{hash}", self.base);
675×
        match self.agent.get(&url).set("Authorization", &self.auth()).call() {
685×
            Ok(r) => Ok(Some(r.into_json()?)),
690×
            Err(ureq::Error::Status(404, _)) => Ok(None),
700×
            Err(e) => Err(Self::fail(&url, e)),
71
        }
725×
    }
73
74
    /// The hub's identity (`/.well-known/oxyhub-key`): the key its swarm
75
    /// tickets are signed with.
769×
    pub fn hub_identity(&self) -> Result<oxy_core::identity::Identity> {
779×
        let url = format!("{}/.well-known/oxyhub-key", self.root);
789×
        let r = self.agent.get(&url).call().map_err(|e| Self::fail(&url, e))?;
799×
        let mut out = Vec::new();
809×
        std::io::Read::read_to_end(&mut r.into_reader(), &mut out)?;
819×
        oxy_core::identity::Identity::decode(&out).map_err(|e| anyhow::anyhow!("{url}: not a hub identity: {e}"))
829×
    }
83
84
    /// Tell the hub's tracker this runner is fetching image `hash`, or has
85
    /// stopped: the peers to ask and the ticket they admit.
8611×
    pub fn announce(&self, hash: &str, state: &str) -> Result<flow_core::api::Announced> {
8711×
        let url = format!("{}/flow/swarm/announce", self.base);
8811×
        let body = flow_core::api::Announce { image: hash.into(), state: state.into() };
8911×
        Ok(self.agent.post(&url).set("Authorization", &self.auth()).send_json(&body).map_err(|e| Self::fail(&url, e))?.into_json()?)
9011×
    }
91
92124×
    pub(crate) fn chunk(&self, hash: &str) -> Result<Vec<u8>> {
93124×
        let url = format!("{}/flow/images/chunks/{hash}", self.base);
94124×
        let r = self.agent.get(&url).set("Authorization", &self.auth()).call().map_err(|e| Self::fail(&url, e))?;
95124×
        let mut out = Vec::new();
96124×
        std::io::Read::read_to_end(&mut r.into_reader(), &mut out)?;
97124×
        Ok(out)
98124×
    }
99
100
    /// Send image `hash` from `home`: only the chunks the hub lacks, then
101
    /// the manifest, which the hub checks against the hash.
1020×
    pub fn push(&self, home: &Home, hash: &str) -> Result<Moved> {
1030×
        let start = Instant::now();
1040×
        let path = home.rootfs(hash);
1050×
        if !path.is_file() {
1060×
            bail!("{} is not in this Flow home ({}); import it first", &hash[..12.min(hash.len())], path.display());
1070×
        }
1080×
        let m = images::scan_file(&path, home.image_arch(hash), |_, _| Ok(()))?;
1090×
        if m.hash != hash {
1100×
            bail!("{} holds an image named {}, not {}: the file was changed", path.display(), &m.hash[..12], &hash[..12]);
1110×
        }
1120×
        let mut missing: HashSet<String> = HashSet::new();
113
        // 20,000 names is about 1.3 MB of JSON: under a hub's 2 MB default
114
        // body limit, which refused 50,000 at a time (oxygenhub#147).
1150×
        for ask in m.needed().chunks(ASK) {
1160×
            let url = format!("{}/flow/images/missing", self.base);
1170×
            let r: serde_json::Value = self
1180×
                .agent
1190×
                .post(&url)
1200×
                .set("Authorization", &self.auth())
1210×
                .send_json(serde_json::json!({ "chunks": ask }))
1220×
                .map_err(|e| Self::fail(&url, e))?
1230×
                .into_json()?;
1240×
            missing.extend(r["missing"].as_array().into_iter().flatten().filter_map(|h| h.as_str().map(String::from)));
125
        }
126
        // Read the image again, sending the missing chunks as they come.
1270×
        let (count, bytes) = (missing.len(), Mutex::new(0u64));
1280×
        let queue: Mutex<Vec<(String, Vec<u8>)>> = Mutex::new(Vec::new());
1290×
        let failed: Mutex<Option<anyhow::Error>> = Mutex::new(None);
1300×
        let sent = Mutex::new(HashSet::new());
1310×
        let send = |c: &str, b: &[u8]| -> Result<()> {
1320×
            let url = format!("{}/flow/images/chunks/{c}", self.base);
1330×
            self.agent.put(&url).set("Authorization", &self.auth()).send_bytes(b).map_err(|e| Self::fail(&url, e))?;
1340×
            *bytes.lock().unwrap() += b.len() as u64;
1350×
            Ok(())
1360×
        };
1370×
        images::scan_file(&path, None, |c: &Chunk, b: &[u8]| {
1380×
            if missing.contains(c.hash()) && sent.lock().unwrap().insert(c.hash().to_string()) {
1390×
                queue.lock().unwrap().push((c.hash().to_string(), b.to_vec()));
1400×
            }
1410×
            if queue.lock().unwrap().len() >= PARALLEL * 4 {
1420×
                let batch: Vec<_> = std::mem::take(&mut *queue.lock().unwrap());
1430×
                send_batch(&batch, &send, &failed);
1440×
            }
1450×
            match failed.lock().unwrap().take() {
1460×
                Some(e) => Err(images::Error::Bad(format!("{e:#}"))),
1470×
                None => Ok(()),
148
            }
1490×
        })?;
1500×
        let rest: Vec<_> = std::mem::take(&mut *queue.lock().unwrap());
1510×
        send_batch(&rest, &send, &failed);
1520×
        if let Some(e) = failed.lock().unwrap().take() {
1530×
            return Err(e);
1540×
        }
1550×
        let url = format!("{}/flow/images/{hash}", self.base);
156
        // The hub reads the whole image before it answers, which on a busy
157
        // disk takes far longer than the agent's 120 s (oxygenhub#341).
1580×
        self.agent
1590×
            .put(&url)
1600×
            .timeout(Duration::from_secs(3600))
1610×
            .set("Authorization", &self.auth())
1620×
            .send_json(&m)
1630×
            .map_err(|e| Self::fail(&url, e))?;
1640×
        let bytes = *bytes.lock().unwrap();
1650×
        Ok(Moved { chunks: count, bytes, peer_bytes: 0, elapsed: start.elapsed() })
1660×
    }
167
168
    /// Fetch image `hash` into `home`: the chunks its cache lacks, the
169
    /// image written and checked, its architecture recorded. `Ok(None)`
170
    /// when the hub does not hold it.
1710×
    pub fn fetch(&self, home: &Home, hash: &str) -> Result<Option<Moved>> {
1720×
        let start = Instant::now();
1730×
        let Some(m) = self.manifest(hash)? else { return Ok(None) };
1740×
        if m.hash != hash {
1750×
            bail!("the hub's manifest for {} names {}", &hash[..12], &m.hash[..12]);
1760×
        }
1770×
        let cache = chunk_cache(home);
1780×
        save_manifest(&home.root, &m)?;
1790×
        let wanted: Vec<String> = m.needed().into_iter().filter(|h| !cache_path(&cache, h).is_file()).map(String::from).collect();
1800×
        let (bytes, failed) = (Mutex::new(0u64), Mutex::new(None::<anyhow::Error>));
1810×
        let next = Mutex::new(wanted.iter());
1820×
        std::thread::scope(|s| {
1830×
            for _ in 0..PARALLEL {
1840×
                s.spawn(|| loop {
1850×
                    let Some(h) = next.lock().unwrap().next() else { break };
1860×
                    if failed.lock().unwrap().is_some() {
1870×
                        break;
1880×
                    }
1890×
                    let got = self.chunk(h).and_then(|b| {
1900×
                        if blake3::hash(&b).to_hex().as_str() != h {
1910×
                            bail!("chunk {} came back with other bytes", &h[..12]);
1920×
                        }
1930×
                        let p = cache_path(&cache, h);
1940×
                        std::fs::create_dir_all(p.parent().expect("a chunk directory"))?;
1950×
                        let tmp = p.with_extension("part");
1960×
                        std::fs::write(&tmp, &b)?;
1970×
                        std::fs::rename(&tmp, &p)?;
1980×
                        *bytes.lock().unwrap() += b.len() as u64;
1990×
                        Ok(())
2000×
                    });
2010×
                    if let Err(e) = got {
2020×
                        *failed.lock().unwrap() = Some(e);
2030×
                        break;
2040×
                    }
2050×
                });
206
            }
2070×
        });
2080×
        if let Some(e) = failed.into_inner().unwrap() {
2090×
            return Err(e);
2100×
        }
2110×
        write_image(home, &m)?;
2120×
        Ok(Some(Moved { chunks: wanted.len(), bytes: bytes.into_inner().unwrap(), peer_bytes: 0, elapsed: start.elapsed() }))
2130×
    }
214
}
215
216
/// Write image `m` into `home` from the chunk cache, checked against its
217
/// hash, and record its architecture.
2185×
pub(crate) fn write_image(home: &Home, m: &Manifest) -> Result<()> {
2195×
    let cache = chunk_cache(home);
2205×
    let out = home.rootfs(&m.hash);
2215×
    std::fs::create_dir_all(out.parent().expect("the cas directory"))?;
222190×
    images::assemble(m, &out, |c| Ok(std::fs::read(cache_path(&cache, c.hash()))?))
2235×
        .with_context(|| format!("write image {}", &m.hash[..12]))?;
2245×
    if let Some(arch) = &m.arch {
2251×
        let manifest = serde_json::json!({ "arch": arch, "imported_ms": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0), "from": "hub" });
2261×
        std::fs::write(home.image_manifest(&m.hash), serde_json::to_vec(&manifest)?)?;
2274×
    }
2285×
    Ok(())
2295×
}
230
231
/// Where an image's chunk manifest is kept (`manifests/<hash>.json`), so
232
/// the runner can serve its chunks to peers out of the image itself.
23310×
pub(crate) fn manifest_path(root: &Path, hash: &str) -> PathBuf {
23410×
    root.join("manifests").join(format!("{hash}.json"))
23510×
}
236
2377×
pub(crate) fn save_manifest(root: &Path, m: &Manifest) -> Result<()> {
2387×
    let p = manifest_path(root, &m.hash);
2397×
    std::fs::create_dir_all(p.parent().expect("the manifests directory"))?;
2407×
    let tmp = p.with_extension("part");
2417×
    std::fs::write(&tmp, serde_json::to_vec(m)?)?;
2427×
    std::fs::rename(&tmp, &p)?;
2437×
    Ok(())
2447×
}
245
2460×
fn send_batch(batch: &[(String, Vec<u8>)], send: &(dyn Fn(&str, &[u8]) -> Result<()> + Sync), failed: &Mutex<Option<anyhow::Error>>) {
2470×
    std::thread::scope(|s| {
2480×
        for part in batch.chunks(batch.len().div_ceil(PARALLEL).max(1)) {
2490×
            s.spawn(move || {
2500×
                for (h, b) in part {
2510×
                    if let Err(e) = send(h, b) {
2520×
                        *failed.lock().unwrap() = Some(e);
2530×
                        return;
2540×
                    }
255
                }
2560×
            });
257
        }
2580×
    });
2590×
}
260
261
/// The home's chunk cache.
26210×
pub fn chunk_cache(home: &Home) -> PathBuf {
26310×
    home.root.join("chunks")
26410×
}
265
266636×
pub(crate) fn cache_path(cache: &Path, hash: &str) -> PathBuf {
267636×
    cache.join(&hash[..2]).join(hash)
268636×
}
269
270
/// A size for people: 991 MiB, 1.2 GiB.
27138×
pub fn human(bytes: u64) -> String {
27238×
    if bytes >= 1 << 30 {
2730×
        format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64)
274
    } else {
27538×
        format!("{} MiB", bytes >> 20)
276
    }
27738×
}