fix(git): the clone cache heals itself after an interrupted clone or fetch (#486) #487

Merged
sharang merged 1 commits from fix/486-clone-cache-heal into main 2026-10-06 08:19:14 +00:00
2 changed files with 212 additions and 13 deletions

No files matched your search

+194 -13
View File
@@ -285,26 +285,67 @@ impl GitOps {
// Per tenant: two tenants with the same target name get two checkouts.
let repo_path = self.clone_path(repo_name);
if repo_path.exists() {
// A cache entry a redeploy interrupted (an empty directory, a
// half-written reference, a lock) is cloned again, never left to fail
// every scan after it (#486).
if repo_path.exists() && prepare_entry(&repo_path) {
tracing::info!("fetching updates for existing repo");
self.fetch(&repo_path)?;
} else {
// Before creating the directory: a refused remote must not leave
// an empty checkout behind for the next run to try to fetch.
self.check_remote(git_url)?;
std::fs::create_dir_all(&repo_path)?;
if let Err(e) = self.clone_repo(git_url, &repo_path) {
// A half-cloned directory would be fetched, not cloned, next
// time.
let _ = std::fs::remove_dir_all(&repo_path);
return Err(e);
match self.fetch(&repo_path) {
Ok(()) => return Ok(repo_path),
Err(AgentError::Git(e)) if is_corruption(&e) => {
tracing::warn!(
tenant_id = %self.tenant_id,
target = %repo_name,
error = %e,
"clone cache entry is broken; cloning it again"
);
std::fs::remove_dir_all(&repo_path)?;
}
Err(e) => return Err(e),
}
tracing::info!("Cloned {git_url} to {}", repo_path.display());
} else if repo_path.exists() {
tracing::warn!(
tenant_id = %self.tenant_id,
target = %repo_name,
"clone cache entry is not a usable repository; cloning it again"
);
std::fs::remove_dir_all(&repo_path)?;
}
// Before creating anything: a refused remote must not leave an entry
// behind for the next run to try to fetch.
self.check_remote(git_url)?;
self.clone_atomically(git_url, &repo_path)?;
tracing::info!("Cloned {git_url} to {}", repo_path.display());
Ok(repo_path)
}
/// Clone into a directory next to `repo_path` and move it into place, so
/// an interrupted clone never leaves a half entry. Directories an earlier
/// interrupted clone left are removed first.
fn clone_atomically(&self, git_url: &str, repo_path: &Path) -> Result<(), AgentError> {
let parent = repo_path
.parent()
.ok_or_else(|| AgentError::Other("clone path has no parent".to_string()))?;
std::fs::create_dir_all(parent)?;
let prefix = temp_prefix(repo_path);
for leftover in std::fs::read_dir(parent)?.filter_map(Result::ok) {
if leftover.file_name().to_string_lossy().starts_with(&prefix) {
let _ = std::fs::remove_dir_all(leftover.path());
}
}
let temp = parent.join(format!("{prefix}{}", uuid::Uuid::new_v4()));
if let Err(e) = self.clone_repo(git_url, &temp) {
let _ = std::fs::remove_dir_all(&temp);
return Err(e);
}
if let Err(e) = std::fs::rename(&temp, repo_path) {
let _ = std::fs::remove_dir_all(&temp);
return Err(e.into());
}
Ok(())
}
#[tracing::instrument(skip_all)]
fn clone_repo(&self, git_url: &str, repo_path: &Path) -> Result<(), AgentError> {
tracing::info!("cloning repo from {}", git_url);
@@ -476,6 +517,58 @@ pub struct DiffFile {
pub hunks: String,
}
/// The name prefix of the directory a clone of `repo_path` is made in.
fn temp_prefix(repo_path: &Path) -> String {
let name = repo_path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
format!(".{name}.cloning-")
}
/// Make a clone cache entry ready to fetch into: remove what an interrupted
/// fetch leaves (`FETCH_HEAD`, which every fetch writes anew, and `*.lock`
/// files; a target's scans never overlap, so no other git holds them), then
/// check that it opens as a repository with an `origin`.
///
/// # Returns
///
/// `false` when the entry is not a usable repository (an empty directory
/// from an interrupted clone, a broken `.git`): the caller clones it again.
fn prepare_entry(repo_path: &Path) -> bool {
let git_dir = repo_path.join(".git");
let _ = std::fs::remove_file(git_dir.join("FETCH_HEAD"));
let locks = walkdir::WalkDir::new(&git_dir)
.max_depth(6)
.into_iter()
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file() && e.file_name().to_string_lossy().ends_with(".lock"));
for lock in locks {
tracing::warn!(path = %lock.path().display(), "removing a lock an interrupted git left");
let _ = std::fs::remove_file(lock.path());
}
// Only what the fetch needs to start: whatever else is broken shows as a
// corruption error there, after the stored remote was checked again.
Repository::open(repo_path)
.and_then(|repo| repo.find_remote("origin").map(drop))
.is_ok()
}
/// Whether a git error means the cache entry itself is broken (a missing or
/// corrupt repository, reference or object), not the network or the remote.
fn is_corruption(error: &git2::Error) -> bool {
use git2::ErrorClass;
matches!(
error.class(),
ErrorClass::Repository
| ErrorClass::Reference
| ErrorClass::Odb
| ErrorClass::Object
| ErrorClass::Index
| ErrorClass::Checkout
)
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
@@ -510,6 +603,94 @@ mod tests {
assert_eq!(limits.timeout.as_secs(), 1800);
}
/// A repository with one commit and an `origin`, in a fresh directory.
fn source_repo() -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("cs-src-{}", uuid::Uuid::new_v4()));
let repo = git2::Repository::init(&dir).unwrap();
std::fs::write(dir.join("README.md"), "pump controller").unwrap();
let mut index = repo.index().unwrap();
index.add_path(Path::new("README.md")).unwrap();
index.write().unwrap();
let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
let sig = git2::Signature::now("t", "t@example.com").unwrap();
repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
.unwrap();
repo.remote("origin", "https://git.example.com/pumps/ctl.git")
.unwrap();
dir
}
#[test]
fn a_broken_cache_entry_is_recognised_and_leftovers_cleared() {
// An interrupted clone: the directory exists, the repository does not.
let empty = std::env::temp_dir().join(format!("cs-empty-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&empty).unwrap();
assert!(!super::prepare_entry(&empty));
let Err(opened) = git2::Repository::open(&empty) else {
panic!("an empty directory opened as a repository");
};
assert!(super::is_corruption(&opened));
std::fs::remove_dir_all(&empty).unwrap();
// An interrupted fetch: a half-written FETCH_HEAD and locks.
let repo = source_repo();
let git = repo.join(".git");
std::fs::write(git.join("FETCH_HEAD"), "\0garbage").unwrap();
std::fs::write(git.join("index.lock"), "").unwrap();
std::fs::write(git.join("refs/heads/main.lock"), "").unwrap();
assert!(super::prepare_entry(&repo));
assert!(!git.join("FETCH_HEAD").exists());
assert!(!git.join("index.lock").exists());
assert!(!git.join("refs/heads/main.lock").exists());
std::fs::remove_dir_all(&repo).unwrap();
// The network or the remote are not the entry's fault.
let net = git2::Error::new(
git2::ErrorCode::GenericError,
git2::ErrorClass::Net,
"connection reset",
);
assert!(!super::is_corruption(&net));
}
#[test]
fn a_clone_appears_whole_or_not_at_all() {
let source = source_repo();
let base = std::env::temp_dir().join(format!("cs-cache-{}", uuid::Uuid::new_v4()));
let ops = GitOps::new(
base.to_str().unwrap(),
"tenant-a",
RepoCredentials::default(),
NetGuard::allow_private(),
);
let entry = ops.clone_path("pump-ctl");
// What an earlier interrupted clone left beside the entry.
let leftover = entry
.parent()
.unwrap()
.join(format!("{}stale", super::temp_prefix(&entry)));
std::fs::create_dir_all(&leftover).unwrap();
ops.clone_atomically(source.to_str().unwrap(), &entry)
.unwrap();
assert!(entry.join("README.md").is_file());
assert!(!leftover.exists());
let siblings: Vec<String> = std::fs::read_dir(entry.parent().unwrap())
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().to_string())
.collect();
assert_eq!(siblings.len(), 1, "{siblings:?}");
// A clone that fails leaves nothing behind.
let missing = ops.clone_path("missing");
assert!(ops
.clone_atomically("/nonexistent/repository", &missing)
.is_err());
assert!(!missing.exists());
let _ = std::fs::remove_dir_all(&base);
let _ = std::fs::remove_dir_all(&source);
}
#[test]
fn lfs_patterns_come_from_gitattributes() {
let dir = std::env::temp_dir().join(format!("cs-lfs-{}", uuid::Uuid::new_v4()));
@@ -14,6 +14,7 @@ together on stage in one pass before the next prod promotion.
| #477 | Findings grouped per rule; gitleaks ignores `*.launch` debugger ids |
| #478–#482 | iOS readiness 1–5: Carthage and lifecycle, iOS rules, Unity targets, app variants, public samples (with the mobsfscan and Firebase fixes) |
| #484 | Groups take over their places' decisions (#483) |
| #486 | The clone cache heals itself after an interrupted clone or fetch |
**Customer-visible on the next prod rescan** is marked **[visible]**: these
change what a customer sees on their existing targets, without them doing
@@ -199,6 +200,23 @@ places) and rescan.
- **[visible]** iOS apps with newer Swift now get mobile analysis; generic-api-key
findings on Firebase Storage URLs close as no longer found.
### 14. #486 Clone cache heals itself
- **Do:** on the stage node, break the cache entry of a git target in
`/home/sharang/bp-cache/pruefwerk-stage-repos/<tenant>/<target>` three
ways, one per scan: empty the directory (`rm -rf <entry>/* <entry>/.git`),
write garbage into `<entry>/.git/FETCH_HEAD`, create `<entry>/.git/index.lock`.
Start **Prüfung starten** after each.
- **Expect:** every scan completes; no "could not find repository" or
"corrupted loose reference file". The two stage targets that failed on this
before scan again on their next schedule.
- **Log:** `clone cache entry is not a usable repository; cloning it again`
(empty directory), `removing a lock an interrupted git left` (lock); a
corrupt object store: `clone cache entry is broken; cloning it again`. No
`*.cloning-*` directories stay beside the entries.
- **[visible]** customers whose scans failed on a broken cache entry get scans
again; nothing else changes.
## After the pass
- The nightly job on `main` is green with the new mobile targets.