rngit: bound fork, mirror, and sync fetches in time and size

This commit is contained in:
DeFiDude committed 2026-11-13 10:02:25 -07:00
1 parent 86e2ab637a
commit c52cf3a5bb
5 files changed
+297 -38

No files matched your search

+2 -1
View File
@@ -13,7 +13,7 @@ use rns_git::server::config::{
NodeConfig, load_or_create_identity, read_or_create_config, resolve_config_dir,
};
use rns_git::server::forks::{
SYNC_CHECK_INTERVAL, handle_fork, handle_mirror, handle_sync, sync_mirrors,
SYNC_CHECK_INTERVAL, handle_fork, handle_mirror, handle_sync, stop_fetches, sync_mirrors,
};
use rns_git::server::handlers::{
Reply, handle_create, handle_delete, handle_fetch, handle_list, handle_push,
@@ -1438,5 +1438,6 @@ async fn main() {
}
}
println!();
stop_fetches();
rns_tools::exit(&handle, 0).await;
}
+40 -1
View File
@@ -3,6 +3,7 @@
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Duration;
use rns_identity::identity::Identity;
use rns_runtime::config::{Config, ConfigError, ConfigSection};
@@ -12,13 +13,32 @@ use super::perms::{ALL_TGTS, resolve_identity_alias};
use super::py_len;
/// The file upstream writes when the config directory has none
/// (`__default_rngit_config__`, `server.py`).
/// (`__default_rngit_config__`, `server.py`), plus the fetch limit keys.
pub const DEFAULT_CONFIG: &str = include_str!("default_config.txt");
pub const DEFAULT_NODE_NAME: &str = "Anonymous Git Node";
const LOG_NONE: i64 = -1;
const LOG_EXTREME: i64 = 8;
/// Bounds on the `git fetch` of a fork, mirror, or sync, which upstream runs
/// unbounded (`_handle_remote_clone`, `__sync_mirror`, `__sync_fork`, `server.py`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FetchLimits {
/// `fetch_time_limit`, minutes in the config file.
pub time: Duration,
/// `fetch_size_limit`, megabytes in the config file: the bytes a fetch may add on disk.
pub size: u64,
}
impl Default for FetchLimits {
fn default() -> Self {
Self {
time: Duration::from_secs(30 * 60),
size: 1024 * 1024 * 1024,
}
}
}
/// What `__apply_config` takes from the config file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NodeConfig {
@@ -36,6 +56,7 @@ pub struct NodeConfig {
pub stats_ignored: Vec<Vec<u8>>,
pub stats_push_ignored: Vec<Vec<u8>>,
pub blocked_identities: Vec<Vec<u8>>,
pub fetch_limits: FetchLimits,
/// `[repositories]` group name to the configured path, before `~` expansion.
pub repositories: BTreeMap<String, String>,
/// `[access]` group name to its permission statements.
@@ -55,6 +76,7 @@ impl Default for NodeConfig {
stats_ignored: Vec::new(),
stats_push_ignored: Vec::new(),
blocked_identities: Vec::new(),
fetch_limits: FetchLimits::default(),
repositories: BTreeMap::new(),
access: BTreeMap::new(),
}
@@ -76,6 +98,15 @@ fn as_int(section: &ConfigSection, name: &str, key: &str) -> Result<i64, ConfigE
.ok_or_else(|| invalid(name, key, "not an integer"))
}
/// A fetch limit: there is no unlimited value, so anything below 1 counts as 1.
fn as_limit(section: &ConfigSection, name: &str, key: &str) -> Result<u64, ConfigError> {
let value = as_int(section, name, key)?;
if value < 1 {
tracing::warn!("{key} = {value} in configuration file is below 1, using 1");
}
Ok(value.max(1) as u64)
}
/// ConfigObj `as_bool`, which raises on anything but its boolean words.
fn as_bool(section: &ConfigSection, name: &str, key: &str) -> Result<bool, ConfigError> {
section
@@ -129,6 +160,14 @@ impl NodeConfig {
if section.has("record_stats") {
node.record_stats = as_bool(section, name, "record_stats")?;
}
if section.has("fetch_time_limit") {
let minutes = as_limit(section, name, "fetch_time_limit")?;
node.fetch_limits.time = Duration::from_secs(minutes.saturating_mul(60));
}
if section.has("fetch_size_limit") {
let megabytes = as_limit(section, name, "fetch_size_limit")?;
node.fetch_limits.size = megabytes.saturating_mul(1024 * 1024);
}
for (key, target) in [
("stats_ignore_identities", &mut node.stats_ignored),
("stats_push_ignore_identities", &mut node.stats_push_ignored),
@@ -34,6 +34,14 @@ announce_interval = 360
# blocked_identities = d7db22f63b453c23bb0688dde565b7c1
# Longest a fork, mirror, or sync fetch may run, in minutes.
# fetch_time_limit = 30
# Most a fork, mirror, or sync fetch may add on disk, in megabytes.
# fetch_size_limit = 1024
[repositories]
# You can define multiple repository groups, each with a path
+244 -35
View File
@@ -1,6 +1,8 @@
//! `/git/fork`, `/git/mirror`, `/git/sync` and the periodic mirror job
//! (`server.py`).
use std::collections::HashSet;
use std::ffi::OsString;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
@@ -9,6 +11,7 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use rmpv::Value;
use super::config::FetchLimits;
use super::handlers::{
REPO_CREATE_PERMS_TEMPLATE, get, identity_text, log_request, status, truthy,
};
@@ -27,6 +30,19 @@ pub const SYNC_CHECK_INTERVAL: u64 = 15 * 60;
/// `ls-remote` is the only git call upstream bounds (`server.py`).
const LS_REMOTE_TIMEOUT: Duration = Duration::from_secs(30);
/// Git has no fetch size cap, so the repository is measured as the fetch runs:
/// once a second, which bounds the overshoot to a second of transfer for one
/// directory walk.
const SIZE_SAMPLE_INTERVAL: Duration = Duration::from_secs(1);
/// What a stopped fetch gets to drop its lock files before it is killed.
const STOP_GRACE: Duration = Duration::from_secs(2);
const POLL_INTERVAL: Duration = Duration::from_millis(50);
/// Process groups of the fetches in flight.
static FETCHES: Mutex<Vec<nix::libc::pid_t>> = Mutex::new(Vec::new());
/// What a clone handler makes: a fork or a mirror.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepoType {
@@ -99,6 +115,171 @@ fn lossy(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}
fn signal_group(pgid: nix::libc::pid_t, signal: nix::libc::c_int) {
// SAFETY: killpg takes two integers and touches no memory of this process.
unsafe { nix::libc::killpg(pgid, signal) };
}
/// Stop the fetches in flight. They run in their own process groups, so a
/// terminal interrupt of the node does not reach them.
pub fn stop_fetches() {
for pgid in FETCHES.lock().unwrap_or_else(|e| e.into_inner()).iter() {
signal_group(*pgid, nix::libc::SIGTERM);
}
}
/// A fetch's process group, listed in `FETCHES` while it runs.
struct FetchGroup(nix::libc::pid_t);
impl FetchGroup {
fn new(child: &std::process::Child) -> Self {
let pgid = child.id() as nix::libc::pid_t;
FETCHES.lock().unwrap_or_else(|e| e.into_inner()).push(pgid);
FetchGroup(pgid)
}
/// SIGTERM, so git removes its lock files, then SIGKILL for whatever is left.
fn stop(&self, child: &mut std::process::Child) {
signal_group(self.0, nix::libc::SIGTERM);
let deadline = Instant::now() + STOP_GRACE;
while Instant::now() < deadline && !matches!(child.try_wait(), Ok(Some(_))) {
std::thread::sleep(POLL_INTERVAL);
}
signal_group(self.0, nix::libc::SIGKILL);
let _ = child.wait();
}
}
impl Drop for FetchGroup {
fn drop(&mut self) {
FETCHES
.lock()
.unwrap_or_else(|e| e.into_inner())
.retain(|pgid| *pgid != self.0);
}
}
/// Bytes of the files under `path`; what vanishes during the walk counts as nothing.
fn dir_size(path: &Path) -> u64 {
let mut total = 0;
let mut pending = vec![path.to_path_buf()];
while let Some(dir) = pending.pop() {
for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {
match entry.metadata() {
Ok(meta) if meta.is_dir() => pending.push(entry.path()),
Ok(meta) => total += meta.len(),
Err(_) => {}
}
}
}
total
}
fn pack_files(repo_path: &Path) -> HashSet<OsString> {
std::fs::read_dir(repo_path.join("objects/pack"))
.into_iter()
.flatten()
.flatten()
.map(|entry| entry.file_name())
.collect()
}
/// Git leaves the pack it was receiving when stopped, and a mirror is retried
/// at every sync check, so the packs this fetch left are removed.
fn remove_partial_packs(repo_path: &Path, before: &HashSet<OsString>) {
for entry in std::fs::read_dir(repo_path.join("objects/pack"))
.into_iter()
.flatten()
.flatten()
{
let name = entry.file_name();
if name.to_string_lossy().starts_with("tmp_") && !before.contains(&name) {
let _ = std::fs::remove_file(entry.path());
}
}
}
/// How a fetch under [`FetchLimits`] ended.
enum Fetched {
Done,
/// Git's stderr.
Failed(String),
/// The limit it went over, which is already logged.
Stopped(String),
}
/// `git fetch <source> +refs/*:refs/*` in `repo_path`, stopped at a time or size limit.
/// Differs from `_handle_remote_clone`, `__sync_mirror`, and `__sync_fork`
/// (`server.py`), whose fetches have no time or size limit.
fn fetch_all(
label: &str,
repo_path: &Path,
source: &str,
limits: FetchLimits,
) -> std::io::Result<Fetched> {
use std::os::unix::process::CommandExt;
let packs_before = pack_files(repo_path);
let size_before = dir_size(repo_path);
let grown = || dir_size(repo_path).saturating_sub(size_before);
let mut child = Command::new("git")
.args(["fetch", source, "+refs/*:refs/*"])
.current_dir(repo_path)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped())
// Its own group, so the transport helpers it starts are stopped with it.
.process_group(0)
.spawn()?;
let group = FetchGroup::new(&child);
let mut stderr = child.stderr.take().expect("piped");
let reader = std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = stderr.read_to_end(&mut buf);
buf
});
let started = Instant::now();
let mut sampled = started;
let time_limit = || {
let minutes = limits.time.as_secs_f64() / 60.0;
format!("time limit of {minutes} minutes exceeded")
};
let size_limit = || {
let megabytes = limits.size as f64 / (1024.0 * 1024.0);
format!("size limit of {megabytes} megabytes exceeded")
};
let reason = loop {
match child.try_wait() {
Ok(Some(status)) if !status.success() => {
return Ok(Fetched::Failed(lossy(&reader.join().unwrap_or_default())));
}
Ok(Some(_)) if grown() <= limits.size => return Ok(Fetched::Done),
// The fetch finished between two samples.
Ok(Some(_)) => break size_limit(),
Ok(None) => {}
Err(e) => {
group.stop(&mut child);
return Err(e);
}
}
let over = if started.elapsed() >= limits.time {
Some(time_limit())
} else if sampled.elapsed() >= SIZE_SAMPLE_INTERVAL {
sampled = Instant::now();
(grown() > limits.size).then(size_limit)
} else {
None
};
if let Some(reason) = over {
group.stop(&mut child);
remove_partial_packs(repo_path, &packs_before);
break reason;
}
std::thread::sleep(POLL_INTERVAL);
};
tracing::error!("Fetch from {source} for {label} failed: {reason}");
Ok(Fetched::Stopped(reason))
}
/// Python `int()` of a stripped string: sign, digits, single underscores between digits.
fn py_int(text: &str) -> Option<i64> {
let text = text.trim();
@@ -227,7 +408,13 @@ pub fn update_head_to_source_default(repo_path: &Path, source_url: &str) -> bool
/// `__sync_mirror` / `__sync_fork` (`server.py`): fetch every ref
/// from the source; a mirror also follows the source's HEAD.
fn sync_upstream(kind: RepoType, label: &str, path: &Path, source: &str) -> bool {
fn sync_upstream(
kind: RepoType,
label: &str,
path: &Path,
source: &str,
limits: FetchLimits,
) -> bool {
let what = match kind {
RepoType::Mirror => "mirror",
RepoType::Fork => "fork",
@@ -236,15 +423,13 @@ fn sync_upstream(kind: RepoType, label: &str, path: &Path, source: &str) -> bool
tracing::error!("Could not determine upstream source for {what} {label}");
return false;
}
match git(Some(path), &["fetch", source, "+refs/*:refs/*"]) {
Ok(out) if out.status.success() => {}
Ok(out) => {
tracing::error!(
"Failed to sync {what} {label} from {source}: {}",
lossy(&out.stderr)
);
match fetch_all(label, path, source, limits) {
Ok(Fetched::Done) => {}
Ok(Fetched::Failed(stderr)) => {
tracing::error!("Failed to sync {what} {label} from {source}: {stderr}");
return false;
}
Ok(Fetched::Stopped(_)) => return false,
Err(e) => {
tracing::error!("Error syncing {what} {label}: {e}");
return false;
@@ -282,9 +467,9 @@ pub fn sync_mirrors(repos: &RwLock<Repositories>, mirror_interval: i64, sync_loc
let Ok(_guard) = sync_lock.try_lock() else {
return;
};
let mirrors: Vec<(String, PathBuf, String)> = {
let (mirrors, limits): (Vec<(String, PathBuf, String)>, FetchLimits) = {
let repos = repos.read().unwrap_or_else(|e| e.into_inner());
repos
let mirrors = repos
.groups
.values()
.flat_map(|g| g.repositories.values())
@@ -292,12 +477,13 @@ pub fn sync_mirrors(repos: &RwLock<Repositories>, mirror_interval: i64, sync_loc
let source = r.mirror.clone().filter(|s| !s.is_empty())?;
Some((format!("{}/{}", r.group, r.name), r.path.clone(), source))
})
.collect()
.collect();
(mirrors, repos.fetch_limits)
};
for (label, path, source) in mirrors {
if now_secs() > mirror_synced(&path) + mirror_interval {
tracing::info!("Syncing mirror {label}");
sync_upstream(RepoType::Mirror, &label, &path, &source);
sync_upstream(RepoType::Mirror, &label, &path, &source, limits);
}
}
}
@@ -405,7 +591,7 @@ fn handle_remote_clone(
return Some(status(RES_INVALID_REQ, "Invalid request"));
};
let final_path = {
let (final_path, limits) = {
let r = repos.read().unwrap_or_else(|e| e.into_inner());
let Some(group_path) = r.groups.get(group).map(|g| g.path.clone()) else {
return Some(status(RES_NOT_FOUND, "Not found"));
@@ -430,10 +616,19 @@ fn handle_remote_clone(
status(RES_NOT_FOUND, "Not found")
});
}
final_path
(final_path, r.fetch_limits)
};
let reply = clone_into(repos, hash, group, repo, source_url, &final_path, repo_type);
let reply = clone_into(
repos,
hash,
group,
repo,
source_url,
&final_path,
repo_type,
limits,
);
Some(reply.unwrap_or_else(|e| {
tracing::error!(
"Error while {}ing repository {group}/{repo}: {e}",
@@ -447,6 +642,7 @@ fn handle_remote_clone(
}
/// The `try` body of `_handle_remote_clone` (`server.py`).
#[allow(clippy::too_many_arguments)]
fn clone_into(
repos: &RwLock<Repositories>,
hash: &[u8; 16],
@@ -455,6 +651,7 @@ fn clone_into(
source_url: &str,
final_path: &Path,
repo_type: RepoType,
limits: FetchLimits,
) -> Result<Vec<u8>, String> {
let kind = repo_type.name();
tracing::debug!(
@@ -485,14 +682,22 @@ fn clone_into(
return Ok(status(RES_REMOTE_FAIL, "Failed to initialize repository"));
}
tracing::debug!("Fetching from {source_url}...");
let result = run(&["fetch", source_url, "+refs/*:refs/*"])?;
if !result.status.success() {
let stderr = lossy(&result.stderr);
tracing::error!("Failed to fetch from {source_url}: {stderr}");
return Ok(status(
RES_REMOTE_FAIL,
&format!("Failed to fetch from source: {stderr}"),
));
let label = format!("{group}/{repo}");
match fetch_all(&label, &temp_path, source_url, limits).map_err(|e| e.to_string())? {
Fetched::Done => {}
Fetched::Failed(stderr) => {
tracing::error!("Failed to fetch from {source_url}: {stderr}");
return Ok(status(
RES_REMOTE_FAIL,
&format!("Failed to fetch from source: {stderr}"),
));
}
Fetched::Stopped(reason) => {
return Ok(status(
RES_REMOTE_FAIL,
&format!("Failed to fetch from source: {reason}"),
));
}
}
update_head_to_source_default(&temp_path, source_url);
@@ -606,24 +811,28 @@ pub fn handle_sync(
let label = format!("{group}/{repo}");
let mirror = repository.mirror.clone().filter(|s| !s.is_empty());
let fork = repository.fork.clone().filter(|s| !s.is_empty());
(label, repository.path.clone(), mirror, fork)
(label, repository.path.clone(), mirror, fork, r.fetch_limits)
};
let (label, path, mirror, fork) = target;
let (label, path, mirror, fork, limits) = target;
if let Some(source) = mirror {
tracing::info!("Syncing mirror {label}");
return Some(if sync_upstream(RepoType::Mirror, &label, &path, &source) {
vec![RES_OK]
} else {
status(RES_REMOTE_FAIL, "Mirror sync failed")
});
return Some(
if sync_upstream(RepoType::Mirror, &label, &path, &source, limits) {
vec![RES_OK]
} else {
status(RES_REMOTE_FAIL, "Mirror sync failed")
},
);
}
if let Some(source) = fork {
tracing::info!("Syncing fork {label} with upstream");
return Some(if sync_upstream(RepoType::Fork, &label, &path, &source) {
vec![RES_OK]
} else {
status(RES_REMOTE_FAIL, "Fork sync failed")
});
return Some(
if sync_upstream(RepoType::Fork, &label, &path, &source, limits) {
vec![RES_OK]
} else {
status(RES_REMOTE_FAIL, "Fork sync failed")
},
);
}
Some(status(
RES_INVALID_REQ,
+3 -1
View File
@@ -5,7 +5,7 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use super::config::{NodeConfig, expand_user};
use super::config::{FetchLimits, NodeConfig, expand_user};
use super::perms::{AllowedError, Perm, Permissions, load_allowed_permissions};
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -37,6 +37,7 @@ pub struct Repositories {
pub groups: BTreeMap<String, Group>,
pub aliases: BTreeMap<String, String>,
pub blocked: Vec<Vec<u8>>,
pub fetch_limits: FetchLimits,
}
/// A `git` call in `cwd` with output captured; `None` when it cannot run
@@ -80,6 +81,7 @@ impl Repositories {
groups: BTreeMap::new(),
aliases: config.aliases.clone(),
blocked: config.blocked_identities.clone(),
fetch_limits: config.fetch_limits,
};
for (name, raw_path) in &config.repositories {
let path = expand_user(raw_path);