OXYGENHUB
# 85275e1ef3b7 oxygenflow / crates / flow / src / workspace.rs
9.6 KiB · Rust · last changed A local flow run of a WASM or syscall job copies the workspace whole 10 days ago source blame history raw
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();
41
                    std::os::unix::fs::symlink(&to, &target).with_context(|| format!("symlink {path}"))?;
42
                } else {
43
                    std::fs::write(&target, &bytes).with_context(|| format!("write {path}"))?;
44
                    if f.mode.exec {
45
                        use std::os::unix::fs::PermissionsExt;
46
                        std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o755))?;
47
                    }
48
                }
49
                files.push((path.clone(), *blake3::hash(&bytes).as_bytes()));
50
            }
51
        }
52
    }
53
    Ok(files)
54
}
55
56
/// Copy a working directory (without `.oxy` and what `.oxyignore` and
57
/// `.gitignore` exclude) under `dir`, for `flow run`.
58
pub fn copy_tree(src: &Path, dir: &Path) -> Result<Files> {
59
    let mut files = Vec::new();
60
    // A file at the top would otherwise find no directory to go in.
61
    std::fs::create_dir_all(dir)?;
62
    let walk = ignore::WalkBuilder::new(src)
63
        .hidden(false)
64
        .git_ignore(true)
65
        .require_git(false)
66
        .add_custom_ignore_filename(".oxyignore")
67
        .filter_entry(|e| e.file_name() != ".oxy" && e.file_name() != ".git")
68
        .build();
69
    for entry in walk {
70
        let entry = entry?;
71
        let rel = entry.path().strip_prefix(src)?;
72
        if rel.as_os_str().is_empty() {
73
            continue;
74
        }
75
        let rel_s = rel.to_string_lossy().replace('\\', "/");
76
        let target = dir.join(rel);
77
        let ft = entry.file_type().context("file type")?;
78
        if ft.is_dir() {
79
            std::fs::create_dir_all(&target)?;
80
        } else if ft.is_symlink() {
81
            let to = std::fs::read_link(entry.path())?;
82
            std::os::unix::fs::symlink(&to, &target)?;
83
            files.push((rel_s, *blake3::hash(to.to_string_lossy().as_bytes()).as_bytes()));
84
        } else if ft.is_file() {
85
            std::fs::copy(entry.path(), &target)?;
86
            files.push((rel_s, *blake3::hash(&std::fs::read(entry.path())?).as_bytes()));
87
        }
88
    }
89
    Ok(files)
90
}
91
92
/// Pack `dir` into an ext4 image whose root belongs to this user, so the
93
/// job (which runs as the owner of `/src`) can write to it.
94
pub fn image(dir: &Path, out: &Path) -> Result<()> {
95
    let used: u64 = ignore::WalkBuilder::new(dir)
96
        .hidden(false)
97
        .ignore(false)
98
        .git_ignore(false)
99
        .build()
100
        .flatten()
101
        .filter_map(|e| e.metadata().ok())
102
        .map(|m| m.len().max(4096))
103
        .sum();
104
    let mib = used * 12 / 10 / (1 << 20) + 512;
105
    let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) };
106
    let status = std::process::Command::new("mkfs.ext4")
107
        .args(["-q", "-F", "-L", "workspace", "-E"])
108
        .arg(format!("root_owner={uid}:{gid}"))
109
        .arg("-d")
110
        .arg(dir)
111
        .arg(out)
112
        .arg(format!("{mib}M"))
113
        .status()
114
        .context("run mkfs.ext4 (e2fsprogs 1.43 or later)")?;
115
    if !status.success() {
116
        bail!("mkfs.ext4 failed for the workspace image");
117
    }
118
    Ok(())
119
}
120
121
/// Give the files of `dir` whose content a cached disk was built from
122
/// the mtime they had then (oxygenflow#52), and describe this checkout's
123
/// sources for the disk to keep: unchanged files are fresh to a build
124
/// tool that judges by time, changed ones newer than anything it built.
125
/// Whole seconds, as the workspace image keeps them. Returns the sources
126
/// and how many files got their time back.
127
pub fn restore_times(dir: &Path, files: &Files, before: Option<&crate::cache::Sources>) -> (crate::cache::Sources, usize) {
128
    let mut out = crate::cache::Sources::new();
129
    let mut restored = 0;
130
    for (path, hash) in files {
131
        let p = dir.join(path);
132
        let Ok(md) = std::fs::symlink_metadata(&p) else { continue };
133
        if !md.is_file() {
134
            continue;
135
        }
136
        let hex = hex::encode(hash);
137
        let kept = before.and_then(|b| b.get(path)).filter(|(h, _)| *h == hex).map(|(_, t)| *t);
138
        let t = match kept {
139
            Some(t) => {
140
                let at = std::time::UNIX_EPOCH + std::time::Duration::from_secs(t.max(0) as u64);
141
                if std::fs::File::options().write(true).open(&p).and_then(|f| f.set_modified(at)).is_err() {
142
                    continue;
143
                }
144
                restored += 1;
145
                t
146
            }
147
            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),
148
        };
149
        out.insert(path.clone(), (hex, t));
150
    }
151
    (out, restored)
152
}
153
154
/// An empty ext4 filesystem of `mib` MiB at `out`, owned by this user like
155
/// the workspace. mkfs.ext4 creates the file sparse, so only what the job
156
/// writes takes space on the runner.
157
pub fn empty_ext4(out: &Path, mib: u32, label: &str) -> Result<()> {
158
    let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) };
159
    let status = std::process::Command::new("mkfs.ext4")
160
        .args(["-q", "-F", "-L", label, "-E"])
161
        .arg(format!("root_owner={uid}:{gid}"))
162
        .arg(out)
163
        .arg(format!("{mib}M"))
164
        .status()
165
        .context("run mkfs.ext4 (e2fsprogs 1.43 or later)")?;
166
    if !status.success() {
167
        bail!("mkfs.ext4 failed for a scratch disk");
168
    }
169
    Ok(())
170
}
171
172
/// Remove `dir` and everything in it, even where a job took away its own
173
/// write or search permission on a directory; links are never followed.
174
pub fn remove_tree(dir: &Path) -> std::io::Result<()> {
175
    match std::fs::remove_dir_all(dir) {
176
        Ok(()) => Ok(()),
177
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
178
        Err(_) => {
179
            open_up(dir);
180
            std::fs::remove_dir_all(dir)
181
        }
182
    }
183
}
184
185
fn open_up(dir: &Path) {
186
    use std::os::unix::fs::PermissionsExt;
187
    let Ok(meta) = std::fs::symlink_metadata(dir) else { return };
188
    if !meta.is_dir() {
189
        return;
190
    }
191
    let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
192
    if let Ok(entries) = std::fs::read_dir(dir) {
193
        for e in entries.flatten() {
194
            open_up(&e.path());
195
        }
196
    }
197
}
198
199
#[cfg(test)]
200
mod tests {
201
    use super::*;
202
    use std::time::UNIX_EPOCH;
203
204
    fn secs(p: &Path) -> i64 {
205
        std::fs::metadata(p).unwrap().modified().unwrap().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64
206
    }
207
208
    /// oxygenflow#52: an unchanged file gets the time it had when the cached
209
    /// disk was built; a changed or new one keeps its checkout's, newer.
210
    #[test]
211
    fn unchanged_sources_get_their_cached_times_back() {
212
        let dir = tempfile::tempdir().unwrap();
213
        for (name, text) in [("same.rs", "a"), ("changed.rs", "b2"), ("new.rs", "c")] {
214
            std::fs::write(dir.path().join(name), text).unwrap();
215
        }
216
        std::os::unix::fs::symlink("same.rs", dir.path().join("link.rs")).unwrap();
217
        let h = |t: &str| *blake3::hash(t.as_bytes()).as_bytes();
218
        let files: Files =
219
            vec![("same.rs".into(), h("a")), ("changed.rs".into(), h("b2")), ("new.rs".into(), h("c")), ("link.rs".into(), h("same.rs"))];
220
        let now = secs(&dir.path().join("same.rs"));
221
        let before: crate::cache::Sources =
222
            [("same.rs".to_string(), (hex::encode(h("a")), 1_000_000)), ("changed.rs".to_string(), (hex::encode(h("b1")), 1_000_000))]
223
                .into();
224
225
        let (sources, restored) = restore_times(dir.path(), &files, Some(&before));
226
        assert_eq!(restored, 1);
227
        assert_eq!(secs(&dir.path().join("same.rs")), 1_000_000, "unchanged: fresh to cargo");
228
        assert!(secs(&dir.path().join("changed.rs")) >= now, "changed: newer than the cached build");
229
        assert_eq!(sources["same.rs"], (hex::encode(h("a")), 1_000_000));
230
        assert_eq!(sources["changed.rs"].0, hex::encode(h("b2")), "kept with its new content");
231
        assert!(sources.contains_key("new.rs") && !sources.contains_key("link.rs"), "files only");
232
233
        // Without a cached build nothing moves, and the sources are listed.
234
        let (again, restored) = restore_times(dir.path(), &files, None);
235
        assert_eq!((restored, again.len()), (0, 3));
236
    }
237
}