OXYGENHUB
◆ v0.5.2 oxygenflow / crates / flow / src / workspace.rs
13.0 KiB · Rust · last changed flow builds for Windows, offering the WASM tier 10 days ago source blame history raw
e0918b88 Andy McCall 1
//! A job's workspace: the files of the state being built, written to a
2
//! scratch directory and packed into an ext4 image for the microVM
3
//! (docs/m0.md §2). Returns each file's content hash for the scope hash.
4
5
use anyhow::{bail, Context, Result};
6
use flow_core::Hash;
7
use oxy_core::hash::ChangeHash;
8
use oxy_core::objects::NodeKind;
9
use oxy_core::repo::Repo;
10
use oxy_core::state::FileContent;
11
use std::path::Path;
12
13
pub type Files = Vec<(String, Hash)>;
14
15
/// Write the state `heads` of `repo` under `dir`.
16
pub fn export_state(repo: &Repo, heads: &[ChangeHash], dir: &Path) -> Result<Files> {
17
    let snapshot = repo.load_state(heads).context("load the state")?.materialize();
18
    let mut files = Vec::new();
19
    for (path, f) in &snapshot.files {
20
        if path.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p == ".oxy") {
21
            continue;
22
        }
23
        let target = dir.join(path);
24
        match (&f.kind, &f.content) {
25
            (NodeKind::Dir, _) | (_, FileContent::Dir) => std::fs::create_dir_all(&target)?,
26
            (NodeKind::Subrepo, _) => {}
27
            (kind, content) => {
28
                let bytes = match content {
29
                    FileContent::Text { bytes, .. } => bytes.clone(),
30
                    FileContent::Opaque { blobs } => match blobs.first() {
31
                        Some(b) => repo.read_blob(b)?,
32
                        None => Vec::new(),
33
                    },
34
                    FileContent::Dir => unreachable!(),
35
                };
36
                if let Some(parent) = target.parent() {
37
                    std::fs::create_dir_all(parent)?;
38
                }
39
                if *kind == NodeKind::Symlink {
40
                    let to = String::from_utf8_lossy(&bytes).into_owned();
3554afef Andy McCall ↶ 41
                    crate::portable::symlink(Path::new(&to), &target).with_context(|| format!("symlink {path}"))?;
e0918b88 Andy McCall 42
                } else {
43
                    std::fs::write(&target, &bytes).with_context(|| format!("write {path}"))?;
44
                    if f.mode.exec {
3554afef Andy McCall ↶ 45
                        crate::portable::set_mode(&target, 0o755)?;
e0918b88 Andy McCall 46
                    }
47
                }
48
                files.push((path.clone(), *blake3::hash(&bytes).as_bytes()));
49
            }
50
        }
51
    }
52
    Ok(files)
53
}
54
55
/// Copy a working directory (without `.oxy` and what `.oxyignore` and
56
/// `.gitignore` exclude) under `dir`, for `flow run`.
57
pub fn copy_tree(src: &Path, dir: &Path) -> Result<Files> {
58
    let mut files = Vec::new();
67851a86 Andy McCall ↶ 59
    // A file at the top would otherwise find no directory to go in.
60
    std::fs::create_dir_all(dir)?;
e0918b88 Andy McCall 61
    let walk = ignore::WalkBuilder::new(src)
62
        .hidden(false)
63
        .git_ignore(true)
64
        .require_git(false)
65
        .add_custom_ignore_filename(".oxyignore")
66
        .filter_entry(|e| e.file_name() != ".oxy" && e.file_name() != ".git")
67
        .build();
68
    for entry in walk {
69
        let entry = entry?;
70
        let rel = entry.path().strip_prefix(src)?;
71
        if rel.as_os_str().is_empty() {
72
            continue;
73
        }
74
        let rel_s = rel.to_string_lossy().replace('\\', "/");
75
        let target = dir.join(rel);
76
        let ft = entry.file_type().context("file type")?;
77
        if ft.is_dir() {
78
            std::fs::create_dir_all(&target)?;
79
        } else if ft.is_symlink() {
80
            let to = std::fs::read_link(entry.path())?;
3554afef Andy McCall ↶ 81
            crate::portable::symlink(&to, &target)?;
e0918b88 Andy McCall 82
            files.push((rel_s, *blake3::hash(to.to_string_lossy().as_bytes()).as_bytes()));
83
        } else if ft.is_file() {
84
            std::fs::copy(entry.path(), &target)?;
85
            files.push((rel_s, *blake3::hash(&std::fs::read(entry.path())?).as_bytes()));
86
        }
87
    }
88
    Ok(files)
89
}
90
91
/// Pack `dir` into an ext4 image whose root belongs to this user, so the
92
/// job (which runs as the owner of `/src`) can write to it.
93
pub fn image(dir: &Path, out: &Path) -> Result<()> {
94
    let used: u64 = ignore::WalkBuilder::new(dir)
95
        .hidden(false)
96
        .ignore(false)
97
        .git_ignore(false)
98
        .build()
99
        .flatten()
100
        .filter_map(|e| e.metadata().ok())
101
        .map(|m| m.len().max(4096))
102
        .sum();
103
    let mib = used * 12 / 10 / (1 << 20) + 512;
3554afef Andy McCall ↶ 104
    let (uid, gid) = owner();
e0918b88 Andy McCall 105
    let status = std::process::Command::new("mkfs.ext4")
106
        .args(["-q", "-F", "-L", "workspace", "-E"])
107
        .arg(format!("root_owner={uid}:{gid}"))
108
        .arg("-d")
109
        .arg(dir)
110
        .arg(out)
111
        .arg(format!("{mib}M"))
112
        .status()
113
        .context("run mkfs.ext4 (e2fsprogs 1.43 or later)")?;
114
    if !status.success() {
115
        bail!("mkfs.ext4 failed for the workspace image");
116
    }
117
    Ok(())
118
}
fc10d9e8 Andy McCall ↶ 119
82cf6e91 Andy McCall ↶ 120
/// Give the files of `dir` whose content a cached disk was built from
121
/// the mtime they had then (oxygenflow#52), and describe this checkout's
122
/// sources for the disk to keep: unchanged files are fresh to a build
123
/// tool that judges by time, changed ones newer than anything it built.
124
/// Whole seconds, as the workspace image keeps them. Returns the sources
125
/// and how many files got their time back.
126
pub fn restore_times(dir: &Path, files: &Files, before: Option<&crate::cache::Sources>) -> (crate::cache::Sources, usize) {
127
    let mut out = crate::cache::Sources::new();
128
    let mut restored = 0;
129
    for (path, hash) in files {
130
        let p = dir.join(path);
131
        let Ok(md) = std::fs::symlink_metadata(&p) else { continue };
132
        if !md.is_file() {
133
            continue;
134
        }
135
        let hex = hex::encode(hash);
136
        let kept = before.and_then(|b| b.get(path)).filter(|(h, _)| *h == hex).map(|(_, t)| *t);
137
        let t = match kept {
138
            Some(t) => {
139
                let at = std::time::UNIX_EPOCH + std::time::Duration::from_secs(t.max(0) as u64);
140
                if std::fs::File::options().write(true).open(&p).and_then(|f| f.set_modified(at)).is_err() {
141
                    continue;
142
                }
143
                restored += 1;
144
                t
145
            }
146
            None => md.modified().ok().and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs() as i64).unwrap_or(0),
147
        };
148
        out.insert(path.clone(), (hex, t));
149
    }
de1d7926 Andy McCall ↶ 150
    // Directories too, after their files (#52): a build script's
151
    // `rerun-if-changed` on a directory looks at its time as well. A
152
    // directory whose listing is unchanged gets its old time back; one that
153
    // gained or lost an entry keeps its checkout's, so the change shows.
154
    restore_dir_times(dir, Path::new(""), before, &mut out, &mut restored);
82cf6e91 Andy McCall ↶ 155
    (out, restored)
156
}
157
de1d7926 Andy McCall ↶ 158
/// The key a directory's entry has in the sources: its path and a slash.
159
fn dir_key(rel: &Path) -> String {
160
    format!("{}/", rel.display())
161
}
162
163
fn restore_dir_times(
164
    root: &Path,
165
    rel: &Path,
166
    before: Option<&crate::cache::Sources>,
167
    out: &mut crate::cache::Sources,
168
    restored: &mut usize,
169
) {
170
    let here = root.join(rel);
171
    let Ok(entries) = std::fs::read_dir(&here) else { return };
172
    let mut names: Vec<(String, bool)> = Vec::new();
173
    for e in entries.flatten() {
174
        let is_dir = e.file_type().is_ok_and(|t| t.is_dir());
175
        names.push((e.file_name().to_string_lossy().into_owned(), is_dir));
176
    }
177
    names.sort();
178
    for (name, is_dir) in &names {
179
        if *is_dir {
180
            restore_dir_times(root, &rel.join(name), before, out, restored);
181
        }
182
    }
183
    let mut h = blake3::Hasher::new();
184
    for (name, is_dir) in &names {
185
        h.update(name.as_bytes());
186
        h.update(if *is_dir { b"/\n".as_slice() } else { b"\n".as_slice() });
187
    }
188
    let hex = h.finalize().to_hex().to_string();
189
    let key = dir_key(rel);
190
    let kept = before.and_then(|b| b.get(&key)).filter(|(h, _)| *h == hex).map(|(_, t)| *t);
191
    let t = match kept {
192
        Some(t) => {
193
            let at = std::time::UNIX_EPOCH + std::time::Duration::from_secs(t.max(0) as u64);
194
            if std::fs::File::open(&here).and_then(|f| f.set_modified(at)).is_err() {
195
                return;
196
            }
197
            *restored += 1;
198
            t
199
        }
200
        None => std::fs::metadata(&here)
201
            .ok()
202
            .and_then(|m| m.modified().ok())
203
            .and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok())
204
            .map(|d| d.as_secs() as i64)
205
            .unwrap_or(0),
206
    };
207
    out.insert(key, (hex, t));
208
}
209
fc10d9e8 Andy McCall ↶ 210
/// An empty ext4 filesystem of `mib` MiB at `out`, owned by this user like
211
/// the workspace. mkfs.ext4 creates the file sparse, so only what the job
212
/// writes takes space on the runner.
213
pub fn empty_ext4(out: &Path, mib: u32, label: &str) -> Result<()> {
3554afef Andy McCall ↶ 214
    let (uid, gid) = owner();
fc10d9e8 Andy McCall ↶ 215
    let status = std::process::Command::new("mkfs.ext4")
216
        .args(["-q", "-F", "-L", label, "-E"])
217
        .arg(format!("root_owner={uid}:{gid}"))
218
        .arg(out)
219
        .arg(format!("{mib}M"))
220
        .status()
221
        .context("run mkfs.ext4 (e2fsprogs 1.43 or later)")?;
222
    if !status.success() {
223
        bail!("mkfs.ext4 failed for a scratch disk");
224
    }
225
    Ok(())
226
}
ea56c56e Andy McCall ↶ 227
228
/// Remove `dir` and everything in it, even where a job took away its own
229
/// write or search permission on a directory; links are never followed.
230
pub fn remove_tree(dir: &Path) -> std::io::Result<()> {
231
    match std::fs::remove_dir_all(dir) {
232
        Ok(()) => Ok(()),
233
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
234
        Err(_) => {
235
            open_up(dir);
236
            std::fs::remove_dir_all(dir)
237
        }
238
    }
239
}
240
3554afef Andy McCall ↶ 241
/// The runner's user and group, which own a workspace image's root.
242
fn owner() -> (u32, u32) {
243
    #[cfg(unix)]
244
    {
245
        unsafe { (libc::getuid(), libc::getgid()) }
246
    }
247
    #[cfg(not(unix))]
248
    {
249
        (0, 0)
250
    }
251
}
252
ea56c56e Andy McCall ↶ 253
fn open_up(dir: &Path) {
254
    let Ok(meta) = std::fs::symlink_metadata(dir) else { return };
255
    if !meta.is_dir() {
256
        return;
257
    }
3554afef Andy McCall ↶ 258
    let _ = crate::portable::set_mode(dir, 0o700);
ea56c56e Andy McCall ↶ 259
    if let Ok(entries) = std::fs::read_dir(dir) {
260
        for e in entries.flatten() {
261
            open_up(&e.path());
82cf6e91 Andy McCall ↶ 262
        }
263
    }
264
}
265
266
#[cfg(test)]
267
mod tests {
268
    use super::*;
269
    use std::time::UNIX_EPOCH;
270
271
    fn secs(p: &Path) -> i64 {
272
        std::fs::metadata(p).unwrap().modified().unwrap().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64
273
    }
274
275
    /// oxygenflow#52: an unchanged file gets the time it had when the cached
276
    /// disk was built; a changed or new one keeps its checkout's, newer.
277
    #[test]
278
    fn unchanged_sources_get_their_cached_times_back() {
279
        let dir = tempfile::tempdir().unwrap();
280
        for (name, text) in [("same.rs", "a"), ("changed.rs", "b2"), ("new.rs", "c")] {
281
            std::fs::write(dir.path().join(name), text).unwrap();
ea56c56e Andy McCall ↶ 282
        }
82cf6e91 Andy McCall ↶ 283
        std::os::unix::fs::symlink("same.rs", dir.path().join("link.rs")).unwrap();
284
        let h = |t: &str| *blake3::hash(t.as_bytes()).as_bytes();
285
        let files: Files =
286
            vec![("same.rs".into(), h("a")), ("changed.rs".into(), h("b2")), ("new.rs".into(), h("c")), ("link.rs".into(), h("same.rs"))];
287
        let now = secs(&dir.path().join("same.rs"));
288
        let before: crate::cache::Sources =
289
            [("same.rs".to_string(), (hex::encode(h("a")), 1_000_000)), ("changed.rs".to_string(), (hex::encode(h("b1")), 1_000_000))]
290
                .into();
291
292
        let (sources, restored) = restore_times(dir.path(), &files, Some(&before));
293
        assert_eq!(restored, 1);
294
        assert_eq!(secs(&dir.path().join("same.rs")), 1_000_000, "unchanged: fresh to cargo");
295
        assert!(secs(&dir.path().join("changed.rs")) >= now, "changed: newer than the cached build");
296
        assert_eq!(sources["same.rs"], (hex::encode(h("a")), 1_000_000));
297
        assert_eq!(sources["changed.rs"].0, hex::encode(h("b2")), "kept with its new content");
298
        assert!(sources.contains_key("new.rs") && !sources.contains_key("link.rs"), "files only");
299
de1d7926 Andy McCall ↶ 300
        // Without a cached build nothing moves, and the sources are listed:
301
        // three files and the directory holding them.
82cf6e91 Andy McCall ↶ 302
        let (again, restored) = restore_times(dir.path(), &files, None);
de1d7926 Andy McCall ↶ 303
        assert_eq!((restored, again.len()), (0, 4));
304
        assert!(again.contains_key("/"));
305
306
        // A directory whose listing is unchanged gets its time back; one
307
        // that gained an entry keeps its new time, so a build script's
308
        // `rerun-if-changed` on it sees the change.
309
        std::fs::create_dir(dir.path().join("migrations")).unwrap();
310
        std::fs::write(dir.path().join("migrations/0001.sql"), "x").unwrap();
311
        let mut files = files;
312
        files.push(("migrations/0001.sql".into(), h("x")));
313
        let (mut kept, _) = restore_times(dir.path(), &files, None);
314
        kept.get_mut("migrations/").unwrap().1 = 2_000_000;
315
        kept.get_mut("migrations/0001.sql").unwrap().1 = 2_000_000;
316
        let (_, restored) = restore_times(dir.path(), &files, Some(&kept));
317
        assert_eq!(secs(&dir.path().join("migrations")), 2_000_000, "unchanged listing: its old time");
318
        assert!(restored >= 2);
319
        std::fs::write(dir.path().join("migrations/0002.sql"), "y").unwrap();
320
        files.push(("migrations/0002.sql".into(), h("y")));
321
        let (now_sources, _) = restore_times(dir.path(), &files, Some(&kept));
322
        assert!(secs(&dir.path().join("migrations")) > 2_000_000, "a new entry: it looks changed");
323
        assert_ne!(now_sources["migrations/"].0, kept["migrations/"].0);
ea56c56e Andy McCall ↶ 324
    }
325
}