OXYGENHUB
◆ v0.3.1 oxygenflow / crates / flow / src / images.rs
11.7 KiB · Rust · last changed flow rootfs push: ask about missing chunks 20,000 at a time 23 days ago source blame history raw
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 {
39
    pub fn new(hub: &str, token: &str, ca: Option<&Path>) -> Result<Client> {
40
        let tls = oxy_core::protocol::tls_client_config(ca).map_err(|e| anyhow::anyhow!("{e}"))?;
41
        let agent = ureq::AgentBuilder::new().tls_config(tls).timeout(Duration::from_secs(120)).build();
42
        let root = hub.trim_end_matches('/').to_string();
43
        Ok(Client { base: format!("{root}/api/v1"), root, token: token.into(), agent })
44
    }
45
46
    fn auth(&self) -> String {
47
        format!("Bearer {}", self.token)
48
    }
49
50
    fn fail(url: &str, e: ureq::Error) -> anyhow::Error {
51
        match e {
52
            ureq::Error::Status(code, r) => {
53
                let text = r.into_string().unwrap_or_default();
54
                let detail = serde_json::from_str::<serde_json::Value>(&text)
55
                    .ok()
56
                    .and_then(|v| v["detail"].as_str().map(String::from))
57
                    .unwrap_or(text);
58
                anyhow::anyhow!("{url}: HTTP {code}: {detail}")
59
            }
60
            e => anyhow::anyhow!("{url}: {e}"),
61
        }
62
    }
63
64
    /// The hub's manifest of image `hash`, `None` when it does not hold it.
65
    pub fn manifest(&self, hash: &str) -> Result<Option<Manifest>> {
66
        let url = format!("{}/flow/images/{hash}", self.base);
67
        match self.agent.get(&url).set("Authorization", &self.auth()).call() {
68
            Ok(r) => Ok(Some(r.into_json()?)),
69
            Err(ureq::Error::Status(404, _)) => Ok(None),
70
            Err(e) => Err(Self::fail(&url, e)),
71
        }
72
    }
73
74
    /// The hub's identity (`/.well-known/oxyhub-key`): the key its swarm
75
    /// tickets are signed with.
76
    pub fn hub_identity(&self) -> Result<oxy_core::identity::Identity> {
77
        let url = format!("{}/.well-known/oxyhub-key", self.root);
78
        let r = self.agent.get(&url).call().map_err(|e| Self::fail(&url, e))?;
79
        let mut out = Vec::new();
80
        std::io::Read::read_to_end(&mut r.into_reader(), &mut out)?;
81
        oxy_core::identity::Identity::decode(&out).map_err(|e| anyhow::anyhow!("{url}: not a hub identity: {e}"))
82
    }
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.
86
    pub fn announce(&self, hash: &str, state: &str) -> Result<flow_core::api::Announced> {
87
        let url = format!("{}/flow/swarm/announce", self.base);
88
        let body = flow_core::api::Announce { image: hash.into(), state: state.into() };
89
        Ok(self.agent.post(&url).set("Authorization", &self.auth()).send_json(&body).map_err(|e| Self::fail(&url, e))?.into_json()?)
90
    }
91
92
    pub(crate) fn chunk(&self, hash: &str) -> Result<Vec<u8>> {
93
        let url = format!("{}/flow/images/chunks/{hash}", self.base);
94
        let r = self.agent.get(&url).set("Authorization", &self.auth()).call().map_err(|e| Self::fail(&url, e))?;
95
        let mut out = Vec::new();
96
        std::io::Read::read_to_end(&mut r.into_reader(), &mut out)?;
97
        Ok(out)
98
    }
99
100
    /// Send image `hash` from `home`: only the chunks the hub lacks, then
101
    /// the manifest, which the hub checks against the hash.
102
    pub fn push(&self, home: &Home, hash: &str) -> Result<Moved> {
103
        let start = Instant::now();
104
        let path = home.rootfs(hash);
105
        if !path.is_file() {
106
            bail!("{} is not in this Flow home ({}); import it first", &hash[..12.min(hash.len())], path.display());
107
        }
108
        let m = images::scan_file(&path, home.image_arch(hash), |_, _| Ok(()))?;
109
        if m.hash != hash {
110
            bail!("{} holds an image named {}, not {}: the file was changed", path.display(), &m.hash[..12], &hash[..12]);
111
        }
112
        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).
115
        for ask in m.needed().chunks(ASK) {
116
            let url = format!("{}/flow/images/missing", self.base);
117
            let r: serde_json::Value = self
118
                .agent
119
                .post(&url)
120
                .set("Authorization", &self.auth())
121
                .send_json(serde_json::json!({ "chunks": ask }))
122
                .map_err(|e| Self::fail(&url, e))?
123
                .into_json()?;
124
            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.
127
        let (count, bytes) = (missing.len(), Mutex::new(0u64));
128
        let queue: Mutex<Vec<(String, Vec<u8>)>> = Mutex::new(Vec::new());
129
        let failed: Mutex<Option<anyhow::Error>> = Mutex::new(None);
130
        let sent = Mutex::new(HashSet::new());
131
        let send = |c: &str, b: &[u8]| -> Result<()> {
132
            let url = format!("{}/flow/images/chunks/{c}", self.base);
133
            self.agent.put(&url).set("Authorization", &self.auth()).send_bytes(b).map_err(|e| Self::fail(&url, e))?;
134
            *bytes.lock().unwrap() += b.len() as u64;
135
            Ok(())
136
        };
137
        images::scan_file(&path, None, |c: &Chunk, b: &[u8]| {
138
            if missing.contains(c.hash()) && sent.lock().unwrap().insert(c.hash().to_string()) {
139
                queue.lock().unwrap().push((c.hash().to_string(), b.to_vec()));
140
            }
141
            if queue.lock().unwrap().len() >= PARALLEL * 4 {
142
                let batch: Vec<_> = std::mem::take(&mut *queue.lock().unwrap());
143
                send_batch(&batch, &send, &failed);
144
            }
145
            match failed.lock().unwrap().take() {
146
                Some(e) => Err(images::Error::Bad(format!("{e:#}"))),
147
                None => Ok(()),
148
            }
149
        })?;
150
        let rest: Vec<_> = std::mem::take(&mut *queue.lock().unwrap());
151
        send_batch(&rest, &send, &failed);
152
        if let Some(e) = failed.lock().unwrap().take() {
153
            return Err(e);
154
        }
155
        let url = format!("{}/flow/images/{hash}", self.base);
156
        self.agent.put(&url).set("Authorization", &self.auth()).send_json(&m).map_err(|e| Self::fail(&url, e))?;
157
        let bytes = *bytes.lock().unwrap();
158
        Ok(Moved { chunks: count, bytes, peer_bytes: 0, elapsed: start.elapsed() })
159
    }
160
161
    /// Fetch image `hash` into `home`: the chunks its cache lacks, the
162
    /// image written and checked, its architecture recorded. `Ok(None)`
163
    /// when the hub does not hold it.
164
    pub fn fetch(&self, home: &Home, hash: &str) -> Result<Option<Moved>> {
165
        let start = Instant::now();
166
        let Some(m) = self.manifest(hash)? else { return Ok(None) };
167
        if m.hash != hash {
168
            bail!("the hub's manifest for {} names {}", &hash[..12], &m.hash[..12]);
169
        }
170
        let cache = chunk_cache(home);
171
        save_manifest(&home.root, &m)?;
172
        let wanted: Vec<String> = m.needed().into_iter().filter(|h| !cache_path(&cache, h).is_file()).map(String::from).collect();
173
        let (bytes, failed) = (Mutex::new(0u64), Mutex::new(None::<anyhow::Error>));
174
        let next = Mutex::new(wanted.iter());
175
        std::thread::scope(|s| {
176
            for _ in 0..PARALLEL {
177
                s.spawn(|| loop {
178
                    let Some(h) = next.lock().unwrap().next() else { break };
179
                    if failed.lock().unwrap().is_some() {
180
                        break;
181
                    }
182
                    let got = self.chunk(h).and_then(|b| {
183
                        if blake3::hash(&b).to_hex().as_str() != h {
184
                            bail!("chunk {} came back with other bytes", &h[..12]);
185
                        }
186
                        let p = cache_path(&cache, h);
187
                        std::fs::create_dir_all(p.parent().expect("a chunk directory"))?;
188
                        let tmp = p.with_extension("part");
189
                        std::fs::write(&tmp, &b)?;
190
                        std::fs::rename(&tmp, &p)?;
191
                        *bytes.lock().unwrap() += b.len() as u64;
192
                        Ok(())
193
                    });
194
                    if let Err(e) = got {
195
                        *failed.lock().unwrap() = Some(e);
196
                        break;
197
                    }
198
                });
199
            }
200
        });
201
        if let Some(e) = failed.into_inner().unwrap() {
202
            return Err(e);
203
        }
204
        write_image(home, &m)?;
205
        Ok(Some(Moved { chunks: wanted.len(), bytes: bytes.into_inner().unwrap(), peer_bytes: 0, elapsed: start.elapsed() }))
206
    }
207
}
208
209
/// Write image `m` into `home` from the chunk cache, checked against its
210
/// hash, and record its architecture.
211
pub(crate) fn write_image(home: &Home, m: &Manifest) -> Result<()> {
212
    let cache = chunk_cache(home);
213
    let out = home.rootfs(&m.hash);
214
    std::fs::create_dir_all(out.parent().expect("the cas directory"))?;
215
    images::assemble(m, &out, |c| Ok(std::fs::read(cache_path(&cache, c.hash()))?))
216
        .with_context(|| format!("write image {}", &m.hash[..12]))?;
217
    if let Some(arch) = &m.arch {
218
        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" });
219
        std::fs::write(home.image_manifest(&m.hash), serde_json::to_vec(&manifest)?)?;
220
    }
221
    Ok(())
222
}
223
224
/// Where an image's chunk manifest is kept (`manifests/<hash>.json`), so
225
/// the runner can serve its chunks to peers out of the image itself.
226
pub(crate) fn manifest_path(root: &Path, hash: &str) -> PathBuf {
227
    root.join("manifests").join(format!("{hash}.json"))
228
}
229
230
pub(crate) fn save_manifest(root: &Path, m: &Manifest) -> Result<()> {
231
    let p = manifest_path(root, &m.hash);
232
    std::fs::create_dir_all(p.parent().expect("the manifests directory"))?;
233
    let tmp = p.with_extension("part");
234
    std::fs::write(&tmp, serde_json::to_vec(m)?)?;
235
    std::fs::rename(&tmp, &p)?;
236
    Ok(())
237
}
238
239
fn send_batch(batch: &[(String, Vec<u8>)], send: &(dyn Fn(&str, &[u8]) -> Result<()> + Sync), failed: &Mutex<Option<anyhow::Error>>) {
240
    std::thread::scope(|s| {
241
        for part in batch.chunks(batch.len().div_ceil(PARALLEL).max(1)) {
242
            s.spawn(move || {
243
                for (h, b) in part {
244
                    if let Err(e) = send(h, b) {
245
                        *failed.lock().unwrap() = Some(e);
246
                        return;
247
                    }
248
                }
249
            });
250
        }
251
    });
252
}
253
254
/// The home's chunk cache.
255
pub fn chunk_cache(home: &Home) -> PathBuf {
256
    home.root.join("chunks")
257
}
258
259
pub(crate) fn cache_path(cache: &Path, hash: &str) -> PathBuf {
260
    cache.join(&hash[..2]).join(hash)
261
}
262
263
/// A size for people: 991 MiB, 1.2 GiB.
264
pub fn human(bytes: u64) -> String {
265
    if bytes >= 1 << 30 {
266
        format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64)
267
    } else {
268
        format!("{} MiB", bytes >> 20)
269
    }
270
}