OXYGENHUB
◆ v0.3.1 oxygenflow / crates / flow / src / workspace.rs
12.9 KiB · Rust · last changed feat(cache): directories keep their times too; FLOW_HEADS only without OXY_BUILD (refs #52) 22 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
    let walk = ignore::WalkBuilder::new(src)
61
        .hidden(false)
62
        .git_ignore(true)
63
        .require_git(false)
64
        .add_custom_ignore_filename(".oxyignore")
65
        .filter_entry(|e| e.file_name() != ".oxy" && e.file_name() != ".git")
66
        .build();
67
    for entry in walk {
68
        let entry = entry?;
69
        let rel = entry.path().strip_prefix(src)?;
70
        if rel.as_os_str().is_empty() {
71
            continue;
72
        }
73
        let rel_s = rel.to_string_lossy().replace('\\', "/");
74
        let target = dir.join(rel);
75
        let ft = entry.file_type().context("file type")?;
76
        if ft.is_dir() {
77
            std::fs::create_dir_all(&target)?;
78
        } else if ft.is_symlink() {
79
            let to = std::fs::read_link(entry.path())?;
80
            std::os::unix::fs::symlink(&to, &target)?;
81
            files.push((rel_s, *blake3::hash(to.to_string_lossy().as_bytes()).as_bytes()));
82
        } else if ft.is_file() {
83
            std::fs::copy(entry.path(), &target)?;
84
            files.push((rel_s, *blake3::hash(&std::fs::read(entry.path())?).as_bytes()));
85
        }
86
    }
87
    Ok(files)
88
}
89
90
/// Pack `dir` into an ext4 image whose root belongs to this user, so the
91
/// job (which runs as the owner of `/src`) can write to it.
92
pub fn image(dir: &Path, out: &Path) -> Result<()> {
93
    let used: u64 = ignore::WalkBuilder::new(dir)
94
        .hidden(false)
95
        .ignore(false)
96
        .git_ignore(false)
97
        .build()
98
        .flatten()
99
        .filter_map(|e| e.metadata().ok())
100
        .map(|m| m.len().max(4096))
101
        .sum();
102
    let mib = used * 12 / 10 / (1 << 20) + 512;
103
    let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) };
104
    let status = std::process::Command::new("mkfs.ext4")
105
        .args(["-q", "-F", "-L", "workspace", "-E"])
106
        .arg(format!("root_owner={uid}:{gid}"))
107
        .arg("-d")
108
        .arg(dir)
109
        .arg(out)
110
        .arg(format!("{mib}M"))
111
        .status()
112
        .context("run mkfs.ext4 (e2fsprogs 1.43 or later)")?;
113
    if !status.success() {
114
        bail!("mkfs.ext4 failed for the workspace image");
115
    }
116
    Ok(())
117
}
118
119
/// Give the files of `dir` whose content a cached disk was built from
120
/// the mtime they had then (oxygenflow#52), and describe this checkout's
121
/// sources for the disk to keep: unchanged files are fresh to a build
122
/// tool that judges by time, changed ones newer than anything it built.
123
/// Whole seconds, as the workspace image keeps them. Returns the sources
124
/// and how many files got their time back.
125
pub fn restore_times(dir: &Path, files: &Files, before: Option<&crate::cache::Sources>) -> (crate::cache::Sources, usize) {
126
    let mut out = crate::cache::Sources::new();
127
    let mut restored = 0;
128
    for (path, hash) in files {
129
        let p = dir.join(path);
130
        let Ok(md) = std::fs::symlink_metadata(&p) else { continue };
131
        if !md.is_file() {
132
            continue;
133
        }
134
        let hex = hex::encode(hash);
135
        let kept = before.and_then(|b| b.get(path)).filter(|(h, _)| *h == hex).map(|(_, t)| *t);
136
        let t = match kept {
137
            Some(t) => {
138
                let at = std::time::UNIX_EPOCH + std::time::Duration::from_secs(t.max(0) as u64);
139
                if std::fs::File::options().write(true).open(&p).and_then(|f| f.set_modified(at)).is_err() {
140
                    continue;
141
                }
142
                restored += 1;
143
                t
144
            }
145
            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),
146
        };
147
        out.insert(path.clone(), (hex, t));
148
    }
149
    // Directories too, after their files (#52): a build script's
150
    // `rerun-if-changed` on a directory looks at its time as well. A
151
    // directory whose listing is unchanged gets its old time back; one that
152
    // gained or lost an entry keeps its checkout's, so the change shows.
153
    restore_dir_times(dir, Path::new(""), before, &mut out, &mut restored);
154
    (out, restored)
155
}
156
157
/// The key a directory's entry has in the sources: its path and a slash.
158
fn dir_key(rel: &Path) -> String {
159
    format!("{}/", rel.display())
160
}
161
162
fn restore_dir_times(
163
    root: &Path,
164
    rel: &Path,
165
    before: Option<&crate::cache::Sources>,
166
    out: &mut crate::cache::Sources,
167
    restored: &mut usize,
168
) {
169
    let here = root.join(rel);
170
    let Ok(entries) = std::fs::read_dir(&here) else { return };
171
    let mut names: Vec<(String, bool)> = Vec::new();
172
    for e in entries.flatten() {
173
        let is_dir = e.file_type().is_ok_and(|t| t.is_dir());
174
        names.push((e.file_name().to_string_lossy().into_owned(), is_dir));
175
    }
176
    names.sort();
177
    for (name, is_dir) in &names {
178
        if *is_dir {
179
            restore_dir_times(root, &rel.join(name), before, out, restored);
180
        }
181
    }
182
    let mut h = blake3::Hasher::new();
183
    for (name, is_dir) in &names {
184
        h.update(name.as_bytes());
185
        h.update(if *is_dir { b"/\n".as_slice() } else { b"\n".as_slice() });
186
    }
187
    let hex = h.finalize().to_hex().to_string();
188
    let key = dir_key(rel);
189
    let kept = before.and_then(|b| b.get(&key)).filter(|(h, _)| *h == hex).map(|(_, t)| *t);
190
    let t = match kept {
191
        Some(t) => {
192
            let at = std::time::UNIX_EPOCH + std::time::Duration::from_secs(t.max(0) as u64);
193
            if std::fs::File::open(&here).and_then(|f| f.set_modified(at)).is_err() {
194
                return;
195
            }
196
            *restored += 1;
197
            t
198
        }
199
        None => std::fs::metadata(&here)
200
            .ok()
201
            .and_then(|m| m.modified().ok())
202
            .and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok())
203
            .map(|d| d.as_secs() as i64)
204
            .unwrap_or(0),
205
    };
206
    out.insert(key, (hex, t));
207
}
208
209
/// An empty ext4 filesystem of `mib` MiB at `out`, owned by this user like
210
/// the workspace. mkfs.ext4 creates the file sparse, so only what the job
211
/// writes takes space on the runner.
212
pub fn empty_ext4(out: &Path, mib: u32, label: &str) -> Result<()> {
213
    let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) };
214
    let status = std::process::Command::new("mkfs.ext4")
215
        .args(["-q", "-F", "-L", label, "-E"])
216
        .arg(format!("root_owner={uid}:{gid}"))
217
        .arg(out)
218
        .arg(format!("{mib}M"))
219
        .status()
220
        .context("run mkfs.ext4 (e2fsprogs 1.43 or later)")?;
221
    if !status.success() {
222
        bail!("mkfs.ext4 failed for a scratch disk");
223
    }
224
    Ok(())
225
}
226
227
/// Remove `dir` and everything in it, even where a job took away its own
228
/// write or search permission on a directory; links are never followed.
229
pub fn remove_tree(dir: &Path) -> std::io::Result<()> {
230
    match std::fs::remove_dir_all(dir) {
231
        Ok(()) => Ok(()),
232
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
233
        Err(_) => {
234
            open_up(dir);
235
            std::fs::remove_dir_all(dir)
236
        }
237
    }
238
}
239
240
fn open_up(dir: &Path) {
241
    use std::os::unix::fs::PermissionsExt;
242
    let Ok(meta) = std::fs::symlink_metadata(dir) else { return };
243
    if !meta.is_dir() {
244
        return;
245
    }
246
    let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
247
    if let Ok(entries) = std::fs::read_dir(dir) {
248
        for e in entries.flatten() {
249
            open_up(&e.path());
250
        }
251
    }
252
}
253
254
#[cfg(test)]
255
mod tests {
256
    use super::*;
257
    use std::time::UNIX_EPOCH;
258
259
    fn secs(p: &Path) -> i64 {
260
        std::fs::metadata(p).unwrap().modified().unwrap().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64
261
    }
262
263
    /// oxygenflow#52: an unchanged file gets the time it had when the cached
264
    /// disk was built; a changed or new one keeps its checkout's, newer.
265
    #[test]
266
    fn unchanged_sources_get_their_cached_times_back() {
267
        let dir = tempfile::tempdir().unwrap();
268
        for (name, text) in [("same.rs", "a"), ("changed.rs", "b2"), ("new.rs", "c")] {
269
            std::fs::write(dir.path().join(name), text).unwrap();
270
        }
271
        std::os::unix::fs::symlink("same.rs", dir.path().join("link.rs")).unwrap();
272
        let h = |t: &str| *blake3::hash(t.as_bytes()).as_bytes();
273
        let files: Files =
274
            vec![("same.rs".into(), h("a")), ("changed.rs".into(), h("b2")), ("new.rs".into(), h("c")), ("link.rs".into(), h("same.rs"))];
275
        let now = secs(&dir.path().join("same.rs"));
276
        let before: crate::cache::Sources =
277
            [("same.rs".to_string(), (hex::encode(h("a")), 1_000_000)), ("changed.rs".to_string(), (hex::encode(h("b1")), 1_000_000))]
278
                .into();
279
280
        let (sources, restored) = restore_times(dir.path(), &files, Some(&before));
281
        assert_eq!(restored, 1);
282
        assert_eq!(secs(&dir.path().join("same.rs")), 1_000_000, "unchanged: fresh to cargo");
283
        assert!(secs(&dir.path().join("changed.rs")) >= now, "changed: newer than the cached build");
284
        assert_eq!(sources["same.rs"], (hex::encode(h("a")), 1_000_000));
285
        assert_eq!(sources["changed.rs"].0, hex::encode(h("b2")), "kept with its new content");
286
        assert!(sources.contains_key("new.rs") && !sources.contains_key("link.rs"), "files only");
287
288
        // Without a cached build nothing moves, and the sources are listed:
289
        // three files and the directory holding them.
290
        let (again, restored) = restore_times(dir.path(), &files, None);
291
        assert_eq!((restored, again.len()), (0, 4));
292
        assert!(again.contains_key("/"));
293
294
        // A directory whose listing is unchanged gets its time back; one
295
        // that gained an entry keeps its new time, so a build script's
296
        // `rerun-if-changed` on it sees the change.
297
        std::fs::create_dir(dir.path().join("migrations")).unwrap();
298
        std::fs::write(dir.path().join("migrations/0001.sql"), "x").unwrap();
299
        let mut files = files;
300
        files.push(("migrations/0001.sql".into(), h("x")));
301
        let (mut kept, _) = restore_times(dir.path(), &files, None);
302
        kept.get_mut("migrations/").unwrap().1 = 2_000_000;
303
        kept.get_mut("migrations/0001.sql").unwrap().1 = 2_000_000;
304
        let (_, restored) = restore_times(dir.path(), &files, Some(&kept));
305
        assert_eq!(secs(&dir.path().join("migrations")), 2_000_000, "unchanged listing: its old time");
306
        assert!(restored >= 2);
307
        std::fs::write(dir.path().join("migrations/0002.sql"), "y").unwrap();
308
        files.push(("migrations/0002.sql".into(), h("y")));
309
        let (now_sources, _) = restore_times(dir.path(), &files, Some(&kept));
310
        assert!(secs(&dir.path().join("migrations")) > 2_000_000, "a new entry: it looks changed");
311
        assert_ne!(now_sources["migrations/"].0, kept["migrations/"].0);
312
    }
313
}