Skip to main content

schedr_agent/
scan.rs

1//! Scanning a DAG root: the files it holds, and its content hash.
2//!
3//! A root is scanned recursively, following symbolic links (git-sync switches a link to each
4//! new checkout), skipping what `.schedrignore` files exclude (gitignore syntax, in any
5//! directory), `.git` and `__pycache__` directories and `*.pyc` files. Every other file counts
6//! for the content hash, not only `.py` files, since tasks read SQL, configuration and other
7//! files next to their DAG files; only `.py` files mentioning `schedr` are parsed (see
8//! archive/PROJECT.md, DAG code delivery and Code versions and change detection; decision 305).
9
10use std::collections::BTreeMap;
11use std::fmt::Write as _;
12use std::io;
13use std::path::{Component, Path, PathBuf};
14use std::time::SystemTime;
15
16use ignore::WalkBuilder;
17use sha2::{Digest, Sha256};
18
19#[cfg(test)]
20mod tests;
21
22/// The name of ignore files.
23pub const IGNORE_FILE: &str = ".schedrignore";
24
25/// Directories never scanned.
26pub const SKIPPED_DIRS: [&str; 2] = [".git", "__pycache__"];
27
28/// The prefix of content hashes, naming the algorithm.
29pub const HASH_PREFIX: &str = "sha256:";
30
31/// A failure to scan or hash a root.
32#[derive(Debug, thiserror::Error)]
33pub enum ScanError {
34    /// The root's directory can't be resolved.
35    #[error("can't read DAG root {}: {source}", root.display())]
36    Root {
37        /// The root's directory.
38        root: PathBuf,
39        /// The error.
40        source: io::Error,
41    },
42    /// An entry under the root can't be read (often a file removed during the scan).
43    #[error("scanning DAG root {}: {source}", root.display())]
44    Walk {
45        /// The root's directory.
46        root: PathBuf,
47        /// The error.
48        source: ignore::Error,
49    },
50    /// A path under the root isn't valid UTF-8 (paths are sent to the master as text).
51    #[error("{}: the path isn't valid UTF-8", path.display())]
52    NotUtf8 {
53        /// The path.
54        path: PathBuf,
55    },
56    /// A file can't be read while hashing.
57    #[error("reading {}: {source}", path.display())]
58    Read {
59        /// The file.
60        path: PathBuf,
61        /// The error.
62        source: io::Error,
63    },
64    /// The copy of a root's code can't be written (decision 102).
65    #[error("copying DAG code to {}: {source}", path.display())]
66    Copy {
67        /// What was being written.
68        path: PathBuf,
69        /// The error.
70        source: io::Error,
71    },
72}
73
74/// What a file looked like when scanned: enough to notice that it changed.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct Stamp {
77    /// The size in bytes.
78    pub len: u64,
79    /// The modification time, where the filesystem reports one.
80    pub modified: Option<SystemTime>,
81}
82
83/// The files of a root at one moment. Two snapshots are equal when the root resolves to the
84/// same directory and every file has the same path, size and modification time.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct Snapshot {
87    root: PathBuf,
88    files: BTreeMap<String, Stamp>,
89}
90
91impl Snapshot {
92    /// The root's directory, with symbolic links resolved.
93    #[must_use]
94    pub fn root(&self) -> &Path {
95        &self.root
96    }
97
98    /// The files, by path relative to the root with `/` separators, in path order.
99    #[must_use]
100    pub const fn files(&self) -> &BTreeMap<String, Stamp> {
101        &self.files
102    }
103
104    /// The `.py` files, in path order; parse mode imports those [`mentions_schedr`] finds.
105    #[must_use]
106    pub fn python_files(&self) -> Vec<String> {
107        self.files
108            .keys()
109            .filter(|path| Path::new(path).extension().is_some_and(|ext| ext == "py"))
110            .cloned()
111            .collect()
112    }
113}
114
115/// What a `.py` file must contain to be parsed (decision 305).
116pub const DAG_FILE_MARK: &[u8] = b"schedr";
117
118/// Whether `path` contains [`DAG_FILE_MARK`], in its bytes, whatever its encoding. A file that
119/// can't be read counts as mentioning it: the parser then reports why, under its timeout, instead
120/// of its DAGs quietly counting as removed. So does what isn't a regular file (opening a FIFO
121/// would wait for a writer, with no timeout here).
122#[must_use]
123pub fn mentions_schedr(path: &Path) -> bool {
124    use std::io::Read as _;
125    if !path.metadata().is_ok_and(|found| found.is_file()) {
126        return true;
127    }
128    let Ok(mut file) = std::fs::File::open(path) else {
129        return true;
130    };
131    let mut buffer = vec![0; 64 * 1024];
132    // Kept from the last read: the mark may span two.
133    let mut kept = 0;
134    loop {
135        match file.read(&mut buffer[kept..]) {
136            Ok(0) => return false,
137            Ok(read) => {
138                let filled = kept + read;
139                if buffer[..filled]
140                    .windows(DAG_FILE_MARK.len())
141                    .any(|window| window == DAG_FILE_MARK)
142                {
143                    return true;
144                }
145                kept = filled.min(DAG_FILE_MARK.len() - 1);
146                buffer.copy_within(filled - kept..filled, 0);
147            }
148            Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
149            Err(_) => return true,
150        }
151    }
152}
153
154/// `files` (relative to `dir`) split into those to parse and those that don't mention
155/// `schedr` (decision 305).
156#[must_use]
157pub fn split_dag_files(dir: &Path, files: Vec<String>) -> (Vec<String>, Vec<String>) {
158    files
159        .into_iter()
160        .partition(|file| mentions_schedr(&dir.join(file)))
161}
162
163/// Scans a root.
164///
165/// # Errors
166///
167/// [`ScanError`] if the root can't be resolved, an entry can't be read, or a path isn't
168/// UTF-8.
169pub fn scan(root: &Path) -> Result<Snapshot, ScanError> {
170    let resolved = root.canonicalize().map_err(|source| ScanError::Root {
171        root: root.to_owned(),
172        source,
173    })?;
174    let mut walk = WalkBuilder::new(&resolved);
175    walk.standard_filters(false)
176        .follow_links(true)
177        .add_custom_ignore_filename(IGNORE_FILE)
178        .filter_entry(|entry| {
179            let is_dir = entry.file_type().is_some_and(|t| t.is_dir());
180            let name = entry.file_name().to_string_lossy();
181            let skipped_dir = is_dir && SKIPPED_DIRS.contains(&name.as_ref());
182            let bytecode = Path::new(name.as_ref())
183                .extension()
184                .is_some_and(|ext| ext == "pyc");
185            !skipped_dir && !bytecode
186        });
187    let mut files = BTreeMap::new();
188    for entry in walk.build() {
189        let entry = entry.map_err(|source| ScanError::Walk {
190            root: resolved.clone(),
191            source,
192        })?;
193        if !entry.file_type().is_some_and(|t| t.is_file()) {
194            continue;
195        }
196        let metadata = entry.metadata().map_err(|source| ScanError::Walk {
197            root: resolved.clone(),
198            source,
199        })?;
200        let relative = relative_path(&resolved, entry.path())?;
201        let stamp = Stamp {
202            len: metadata.len(),
203            modified: metadata.modified().ok(),
204        };
205        files.insert(relative, stamp);
206    }
207    Ok(Snapshot {
208        root: resolved,
209        files,
210    })
211}
212
213/// The content hash of a snapshot's files: `sha256:` and the hex digest of each file's path,
214/// length and bytes, in path order. It depends only on the files' paths and contents, so every
215/// worker with the same code gets the same hash.
216///
217/// # Errors
218///
219/// [`ScanError::Read`] if a file can't be read (e.g. it was removed since the scan).
220pub fn content_hash(snapshot: &Snapshot) -> Result<String, ScanError> {
221    let mut hasher = Sha256::new();
222    for path in snapshot.files.keys() {
223        let full = snapshot.root.join(path);
224        hash_file(&mut hasher, path, &full)
225            .map_err(|source| ScanError::Read { path: full, source })?;
226    }
227    Ok(hex_hash(hasher))
228}
229
230/// A root's code, copied by [`capture`]: its content hash and the read-only copy.
231#[derive(Debug, Clone, PartialEq, Eq)]
232pub struct Captured {
233    /// The content hash of the copied bytes.
234    pub hash: String,
235    /// The copy: `<store>/<hash>`, the hash's `:` a `-`.
236    pub dir: PathBuf,
237    /// Whether this capture made the copy (else it was in `store` already, perhaps in use).
238    pub fresh: bool,
239}
240
241/// Copies a snapshot's files into `store` and hashes the bytes copied (decision 102): parse
242/// jobs and tasks import from the copy, so the code that runs is the code hashed, whatever
243/// happens to the root afterwards (git-sync deleting a checkout, an edit in place). A
244/// followed link is copied as its target's contents; the copy is read-only (executable bits
245/// kept), so no task changes another's code by accident. The hash is the same as
246/// [`content_hash`]'s.
247///
248/// The root is hashed first: a copy already in `store` for that hash is used as it is, and
249/// nothing is written. A copy is complete whenever it has its hash's name: it is written
250/// under a temporary name and renamed into place, and [`remove_capture`] renames it away
251/// before deleting it.
252///
253/// # Errors
254///
255/// [`ScanError::Read`] if a file can't be read, [`ScanError::Copy`] if the copy can't be
256/// written.
257pub fn capture(snapshot: &Snapshot, store: &Path) -> Result<Captured, ScanError> {
258    use std::os::unix::fs::PermissionsExt;
259    let copy_error = |path: &Path| {
260        let path = path.to_path_buf();
261        move |source| ScanError::Copy { path, source }
262    };
263    let hash = content_hash(snapshot)?;
264    let dir = store.join(hash.replace(':', "-"));
265    if dir.is_dir() {
266        // Already copied (the same code again, e.g. a git-sync commit outside this root).
267        return Ok(Captured {
268            hash,
269            dir,
270            fresh: false,
271        });
272    }
273    std::fs::create_dir_all(store).map_err(copy_error(store))?;
274    let partial = Partial::new(store).map_err(copy_error(store))?;
275    let mut hasher = Sha256::new();
276    for path in snapshot.files.keys() {
277        let full = snapshot.root.join(path);
278        let read_error = |source| ScanError::Read {
279            path: full.clone(),
280            source,
281        };
282        let mut source = std::fs::File::open(&full).map_err(read_error)?;
283        let mode = source.metadata().map_err(read_error)?.permissions().mode();
284        let target = partial.path().join(path);
285        if let Some(parent) = target.parent() {
286            std::fs::create_dir_all(parent).map_err(copy_error(parent))?;
287        }
288        // Streamed, never whole in memory (B63); a read error is the root's, a write
289        // error the copy's.
290        let mut copy = std::fs::File::create(&target).map_err(copy_error(&target))?;
291        let mut buffer = vec![0; COPY_BUFFER];
292        loop {
293            let read = io::Read::read(&mut source, &mut buffer).map_err(read_error)?;
294            if read == 0 {
295                break;
296            }
297            io::Write::write_all(&mut copy, &buffer[..read]).map_err(copy_error(&target))?;
298        }
299        drop(copy);
300        std::fs::set_permissions(&target, std::fs::Permissions::from_mode(mode & 0o555))
301            .map_err(copy_error(&target))?;
302        // The copy's bytes: nothing changes them now.
303        hash_file(&mut hasher, path, &target).map_err(copy_error(&target))?;
304    }
305    // What was copied: the files may have changed since they were hashed above.
306    let hash = hex_hash(hasher);
307    let dir = store.join(hash.replace(':', "-"));
308    if dir.is_dir() {
309        return Ok(Captured {
310            hash,
311            dir,
312            fresh: false,
313        });
314    }
315    set_dirs_read_only(partial.path()).map_err(copy_error(partial.path()))?;
316    // macOS renames a directory only with write permission on it (its `..` changes; Linux
317    // doesn't ask): the top one is made read-only once in place.
318    std::fs::set_permissions(partial.path(), std::fs::Permissions::from_mode(0o755))
319        .map_err(copy_error(partial.path()))?;
320    std::fs::rename(partial.path(), &dir).map_err(copy_error(&dir))?;
321    partial.kept();
322    std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555))
323        .map_err(copy_error(&dir))?;
324    Ok(Captured {
325        hash,
326        dir,
327        fresh: true,
328    })
329}
330
331/// A new temporary name in `store`: `.<kind>-<pid>-<n>`. (A leftover of a killed agent is
332/// removed with the other copies nothing uses.)
333fn temporary(store: &Path, kind: &str) -> PathBuf {
334    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
335    let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
336    store.join(format!(".{kind}-{}-{n}", std::process::id()))
337}
338
339/// A copy being written, `<store>/.capture-<pid>-<n>`: removed when dropped unless kept (a
340/// failed or duplicate capture leaves nothing behind).
341struct Partial(Option<PathBuf>);
342
343impl Partial {
344    fn new(store: &Path) -> io::Result<Self> {
345        let path = temporary(store, "capture");
346        std::fs::create_dir(&path)?;
347        Ok(Self(Some(path)))
348    }
349
350    fn path(&self) -> &Path {
351        self.0.as_deref().unwrap_or(Path::new(""))
352    }
353
354    /// Renamed into place: nothing left to remove.
355    fn kept(mut self) {
356        self.0 = None;
357    }
358}
359
360impl Drop for Partial {
361    fn drop(&mut self) {
362        if let Some(path) = &self.0 {
363            let _ = remove_capture(path);
364        }
365    }
366}
367
368/// Makes every directory under (and including) `dir` read-only: no file added or removed.
369fn set_dirs_read_only(dir: &Path) -> io::Result<()> {
370    use std::os::unix::fs::PermissionsExt;
371    for entry in std::fs::read_dir(dir)? {
372        let entry = entry?;
373        if entry.file_type()?.is_dir() {
374            set_dirs_read_only(&entry.path())?;
375        }
376    }
377    std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o555))
378}
379
380/// Removes a folder that may hold read-only copies of code (a local run's, B181).
381///
382/// # Errors
383///
384/// The I/O error of making it writable or of removing it.
385pub fn remove_tree(dir: &Path) -> io::Result<()> {
386    use std::os::unix::fs::PermissionsExt;
387    fn writable(dir: &Path) -> io::Result<()> {
388        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755))?;
389        for entry in std::fs::read_dir(dir)? {
390            let entry = entry?;
391            if entry.file_type()?.is_dir() {
392                writable(&entry.path())?;
393            }
394        }
395        Ok(())
396    }
397    writable(dir)?;
398    std::fs::remove_dir_all(dir)
399}
400
401/// Removes a copy made by [`capture`], read-only as it is: first renamed to a temporary name,
402/// so a removal cut short never leaves a partial copy under its hash's name (which a later
403/// capture of that hash would use as it is).
404///
405/// # Errors
406///
407/// The I/O error of making it writable again or of removing it.
408pub fn remove_capture(dir: &Path) -> io::Result<()> {
409    use std::os::unix::fs::PermissionsExt;
410    fn writable(dir: &Path) -> io::Result<()> {
411        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755))?;
412        for entry in std::fs::read_dir(dir)? {
413            let entry = entry?;
414            if entry.file_type()?.is_dir() {
415                writable(&entry.path())?;
416            }
417        }
418        Ok(())
419    }
420    let temporary_already = dir
421        .file_name()
422        .is_some_and(|name| name.to_string_lossy().starts_with('.'));
423    let doomed = match dir.parent() {
424        Some(store) if !temporary_already => {
425            let doomed = temporary(store, "removing");
426            // Writable first: macOS renames a directory only then (see `capture`).
427            std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755))?;
428            std::fs::rename(dir, &doomed)?;
429            doomed
430        }
431        _ => dir.to_path_buf(),
432    };
433    writable(&doomed)?;
434    std::fs::remove_dir_all(&doomed)
435}
436
437/// The buffer a file is read through when hashed or copied: a file is never read whole
438/// (B63), however big.
439const COPY_BUFFER: usize = 64 << 10;
440
441/// Adds file `full`, at `path` in its root, to a content hash: its path, a NUL, its length
442/// and its bytes, read through a buffer. Its length is its size when opened; a file whose
443/// size changes while it is read is an error (it was being written: the scan is retried).
444fn hash_file(hasher: &mut Sha256, path: &str, full: &Path) -> io::Result<()> {
445    let mut file = std::fs::File::open(full)?;
446    let size = file.metadata()?.len();
447    hasher.update(path.as_bytes());
448    hasher.update([0]);
449    hasher.update(size.to_be_bytes());
450    let mut buffer = vec![0; COPY_BUFFER];
451    let mut read_total = 0;
452    loop {
453        let read = io::Read::read(&mut file, &mut buffer)?;
454        if read == 0 {
455            break;
456        }
457        read_total += read as u64;
458        if read_total > size {
459            break;
460        }
461        hasher.update(&buffer[..read]);
462    }
463    if read_total != size {
464        return Err(io::Error::other(format!(
465            "its size changed while it was read ({size} bytes, then {read_total})"
466        )));
467    }
468    Ok(())
469}
470
471/// `sha256:` and the hex digest.
472fn hex_hash(hasher: Sha256) -> String {
473    let digest = hasher.finalize();
474    let mut hash = String::from(HASH_PREFIX);
475    for byte in digest {
476        let _ = write!(hash, "{byte:02x}");
477    }
478    hash
479}
480
481fn relative_path(root: &Path, path: &Path) -> Result<String, ScanError> {
482    let relative = path.strip_prefix(root).unwrap_or(path);
483    let mut parts = Vec::new();
484    for component in relative.components() {
485        if let Component::Normal(part) = component {
486            let part = part.to_str().ok_or_else(|| ScanError::NotUtf8 {
487                path: path.to_owned(),
488            })?;
489            parts.push(part);
490        }
491    }
492    Ok(parts.join("/"))
493}