Skip to content
Open
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/mockci/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ publish = false

[dependencies]
anyhow.workspace = true
base64 = "0.22.1"
globset = "0.4.22"
hex = "0.4.3"
rusqlite = { version = "0.43.0", features = ["bundled"] }
Expand Down
49 changes: 34 additions & 15 deletions crates/mockci/src/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ fn checkout(ctx: &JobContext) -> Result<ActionResult> {
)?;
for (destination, source) in &ctx.sim.files {
let target = ctx.workspace.join(destination);
copy_tree(source, &target)?;
copy_tree(source, &target, &ctx.workspace)?;
make_executable(&target)?;
}
Ok(ActionResult::ok(format!("checked out {}", ctx.event.sha())))
Expand Down Expand Up @@ -208,29 +208,32 @@ fn upload(with: &BTreeMap<String, String>, ctx: &JobContext) -> Result<ActionRes
}
let destination = ctx.artifact_dir(name);
if source.is_file() {
copy_tree(
&source,
&destination.join(
source
.file_name()
.context("artifact path has no file name")?,
),
)?;
let name = source
.file_name()
.context("artifact path has no file name")?;
copy_followed(&source, &destination.join(name))?;
} else {
let include_hidden = with
.get("include-hidden-files")
.is_some_and(|v| v == "true");
for entry in walkdir::WalkDir::new(&source)
// upload-artifact globs with `followSymbolicLinks: true` and `omitBrokenSymbolicLinks:
// true`: a link uploads what it points to, and a broken one is left out.
let walk = walkdir::WalkDir::new(&source)
.follow_links(true)
.into_iter()
.filter_entry(|entry| {
include_hidden
|| entry.depth() == 0
|| !entry.file_name().to_string_lossy().starts_with('.')
})
{
let entry = entry?;
});
for entry in walk {
let entry = match entry {
Ok(entry) => entry,
Err(error) if error.path().is_some_and(is_broken_link) => continue,
Err(error) => return Err(error.into()),
};
if entry.file_type().is_file() {
copy_tree(
copy_followed(
entry.path(),
&destination.join(entry.path().strip_prefix(&source)?),
)?;
Expand All @@ -255,11 +258,27 @@ fn download(with: &BTreeMap<String, String>, ctx: &JobContext) -> Result<ActionR
}
let source = ctx.artifact_dir(name);
if source.exists() {
copy_tree(&source, &target)?;
copy_tree(&source, &target, &ctx.workspace)?;
}
Ok(ActionResult::ok(format!("downloaded artifact {name}")))
}

/// Copies a file's contents, following a symlink to it, as an artifact upload stores it.
fn copy_followed(source: &Path, destination: &Path) -> Result<()> {
if let Some(parent) = destination.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::copy(source, destination)
.with_context(|| format!("copying {} to {}", source.display(), destination.display()))?;
Ok(())
}

fn is_broken_link(path: &Path) -> bool {
path.symlink_metadata()
.is_ok_and(|m| m.file_type().is_symlink())
&& !path.exists()
}

fn make_executable(path: &Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
if path.is_file() {
Expand Down
79 changes: 68 additions & 11 deletions crates/mockci/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl Cache<'_> {
for (index, path) in paths.iter().enumerate() {
let stored = self.blob_path(entry.id, index);
if stored.exists() {
copy_tree(&stored, &workspace.join(path))?;
copy_tree(&stored, &workspace.join(path), workspace)?;
}
}
let exact = entry.key == key;
Expand Down Expand Up @@ -131,7 +131,7 @@ impl Cache<'_> {
for (index, path) in paths.iter().enumerate() {
let source = workspace.join(path);
if source.exists() {
copy_tree(&source, &self.blob_path(id, index))?;
copy_tree(&source, &self.blob_path(id, index), self.blobs)?;
}
}
self.record("save", key, None, Some(scope), "saved")
Expand Down Expand Up @@ -162,25 +162,82 @@ impl Cache<'_> {
}
}

/// Copies a file or a directory tree, replacing files that exist at the destination.
pub fn copy_tree(source: &Path, destination: &Path) -> Result<()> {
if source.is_file() {
/// Copies a file or a directory tree to `destination`, which must stay inside `root` (a job's
/// workspace or directory, or the cache's own store), replacing files that exist there.
/// Symlinks are copied as symlinks, never followed, as tar does for caches. Nothing is written
/// through a symlink: a symlink at the destination is replaced, and the destination's nearest
/// existing ancestor, and each entry's parent, must resolve inside `root`.
pub fn copy_tree(source: &Path, destination: &Path, root: &Path) -> Result<()> {
let metadata = std::fs::symlink_metadata(source)
.with_context(|| format!("reading {}", source.display()))?;
std::fs::create_dir_all(root)?;
let root = root
.canonicalize()
.with_context(|| format!("resolving {}", root.display()))?;
if destination
.symlink_metadata()
.is_ok_and(|m| m.file_type().is_symlink())
{
std::fs::remove_file(destination)?;
}
let inside = |path: &Path| -> Result<()> {
let existing = path
.ancestors()
.find(|ancestor| ancestor.symlink_metadata().is_ok())
.context("a path with no existing ancestor")?;
if !existing.canonicalize()?.starts_with(&root) {
bail!(
"writing {} would go through a symlink to outside {}",
path.display(),
root.display()
);
}
Ok(())
};
inside(destination)?;
if !metadata.is_dir() {
if let Some(parent) = destination.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::copy(source, destination).with_context(|| {
format!("copying {} to {}", source.display(), destination.display())
})?;
return Ok(());
return copy_entry(source, destination, metadata.file_type().is_symlink());
}
for entry in walkdir::WalkDir::new(source) {
std::fs::create_dir_all(destination)?;
// Directories come before their contents, so each entry's parent exists by the time it's
// copied, and is checked first.
for entry in walkdir::WalkDir::new(source).min_depth(1) {
let entry = entry?;
let target = destination.join(entry.path().strip_prefix(source)?);
inside(target.parent().context("a copied entry has a parent")?)?;
if entry.file_type().is_dir() {
if target
.symlink_metadata()
.is_ok_and(|m| m.file_type().is_symlink())
{
std::fs::remove_file(&target)?;
}
std::fs::create_dir_all(&target)?;
} else {
copy_tree(entry.path(), &target)?;
copy_entry(entry.path(), &target, entry.file_type().is_symlink())?;
}
}
Ok(())
}

/// Copies one file or symlink, replacing whatever file or symlink is at `target` rather than
/// writing through it.
fn copy_entry(source: &Path, target: &Path, is_symlink: bool) -> Result<()> {
if let Ok(existing) = target.symlink_metadata()
&& !existing.is_dir()
{
std::fs::remove_file(target)?;
}
if is_symlink {
let link = std::fs::read_link(source)?;
std::os::unix::fs::symlink(&link, target)
.with_context(|| format!("linking {} to {}", target.display(), link.display()))?;
} else {
std::fs::copy(source, target)
.with_context(|| format!("copying {} to {}", source.display(), target.display()))?;
}
Ok(())
}
153 changes: 153 additions & 0 deletions crates/mockci/src/circleci/cache.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
//! A model of CircleCI's cache, as `restore_cache` and `save_cache` see it:
//!
//! - One scope for the whole project: every branch, and pull requests from the same repository,
//! read and write the same caches.
//! - `restore_cache` tries each key in order. Each key matches as a prefix, and the most
//! recently saved match wins.
//! - Caches are immutable: saving a key that exists does nothing.
//! - Caches expire 15 days after they're saved, however often they're read.
//! - A cache restores its files to the paths they were saved from.

use super::paths::JobDirs;
use super::template;
use crate::cache::copy_tree;
use crate::db::{CacheEvent, Db};
use anyhow::{Context, Result, bail};
use std::path::{Path, PathBuf};

/// The `scope` CircleCI entries have in the shared table, apart from GitHub's refs.
pub const SCOPE: &str = "circleci-project";
const VERSION: &str = "circleci";
pub const EXPIRY_SECONDS: i64 = 15 * 24 * 60 * 60;

pub struct Cache<'a> {
pub db: &'a Db,
pub blobs: &'a Path,
pub job_row: i64,
pub now: i64,
pub dirs: JobDirs<'a>,
/// When the job started, on the host's clock: a host `/tmp` path changed since then was
/// written by one of its steps.
pub started: std::time::SystemTime,
}

impl Cache<'_> {
/// Restores the newest cache matching the first key that matches anything. Returns the
/// key it restored, if any.
pub fn restore(&self, keys: &[String]) -> Result<Option<String>> {
self.db
.expire_cache_entries(SCOPE, self.now, EXPIRY_SECONDS)?;
for key in keys {
let Some(entry) = self.db.find_prefix_cache_entry(key, VERSION, SCOPE)? else {
continue;
};
let dir = self.blob_dir(entry.id);
let manifest = std::fs::read_to_string(dir.join("paths"))?;
for (index, path) in manifest.lines().enumerate() {
let stored = dir.join(index.to_string());
if stored.exists() {
let target = resolve_path(path, &self.dirs)?;
let root = if target.starts_with(self.dirs.tmp) {
self.dirs.tmp
} else {
self.dirs.home
};
copy_tree(&stored, &target, root)?;
}
}
self.record("restore", key, Some(&entry.key), "hit")?;
return Ok(Some(entry.key));
}
self.record("restore", &keys.join(" "), None, "miss")?;
Ok(None)
}

/// Saves `paths` (already resolved) under `key`, unless a cache with that key exists.
/// Returns what CircleCI would print.
pub fn save(&self, key: &str, paths: &[PathBuf]) -> Result<String> {
self.db
.expire_cache_entries(SCOPE, self.now, EXPIRY_SECONDS)?;
if self
.db
.find_exact_cache_entry(key, VERSION, SCOPE)?
.is_some()
{
self.record("save", key, None, "exists")?;
return Ok(format!(
"Skipping cache generation, cache already exists for key: {key}"
));
}
let logical = paths
.iter()
.map(|path| self.dirs.logical(path))
.collect::<Result<Vec<_>>>()?;
for (path, logical) in paths.iter().zip(&logical) {
if logical.starts_with("/tmp/") && !path.exists() && self.changed_on_host(logical) {
bail!(
"`save_cache` of `{logical}`: the job's /tmp has no `{logical}`, but the host's does, so a step wrote to the host. Steps reach the job's /tmp through `${{TMPDIR:-/tmp}}`"
);
}
}
if !paths.iter().any(|path| path.exists()) {
self.record("save", key, None, "no-files")?;
return Ok(format!("No files to save for key: {key}"));
}
let id = self.db.insert_cache_entry(key, VERSION, SCOPE, self.now)?;
let dir = self.blob_dir(id);
std::fs::create_dir_all(&dir)?;
let mut manifest = String::new();
for (index, (path, logical)) in paths.iter().zip(&logical).enumerate() {
manifest.push_str(&format!("{logical}\n"));
if path.exists() {
copy_tree(path, &dir.join(index.to_string()), self.blobs)?;
}
}
std::fs::write(dir.join("paths"), manifest)?;
self.record("save", key, None, "saved")?;
Ok(format!("Stored cache for key: {key}"))
}

/// Whether anything at or under the host's `path` changed after the job started (a step
/// wrote it), rather than being left there by something else.
/// The newest change anywhere under `path` counts: a write deep inside an old directory
/// changes only its own parent's time.
fn changed_on_host(&self, path: &str) -> bool {
walkdir::WalkDir::new(path)
.into_iter()
.filter_map(Result::ok)
.filter_map(|entry| entry.metadata().ok()?.modified().ok())
.any(|modified| modified >= self.started)
}

fn blob_dir(&self, id: i64) -> PathBuf {
self.blobs.join(format!("circleci-{id}"))
}

fn record(&self, action: &str, key: &str, matched: Option<&str>, result: &str) -> Result<()> {
self.db.record_cache_event(
self.job_row,
&CacheEvent {
action: action.to_string(),
key: key.to_string(),
matched_key: matched.map(str::to_string),
scope: Some(SCOPE.to_string()),
result: result.to_string(),
},
)
}
}

/// A cache path as the job would see it (`paths.rs`).
pub fn resolve_path(path: &str, dirs: &JobDirs) -> Result<PathBuf> {
if path.contains(['*', '?', '[']) {
bail!("mockci doesn't model glob patterns in cache paths, got `{path}`");
}
dirs.resolve(path, "the cache path")
}

/// The keys of a `restore_cache` step (`key` or `keys`), rendered.
pub fn render_keys(keys: &[String], ctx: &template::Context) -> Result<Vec<String>> {
keys.iter()
.map(|key| template::render(key, ctx).with_context(|| format!("in cache key `{key}`")))
.collect()
}
Loading
Loading