OXYGENHUB
# 67851a868a3b oxygenflow / crates / flow / src / checkpoint.rs
10.0 KiB · Rust · last changed Checkpoints: a handed-back job resumes (refs #77) 10 days ago source blame history raw
1
//! Checkpoints (oxygenflow#77, docs/handover.md §7): the directories a job
2
//! declares with `checkpoint "/src/…"`, saved when its runner hands it back
3
//! and restored before the next attempt runs the same exec, so a tool that
4
//! skips finished work (cargo, make) carries on where it stopped.
5
//!
6
//! The format is the runner's own, so CI builds need no new crate: a magic
7
//! line, then entries (a kind byte, the path under /src, mode, modification
8
//! time and, for a file, its bytes). Files keep their times, since cargo's
9
//! fingerprints read them. Links are left out. Unpacking accepts only paths
10
//! under the job's own checkpoints, without `.` or `..`.
11
12
use anyhow::{bail, Context, Result};
13
use flow_core::pipeline::{Job, MountSource};
14
use std::path::{Path, PathBuf};
15
use std::time::{Duration, SystemTime, UNIX_EPOCH};
16
17
/// At most this much is saved: the hub keeps it as it keeps an artifact.
18
pub const MAX_BYTES: usize = 512 << 20;
19
20
const MAGIC: &[u8] = b"OXYFLOW-CHECKPOINT 1\n";
21
const DIR: u8 = 0;
22
const FILE: u8 = 1;
23
24
/// What was saved or restored.
25
#[derive(Debug, Default, PartialEq, Eq)]
26
pub struct Counts {
27
    pub files: usize,
28
    pub dirs: usize,
29
    pub bytes: u64,
30
}
31
32
/// Where checkpoint `path` (under /src) is on this host, for a job of a
33
/// directory tier (WASM, syscall): in a disk mount's directory when a mount
34
/// holds it, else in the job's tree. `None` for one under a tmpfs, which
35
/// the syscall tier keeps in memory.
36
pub fn host_dir(path: &str, job: &Job, tree: &Path, scratch: &Path, wasm: bool) -> Option<PathBuf> {
37
    let under = |t: &str| path == t || path.starts_with(&format!("{}/", t.trim_end_matches('/')));
38
    let mut disks = 0;
39
    let mut best: Option<(usize, PathBuf)> = None;
40
    for (i, m) in job.mounts.iter().enumerate() {
41
        let dir = match m.source {
42
            MountSource::Disk => {
43
                disks += 1;
44
                Some(crate::syscall::disk_dir(scratch, disks - 1))
45
            }
46
            MountSource::Tmpfs if wasm => Some(scratch.join(format!("tmpfs-{i}"))),
47
            MountSource::Tmpfs => None,
48
        };
49
        if under(&m.target) && best.as_ref().is_none_or(|(len, _)| m.target.len() > *len) {
50
            let rest = path[m.target.trim_end_matches('/').len()..].trim_start_matches('/');
51
            best = Some((m.target.len(), dir.map(|d| d.join(rest)).unwrap_or_default()));
52
        }
53
    }
54
    match best {
55
        Some((_, d)) if d.as_os_str().is_empty() => None,
56
        Some((_, d)) => Some(d),
57
        None => Some(tree.join(path.trim_start_matches("/src").trim_start_matches('/'))),
58
    }
59
}
60
61
/// Pack `dirs` (each a checkpoint path and where it is on this host).
62
pub fn pack(dirs: &[(String, PathBuf)]) -> Result<(Vec<u8>, Counts)> {
63
    let mut out = MAGIC.to_vec();
64
    let mut n = Counts::default();
65
    for (path, host) in dirs {
66
        if !host.is_dir() {
67
            continue;
68
        }
69
        let mut stack = vec![(host.clone(), path.trim_end_matches('/').to_string())];
70
        while let Some((at, name)) = stack.pop() {
71
            let meta = std::fs::symlink_metadata(&at)?;
72
            if meta.is_dir() {
73
                entry(&mut out, DIR, &name, &meta, &[]);
74
                n.dirs += 1;
75
                let mut children: Vec<_> = std::fs::read_dir(&at)?.collect::<std::io::Result<_>>()?;
76
                children.sort_by_key(|e| e.file_name());
77
                for c in children.into_iter().rev() {
78
                    let Some(child) = c.file_name().to_str().map(String::from) else { continue };
79
                    stack.push((c.path(), format!("{name}/{child}")));
80
                }
81
            } else if meta.is_file() {
82
                let bytes = std::fs::read(&at).with_context(|| format!("read {}", at.display()))?;
83
                n.files += 1;
84
                n.bytes += bytes.len() as u64;
85
                entry(&mut out, FILE, &name, &meta, &bytes);
86
            }
87
            if out.len() > MAX_BYTES {
88
                bail!("the checkpoint is over {} MiB", MAX_BYTES >> 20);
89
            }
90
        }
91
    }
92
    Ok((out, n))
93
}
94
95
fn entry(out: &mut Vec<u8>, kind: u8, path: &str, meta: &std::fs::Metadata, bytes: &[u8]) {
96
    use std::os::unix::fs::PermissionsExt;
97
    let since = meta.modified().ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok()).unwrap_or_default();
98
    out.push(kind);
99
    out.extend((path.len() as u32).to_le_bytes());
100
    out.extend(path.as_bytes());
101
    out.extend(meta.permissions().mode().to_le_bytes());
102
    out.extend(since.as_secs().to_le_bytes());
103
    out.extend(since.subsec_nanos().to_le_bytes());
104
    out.extend((bytes.len() as u64).to_le_bytes());
105
    out.extend(bytes);
106
}
107
108
/// Restore a checkpoint: each entry at `place(checkpoint)` joined with the
109
/// rest of its path, for the job's own `checkpoints` only.
110
pub fn unpack(bytes: &[u8], checkpoints: &[String], place: impl Fn(&str) -> Option<PathBuf>) -> Result<Counts> {
111
    use std::os::unix::fs::PermissionsExt;
112
    let Some(mut rest) = bytes.strip_prefix(MAGIC) else { bail!("not a checkpoint") };
113
    let mut n = Counts::default();
114
    let take = |rest: &mut &[u8], k: usize| -> Result<Vec<u8>> {
115
        if rest.len() < k {
116
            bail!("the checkpoint is cut short");
117
        }
118
        let (a, b) = rest.split_at(k);
119
        *rest = b;
120
        Ok(a.to_vec())
121
    };
122
    while !rest.is_empty() {
123
        let kind = take(&mut rest, 1)?[0];
124
        let len = u32::from_le_bytes(take(&mut rest, 4)?.try_into().unwrap()) as usize;
125
        let path = String::from_utf8(take(&mut rest, len)?).context("a path that is not UTF-8")?;
126
        let mode = u32::from_le_bytes(take(&mut rest, 4)?.try_into().unwrap());
127
        let secs = u64::from_le_bytes(take(&mut rest, 8)?.try_into().unwrap());
128
        let nanos = u32::from_le_bytes(take(&mut rest, 4)?.try_into().unwrap());
129
        let size = u64::from_le_bytes(take(&mut rest, 8)?.try_into().unwrap()) as usize;
130
        let data = take(&mut rest, size)?;
131
        // Under one of the job's checkpoints, without . or .. on the way.
132
        let Some(root) = checkpoints.iter().map(|c| c.trim_end_matches('/')).find(|c| path == *c || path.starts_with(&format!("{c}/")))
133
        else {
134
            bail!("{path} is not under the job's checkpoints");
135
        };
136
        let below = path[root.len()..].trim_start_matches('/');
137
        if below.split('/').any(|p| p == "." || p == ".." || (p.is_empty() && !below.is_empty())) {
138
            bail!("{path}: . or .. in a checkpoint path");
139
        }
140
        let Some(base) = place(root) else { continue };
141
        let at = if below.is_empty() { base } else { base.join(below) };
142
        match kind {
143
            DIR => {
144
                std::fs::create_dir_all(&at)?;
145
                n.dirs += 1;
146
            }
147
            FILE => {
148
                if let Some(parent) = at.parent() {
149
                    std::fs::create_dir_all(parent)?;
150
                }
151
                // Never through a link already there.
152
                if std::fs::symlink_metadata(&at).is_ok_and(|m| !m.is_file()) {
153
                    bail!("{path}: something other than a file is in the way");
154
                }
155
                std::fs::write(&at, &data)?;
156
                let f = std::fs::File::options().write(true).open(&at)?;
157
                f.set_permissions(std::fs::Permissions::from_mode(mode & 0o777))?;
158
                f.set_modified(SystemTime::UNIX_EPOCH + Duration::new(secs, nanos))?;
159
                n.files += 1;
160
                n.bytes += data.len() as u64;
161
            }
162
            other => bail!("{path}: unknown entry kind {other}"),
163
        }
164
    }
165
    Ok(n)
166
}
167
168
#[cfg(test)]
169
mod tests {
170
    use super::*;
171
172
    #[test]
173
    fn a_checkpoint_comes_back_with_its_times_and_only_where_it_belongs() {
174
        let from = tempfile::tempdir().unwrap();
175
        let target = from.path().join("target");
176
        std::fs::create_dir_all(target.join("debug/deps")).unwrap();
177
        std::fs::write(target.join("debug/deps/libx.rlib"), b"built").unwrap();
178
        std::fs::write(target.join("debug/.fingerprint"), b"fp").unwrap();
179
        let old = SystemTime::UNIX_EPOCH + Duration::new(1_700_000_000, 123_000_000);
180
        std::fs::File::options().write(true).open(target.join("debug/deps/libx.rlib")).unwrap().set_modified(old).unwrap();
181
        let (bytes, n) = pack(&[("/src/target".into(), target.clone())]).unwrap();
182
        assert_eq!((n.files, n.dirs, n.bytes), (2, 3, 7));
183
184
        let to = tempfile::tempdir().unwrap();
185
        let place = |root: &str| (root == "/src/target").then(|| to.path().join("t"));
186
        let back = unpack(&bytes, &["/src/target".into()], place).unwrap();
187
        assert_eq!(back, n);
188
        let restored = to.path().join("t/debug/deps/libx.rlib");
189
        assert_eq!(std::fs::read(&restored).unwrap(), b"built");
190
        assert_eq!(std::fs::metadata(&restored).unwrap().modified().unwrap(), old, "cargo reads the times");
191
192
        // Not the job's checkpoint, or a path that climbs out: refused.
193
        assert!(unpack(&bytes, &["/src/other".into()], place).is_err());
194
        let mut evil = MAGIC.to_vec();
195
        let meta = std::fs::metadata(target.join("debug/.fingerprint")).unwrap();
196
        entry(&mut evil, FILE, "/src/target/../escape", &meta, b"x");
197
        assert!(unpack(&evil, &["/src/target".into()], place).is_err());
198
        assert!(!to.path().join("escape").exists());
199
        assert!(unpack(b"junk", &["/src/target".into()], place).is_err());
200
    }
201
202
    #[test]
203
    fn a_checkpoint_under_a_disk_mount_is_in_the_mount_s_directory() {
204
        let p = flow_core::Pipeline::parse(
205
            "schema-version 1\nsandbox \"w\" {\n    runtime \"wasm\"\n}\njob \"j\" {\n    sandbox \"w\"\n    mount {\n        source \"ephemeral://disk\"\n        target \"/src/target\"\n        size \"1GiB\"\n    }\n    checkpoint \"/src/target\" \"/src/state\"\n    exec \"x.wasm\"\n}\n",
206
        )
207
        .unwrap();
208
        let job = &p.jobs["j"];
209
        assert_eq!(job.checkpoints, ["/src/state", "/src/target"]);
210
        let (tree, scratch) = (Path::new("/w/tree"), Path::new("/w"));
211
        assert_eq!(host_dir("/src/target", job, tree, scratch, true), Some(crate::syscall::disk_dir(scratch, 0)));
212
        assert_eq!(host_dir("/src/state", job, tree, scratch, true), Some(PathBuf::from("/w/tree/state")));
213
    }
214
}