style: switch rustfmt to hard tabs; document tests-separate rule in TODO
- rustfmt.toml: hard_tabs = true. - TODO §0.7: tests live in tests/, no #[cfg(test)] modules in code files.
This commit is contained in:
parent
d8393e0f39
commit
a90f0da226
96 changed files with 6542 additions and 6537 deletions
|
|
@ -25,11 +25,11 @@ use super::services::{build_registry, build_whitelist, start_subnet_tracker, sta
|
|||
use super::shutdown::{RunExit, spawn_shutdown_drain};
|
||||
|
||||
fn attack_status_value(status: AttackStatus) -> i64 {
|
||||
match status {
|
||||
AttackStatus::Normal => 0,
|
||||
AttackStatus::Suspicious => 1,
|
||||
AttackStatus::UnderAttack => 2,
|
||||
}
|
||||
match status {
|
||||
AttackStatus::Normal => 0,
|
||||
AttackStatus::Suspicious => 1,
|
||||
AttackStatus::UnderAttack => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// Точка входа edge-демона (`rampart`): то, что делал `main` бинаря.
|
||||
|
|
@ -39,194 +39,194 @@ fn attack_status_value(status: AttackStatus) -> i64 {
|
|||
/// # Errors
|
||||
/// Ошибки старта: нечитаемый конфиг, пустой реестр протоколов, сбой listener.
|
||||
pub async fn run() -> anyhow::Result<RunExit> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env().add_directive("rampart=info".parse()?))
|
||||
.init();
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env().add_directive("rampart=info".parse()?))
|
||||
.init();
|
||||
|
||||
let config_path = std::env::var("RAMPART_CONFIG").unwrap_or_else(|_| "/etc/rampart/config.toml".to_string());
|
||||
let config = Arc::new(Config::from_file(&config_path)?);
|
||||
let config_path = std::env::var("RAMPART_CONFIG").unwrap_or_else(|_| "/etc/rampart/config.toml".to_string());
|
||||
let config = Arc::new(Config::from_file(&config_path)?);
|
||||
|
||||
let registry = Arc::new(build_registry(&config));
|
||||
if registry.is_empty() {
|
||||
anyhow::bail!(
|
||||
"no protocol plugins compiled; available feature flags: protocol-http, \
|
||||
let registry = Arc::new(build_registry(&config));
|
||||
if registry.is_empty() {
|
||||
anyhow::bail!(
|
||||
"no protocol plugins compiled; available feature flags: protocol-http, \
|
||||
store-redis, geoip, xdp, io-uring. Build with --features protocol-http \
|
||||
or link an external ProtocolHandler implementation"
|
||||
);
|
||||
}
|
||||
let whitelist = build_whitelist(&config)?;
|
||||
);
|
||||
}
|
||||
let whitelist = build_whitelist(&config)?;
|
||||
|
||||
let rate_limiter = Arc::new(RateLimiter::new(
|
||||
config.limits.rate_limit_pps,
|
||||
config.limits.rate_limit_burst,
|
||||
));
|
||||
let blacklist = Arc::new(Blacklist::new());
|
||||
let reputation = Arc::new(IpReputation::new());
|
||||
let detector = Arc::new(Mutex::new(AttackDetector::new()));
|
||||
let hook = Arc::new(TrafficHook::new(
|
||||
reputation.clone(),
|
||||
blacklist.clone(),
|
||||
config.detect.autoban.clone(),
|
||||
config.ban.ban_duration_secs,
|
||||
));
|
||||
let alert_dispatcher = AlertDispatcher::new();
|
||||
let webhook_url = config.detect.alert.webhook_url.clone();
|
||||
let allowed_1s = Arc::new(AtomicU64::new(0));
|
||||
let rate_limiter = Arc::new(RateLimiter::new(
|
||||
config.limits.rate_limit_pps,
|
||||
config.limits.rate_limit_burst,
|
||||
));
|
||||
let blacklist = Arc::new(Blacklist::new());
|
||||
let reputation = Arc::new(IpReputation::new());
|
||||
let detector = Arc::new(Mutex::new(AttackDetector::new()));
|
||||
let hook = Arc::new(TrafficHook::new(
|
||||
reputation.clone(),
|
||||
blacklist.clone(),
|
||||
config.detect.autoban.clone(),
|
||||
config.ban.ban_duration_secs,
|
||||
));
|
||||
let alert_dispatcher = AlertDispatcher::new();
|
||||
let webhook_url = config.detect.alert.webhook_url.clone();
|
||||
let allowed_1s = Arc::new(AtomicU64::new(0));
|
||||
|
||||
let (shutdown_tx, shutdown_rx) = watch::channel(false);
|
||||
let (drain_tx, drain_rx) = oneshot::channel();
|
||||
let (shutdown_tx, shutdown_rx) = watch::channel(false);
|
||||
let (drain_tx, drain_rx) = oneshot::channel();
|
||||
|
||||
spawn_shutdown_drain(shutdown_tx.clone(), drain_tx);
|
||||
spawn_shutdown_drain(shutdown_tx.clone(), drain_tx);
|
||||
|
||||
#[cfg(feature = "store-redis")]
|
||||
if let Some(redis_url) = &config.store.redis_url
|
||||
&& !redis_url.is_empty()
|
||||
{
|
||||
let bl = blacklist.clone();
|
||||
let sd = shutdown_rx.clone();
|
||||
let url = redis_url.clone();
|
||||
tokio::spawn(async move {
|
||||
let client = match redis::Client::open(url.as_str()) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
tracing::warn!("Invalid redis_url: {e}, blacklist sync disabled");
|
||||
return;
|
||||
},
|
||||
};
|
||||
let local_events = bl.subscribe_local_bans();
|
||||
let publisher_client = client.clone();
|
||||
let publisher_blacklist = bl.clone();
|
||||
let publisher_shutdown = sd.clone();
|
||||
tokio::spawn(async move {
|
||||
crate::store::start_local_ban_publisher(
|
||||
publisher_client,
|
||||
publisher_blacklist,
|
||||
local_events,
|
||||
publisher_shutdown,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
crate::store::start_blacklist_sync(&client, bl, sd).await;
|
||||
});
|
||||
}
|
||||
#[cfg(feature = "store-redis")]
|
||||
if let Some(redis_url) = &config.store.redis_url
|
||||
&& !redis_url.is_empty()
|
||||
{
|
||||
let bl = blacklist.clone();
|
||||
let sd = shutdown_rx.clone();
|
||||
let url = redis_url.clone();
|
||||
tokio::spawn(async move {
|
||||
let client = match redis::Client::open(url.as_str()) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
tracing::warn!("Invalid redis_url: {e}, blacklist sync disabled");
|
||||
return;
|
||||
},
|
||||
};
|
||||
let local_events = bl.subscribe_local_bans();
|
||||
let publisher_client = client.clone();
|
||||
let publisher_blacklist = bl.clone();
|
||||
let publisher_shutdown = sd.clone();
|
||||
tokio::spawn(async move {
|
||||
crate::store::start_local_ban_publisher(
|
||||
publisher_client,
|
||||
publisher_blacklist,
|
||||
local_events,
|
||||
publisher_shutdown,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
crate::store::start_blacklist_sync(&client, bl, sd).await;
|
||||
});
|
||||
}
|
||||
|
||||
if config.metrics.enabled {
|
||||
let metrics_addr = format!("0.0.0.0:{}", config.metrics.port);
|
||||
tracing::info!("Metrics server listening on {metrics_addr}");
|
||||
tokio::spawn(async move {
|
||||
metrics::run_metrics_server(&metrics_addr).await;
|
||||
});
|
||||
}
|
||||
if config.metrics.enabled {
|
||||
let metrics_addr = format!("0.0.0.0:{}", config.metrics.port);
|
||||
tracing::info!("Metrics server listening on {metrics_addr}");
|
||||
tokio::spawn(async move {
|
||||
metrics::run_metrics_server(&metrics_addr).await;
|
||||
});
|
||||
}
|
||||
|
||||
let clickhouse: Option<Arc<tokio::sync::Mutex<ClickHouseWriter>>> = match &config.store.clickhouse_url {
|
||||
Some(url) if !url.is_empty() => {
|
||||
let writer = Arc::new(tokio::sync::Mutex::new(ClickHouseWriter::new(url)));
|
||||
crate::store::clickhouse::start_flush_task(writer.clone(), shutdown_rx.clone());
|
||||
Some(writer)
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let clickhouse: Option<Arc<tokio::sync::Mutex<ClickHouseWriter>>> = match &config.store.clickhouse_url {
|
||||
Some(url) if !url.is_empty() => {
|
||||
let writer = Arc::new(tokio::sync::Mutex::new(ClickHouseWriter::new(url)));
|
||||
crate::store::clickhouse::start_flush_task(writer.clone(), shutdown_rx.clone());
|
||||
Some(writer)
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let xdp_filter = start_xdp(&config, &shutdown_rx, &blacklist)?;
|
||||
let subnet_tracker = start_subnet_tracker(&config);
|
||||
monitor::spawn(
|
||||
&config.detect.prefix,
|
||||
subnet_tracker.clone(),
|
||||
xdp_filter.clone(),
|
||||
shutdown_rx.clone(),
|
||||
);
|
||||
let xdp_filter = start_xdp(&config, &shutdown_rx, &blacklist)?;
|
||||
let subnet_tracker = start_subnet_tracker(&config);
|
||||
monitor::spawn(
|
||||
&config.detect.prefix,
|
||||
subnet_tracker.clone(),
|
||||
xdp_filter.clone(),
|
||||
shutdown_rx.clone(),
|
||||
);
|
||||
|
||||
let rl = rate_limiter.clone();
|
||||
let bl = blacklist.clone();
|
||||
let det = detector.clone();
|
||||
let intel = hook.clone();
|
||||
let a1s = allowed_1s.clone();
|
||||
let ch = clickhouse.clone();
|
||||
let mut sd = shutdown_rx.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut sec_tick = tokio::time::interval(Duration::from_secs(1));
|
||||
let mut min_tick = tokio::time::interval(Duration::from_secs(60));
|
||||
sec_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
min_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = sd.changed() => {
|
||||
if *sd.borrow() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
_ = sec_tick.tick() => {
|
||||
let pps = a1s.swap(0, Ordering::Relaxed) as f64;
|
||||
let cps = intel.take_cps() as f64;
|
||||
metrics::INTEL_CPS.set(cps as i64);
|
||||
let status = det.lock().expect("detector lock poisoned").analyze(pps, cps);
|
||||
metrics::ATTACK_STATUS.set(attack_status_value(status));
|
||||
if let Some(alert) = alert_dispatcher.on_status(status) {
|
||||
// Дедупликация: алерт только на переходе состояния атаки.
|
||||
metrics::INTEL_ALERTS_TOTAL.inc();
|
||||
tracing::warn!(pps, cps, "{alert}");
|
||||
push_attack_event(&ch, pps).await;
|
||||
if let Some(url) = webhook_url.clone() {
|
||||
tokio::spawn(send_webhook(url, alert.clone()));
|
||||
}
|
||||
}
|
||||
if status == AttackStatus::UnderAttack {
|
||||
let banned = intel.ban_offenders();
|
||||
if banned > 0 {
|
||||
tracing::info!(banned, "escalation: offenders auto-banned during attack");
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = min_tick.tick() => {
|
||||
rl.sweep();
|
||||
bl.clear_expired();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let rl = rate_limiter.clone();
|
||||
let bl = blacklist.clone();
|
||||
let det = detector.clone();
|
||||
let intel = hook.clone();
|
||||
let a1s = allowed_1s.clone();
|
||||
let ch = clickhouse.clone();
|
||||
let mut sd = shutdown_rx.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut sec_tick = tokio::time::interval(Duration::from_secs(1));
|
||||
let mut min_tick = tokio::time::interval(Duration::from_secs(60));
|
||||
sec_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
min_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = sd.changed() => {
|
||||
if *sd.borrow() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
_ = sec_tick.tick() => {
|
||||
let pps = a1s.swap(0, Ordering::Relaxed) as f64;
|
||||
let cps = intel.take_cps() as f64;
|
||||
metrics::INTEL_CPS.set(cps as i64);
|
||||
let status = det.lock().expect("detector lock poisoned").analyze(pps, cps);
|
||||
metrics::ATTACK_STATUS.set(attack_status_value(status));
|
||||
if let Some(alert) = alert_dispatcher.on_status(status) {
|
||||
// Дедупликация: алерт только на переходе состояния атаки.
|
||||
metrics::INTEL_ALERTS_TOTAL.inc();
|
||||
tracing::warn!(pps, cps, "{alert}");
|
||||
push_attack_event(&ch, pps).await;
|
||||
if let Some(url) = webhook_url.clone() {
|
||||
tokio::spawn(send_webhook(url, alert.clone()));
|
||||
}
|
||||
}
|
||||
if status == AttackStatus::UnderAttack {
|
||||
let banned = intel.ban_offenders();
|
||||
if banned > 0 {
|
||||
tracing::info!(banned, "escalation: offenders auto-banned during attack");
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = min_tick.tick() => {
|
||||
rl.sweep();
|
||||
bl.clear_expired();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
tracing::info!("Rampart edge starting on {}:{}", config.bind.address, config.bind.port);
|
||||
tracing::info!("Upstreams: {:?}", config.backend.upstreams);
|
||||
tracing::info!("Rampart edge starting on {}:{}", config.bind.address, config.bind.port);
|
||||
tracing::info!("Upstreams: {:?}", config.backend.upstreams);
|
||||
|
||||
let adjuster = Arc::new(Mutex::new(DifficultyAdjuster::default()));
|
||||
let gateway = Arc::new(Gateway::new(
|
||||
config.clone(),
|
||||
rate_limiter,
|
||||
blacklist,
|
||||
adjuster,
|
||||
whitelist,
|
||||
reputation,
|
||||
xdp_filter,
|
||||
clickhouse,
|
||||
allowed_1s,
|
||||
registry,
|
||||
subnet_tracker,
|
||||
));
|
||||
tokio::select! {
|
||||
result = listener::run(config, gateway, hook, shutdown_rx) => {
|
||||
result?;
|
||||
Ok(RunExit::Ok)
|
||||
}
|
||||
// Drain-таймаут сработал: возвращаем сигнал бинарю завершить процесс
|
||||
// немедленно, как это делал прежний `process::exit(0)`.
|
||||
_ = drain_rx => Ok(RunExit::DrainTimeout),
|
||||
}
|
||||
let adjuster = Arc::new(Mutex::new(DifficultyAdjuster::default()));
|
||||
let gateway = Arc::new(Gateway::new(
|
||||
config.clone(),
|
||||
rate_limiter,
|
||||
blacklist,
|
||||
adjuster,
|
||||
whitelist,
|
||||
reputation,
|
||||
xdp_filter,
|
||||
clickhouse,
|
||||
allowed_1s,
|
||||
registry,
|
||||
subnet_tracker,
|
||||
));
|
||||
tokio::select! {
|
||||
result = listener::run(config, gateway, hook, shutdown_rx) => {
|
||||
result?;
|
||||
Ok(RunExit::Ok)
|
||||
}
|
||||
// Drain-таймаут сработал: возвращаем сигнал бинарю завершить процесс
|
||||
// немедленно, как это делал прежний `process::exit(0)`.
|
||||
_ = drain_rx => Ok(RunExit::DrainTimeout),
|
||||
}
|
||||
}
|
||||
|
||||
async fn push_attack_event(writer: &Option<Arc<tokio::sync::Mutex<ClickHouseWriter>>>, pps: f64) {
|
||||
let Some(writer) = writer else {
|
||||
return;
|
||||
};
|
||||
let event = ClickHouseEvent {
|
||||
timestamp: chrono::Utc::now(),
|
||||
event_type: "attack".to_string(),
|
||||
ip: String::new(),
|
||||
data_float: pps,
|
||||
data_int: 0,
|
||||
data_string: "under_attack".to_string(),
|
||||
};
|
||||
if let Err(e) = writer.lock().await.push(event).await {
|
||||
tracing::debug!("clickhouse push error: {e}");
|
||||
}
|
||||
let Some(writer) = writer else {
|
||||
return;
|
||||
};
|
||||
let event = ClickHouseEvent {
|
||||
timestamp: chrono::Utc::now(),
|
||||
event_type: "attack".to_string(),
|
||||
ip: String::new(),
|
||||
data_float: pps,
|
||||
data_int: 0,
|
||||
data_string: "under_attack".to_string(),
|
||||
};
|
||||
if let Err(e) = writer.lock().await.push(event).await {
|
||||
tracing::debug!("clickhouse push error: {e}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,116 +19,116 @@ use tokio::sync::watch;
|
|||
/// HTTP/1.1-обработчик с политикой из секции `[protocol.http]`.
|
||||
/// Внешние крейты регистрируют свои обработчики в этом же месте.
|
||||
pub(crate) fn build_registry(config: &Config) -> ProtocolRegistry {
|
||||
#[cfg(feature = "protocol-minecraft")]
|
||||
if config.protocol.minecraft.enabled {
|
||||
let mut registry = ProtocolRegistry::new();
|
||||
registry.register(Box::new(crate::protocol::minecraft::MinecraftProtocolHandler::new(
|
||||
&config.protocol.minecraft,
|
||||
&config.backend.upstreams,
|
||||
)));
|
||||
return registry;
|
||||
}
|
||||
#[cfg(feature = "protocol-http")]
|
||||
{
|
||||
let mut registry = ProtocolRegistry::new();
|
||||
register_http(&mut registry, config);
|
||||
registry
|
||||
}
|
||||
#[cfg(not(feature = "protocol-http"))]
|
||||
{
|
||||
let _ = config;
|
||||
ProtocolRegistry::new()
|
||||
}
|
||||
#[cfg(feature = "protocol-minecraft")]
|
||||
if config.protocol.minecraft.enabled {
|
||||
let mut registry = ProtocolRegistry::new();
|
||||
registry.register(Box::new(crate::protocol::minecraft::MinecraftProtocolHandler::new(
|
||||
&config.protocol.minecraft,
|
||||
&config.backend.upstreams,
|
||||
)));
|
||||
return registry;
|
||||
}
|
||||
#[cfg(feature = "protocol-http")]
|
||||
{
|
||||
let mut registry = ProtocolRegistry::new();
|
||||
register_http(&mut registry, config);
|
||||
registry
|
||||
}
|
||||
#[cfg(not(feature = "protocol-http"))]
|
||||
{
|
||||
let _ = config;
|
||||
ProtocolRegistry::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "protocol-http")]
|
||||
fn register_http(registry: &mut ProtocolRegistry, config: &Config) {
|
||||
registry.register(Box::new(crate::protocol::http::HttpProtocolHandler::new(
|
||||
&config.protocol.http,
|
||||
&config.backend.upstreams,
|
||||
)));
|
||||
registry.register(Box::new(crate::protocol::http::HttpProtocolHandler::new(
|
||||
&config.protocol.http,
|
||||
&config.backend.upstreams,
|
||||
)));
|
||||
}
|
||||
|
||||
#[cfg(feature = "xdp")]
|
||||
pub(crate) fn start_xdp(
|
||||
config: &Arc<Config>,
|
||||
shutdown_rx: &watch::Receiver<bool>,
|
||||
blacklist: &Arc<Blacklist>,
|
||||
config: &Arc<Config>,
|
||||
shutdown_rx: &watch::Receiver<bool>,
|
||||
blacklist: &Arc<Blacklist>,
|
||||
) -> anyhow::Result<Option<Arc<Mutex<XdpFilter>>>> {
|
||||
use std::time::Duration;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::xdp::XdpMetrics;
|
||||
use crate::xdp::XdpMetrics;
|
||||
|
||||
if !config.xdp.enabled {
|
||||
return Ok(None);
|
||||
}
|
||||
if !config.xdp.enabled {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let filter = XdpFilter::new(&config.xdp.interface);
|
||||
let shared = Arc::new(Mutex::new(filter));
|
||||
{
|
||||
let mut guard = shared.lock().expect("xdp lock poisoned");
|
||||
let globals = XdpGlobals::from_config(&config.xdp)?;
|
||||
guard.set_globals(globals);
|
||||
// With ingress PROXY protocol, XDP sees only the provider's transport
|
||||
// address, so its events must not trigger per-player or provider bans.
|
||||
if !config.proxy_protocol.ingress_enabled {
|
||||
// load() captures the blacklist and auto-ban policy in its ringbuf
|
||||
// callback, so set_autoban must happen first.
|
||||
guard.set_autoban(blacklist.clone(), &config.xdp);
|
||||
} else if config.xdp.auto_ban_enabled {
|
||||
tracing::warn!(
|
||||
"XDP auto-ban is disabled while inbound PROXY protocol is enabled; XDP only sees transport peers"
|
||||
);
|
||||
}
|
||||
guard.load()?;
|
||||
}
|
||||
let xdp_metrics = XdpMetrics::register()?;
|
||||
let filter = XdpFilter::new(&config.xdp.interface);
|
||||
let shared = Arc::new(Mutex::new(filter));
|
||||
{
|
||||
let mut guard = shared.lock().expect("xdp lock poisoned");
|
||||
let globals = XdpGlobals::from_config(&config.xdp)?;
|
||||
guard.set_globals(globals);
|
||||
// With ingress PROXY protocol, XDP sees only the provider's transport
|
||||
// address, so its events must not trigger per-player or provider bans.
|
||||
if !config.proxy_protocol.ingress_enabled {
|
||||
// load() captures the blacklist and auto-ban policy in its ringbuf
|
||||
// callback, so set_autoban must happen first.
|
||||
guard.set_autoban(blacklist.clone(), &config.xdp);
|
||||
} else if config.xdp.auto_ban_enabled {
|
||||
tracing::warn!(
|
||||
"XDP auto-ban is disabled while inbound PROXY protocol is enabled; XDP only sees transport peers"
|
||||
);
|
||||
}
|
||||
guard.load()?;
|
||||
}
|
||||
let xdp_metrics = XdpMetrics::register()?;
|
||||
|
||||
let sd = shutdown_rx.clone();
|
||||
let shared_thread = shared.clone();
|
||||
std::thread::spawn(move || {
|
||||
while !*sd.borrow() {
|
||||
let guard = match shared_thread.lock() {
|
||||
Ok(g) => g,
|
||||
Err(_) => break,
|
||||
};
|
||||
guard.drain_events();
|
||||
if let Ok(stats) = guard.get_stats() {
|
||||
xdp_metrics.update(&stats);
|
||||
}
|
||||
drop(guard);
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
}
|
||||
if let Ok(mut guard) = shared_thread.lock() {
|
||||
guard.unload().ok();
|
||||
}
|
||||
});
|
||||
Ok(Some(shared))
|
||||
let sd = shutdown_rx.clone();
|
||||
let shared_thread = shared.clone();
|
||||
std::thread::spawn(move || {
|
||||
while !*sd.borrow() {
|
||||
let guard = match shared_thread.lock() {
|
||||
Ok(g) => g,
|
||||
Err(_) => break,
|
||||
};
|
||||
guard.drain_events();
|
||||
if let Ok(stats) = guard.get_stats() {
|
||||
xdp_metrics.update(&stats);
|
||||
}
|
||||
drop(guard);
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
}
|
||||
if let Ok(mut guard) = shared_thread.lock() {
|
||||
guard.unload().ok();
|
||||
}
|
||||
});
|
||||
Ok(Some(shared))
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "xdp"))]
|
||||
pub(crate) fn start_xdp(
|
||||
_config: &Arc<Config>,
|
||||
_shutdown_rx: &watch::Receiver<bool>,
|
||||
_blacklist: &Arc<Blacklist>,
|
||||
_config: &Arc<Config>,
|
||||
_shutdown_rx: &watch::Receiver<bool>,
|
||||
_blacklist: &Arc<Blacklist>,
|
||||
) -> anyhow::Result<Option<Arc<Mutex<XdpFilter>>>> {
|
||||
Ok(None)
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Юзерспейс-агрегатор префиксов: активен, когда detect.prefix включён,
|
||||
/// а XDP-путь не работает (не собран или выключен в конфиге).
|
||||
pub(crate) fn start_subnet_tracker(config: &Config) -> Option<Arc<SubnetTracker>> {
|
||||
let xdp_active = cfg!(feature = "xdp") && config.xdp.enabled;
|
||||
if config.detect.prefix.enabled && !xdp_active {
|
||||
tracing::info!(
|
||||
window_secs = config.detect.prefix.window_secs,
|
||||
syn_threshold = config.detect.prefix.syn_threshold,
|
||||
"subnet tracker enabled (userspace prefix aggregation)"
|
||||
);
|
||||
Some(Arc::new(SubnetTracker::new()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
let xdp_active = cfg!(feature = "xdp") && config.xdp.enabled;
|
||||
if config.detect.prefix.enabled && !xdp_active {
|
||||
tracing::info!(
|
||||
window_secs = config.detect.prefix.window_secs,
|
||||
syn_threshold = config.detect.prefix.syn_threshold,
|
||||
"subnet tracker enabled (userspace prefix aggregation)"
|
||||
);
|
||||
Some(Arc::new(SubnetTracker::new()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Store-фичи проверяются на старте edge-демона: конфиг, запрашивающий redis,
|
||||
|
|
@ -137,71 +137,71 @@ pub(crate) fn start_subnet_tracker(config: &Config) -> Option<Arc<SubnetTracker>
|
|||
/// Точка вызова — `build_whitelist`: ближайший `?`-хук, принимающий конфиг
|
||||
/// до бинда listener'а (сам runtime.rs вне правок этой задачи).
|
||||
fn ensure_store_features(config: &Config) -> anyhow::Result<()> {
|
||||
#[cfg(not(feature = "store-redis"))]
|
||||
if config.store.redis_url.as_deref().is_some_and(|url| !url.is_empty()) {
|
||||
anyhow::bail!("[store].redis_url requires a redis-backed store: built without store-redis feature");
|
||||
}
|
||||
#[cfg(feature = "store-redis")]
|
||||
let _ = config;
|
||||
Ok(())
|
||||
#[cfg(not(feature = "store-redis"))]
|
||||
if config.store.redis_url.as_deref().is_some_and(|url| !url.is_empty()) {
|
||||
anyhow::bail!("[store].redis_url requires a redis-backed store: built without store-redis feature");
|
||||
}
|
||||
#[cfg(feature = "store-redis")]
|
||||
let _ = config;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn build_whitelist(config: &Config) -> anyhow::Result<Arc<HashSet<IpAddr>>> {
|
||||
ensure_store_features(config)?;
|
||||
let mut set = HashSet::with_capacity(config.whitelist.len());
|
||||
for entry in &config.whitelist {
|
||||
let ip: IpAddr = entry
|
||||
.parse()
|
||||
.map_err(|_| anyhow::anyhow!("invalid whitelist entry: {entry}"))?;
|
||||
set.insert(ip);
|
||||
}
|
||||
Ok(Arc::new(set))
|
||||
ensure_store_features(config)?;
|
||||
let mut set = HashSet::with_capacity(config.whitelist.len());
|
||||
for entry in &config.whitelist {
|
||||
let ip: IpAddr = entry
|
||||
.parse()
|
||||
.map_err(|_| anyhow::anyhow!("invalid whitelist entry: {entry}"))?;
|
||||
set.insert(ip);
|
||||
}
|
||||
Ok(Arc::new(set))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::*;
|
||||
|
||||
fn config_with_redis() -> Config {
|
||||
Config {
|
||||
store: crate::config::StoreConfig {
|
||||
redis_url: Some("redis://127.0.0.1:6379/0".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
fn config_with_redis() -> Config {
|
||||
Config {
|
||||
store: crate::config::StoreConfig {
|
||||
redis_url: Some("redis://127.0.0.1:6379/0".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "store-redis"))]
|
||||
#[test]
|
||||
fn redis_config_without_feature_fails_fast() {
|
||||
let err = ensure_store_features(&config_with_redis()).expect_err("must fail without store-redis");
|
||||
assert!(err.to_string().contains("built without store-redis feature"));
|
||||
}
|
||||
#[cfg(not(feature = "store-redis"))]
|
||||
#[test]
|
||||
fn redis_config_without_feature_fails_fast() {
|
||||
let err = ensure_store_features(&config_with_redis()).expect_err("must fail without store-redis");
|
||||
assert!(err.to_string().contains("built without store-redis feature"));
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "store-redis"))]
|
||||
#[test]
|
||||
fn empty_store_config_passes_without_feature() {
|
||||
assert!(ensure_store_features(&Config::default()).is_ok());
|
||||
}
|
||||
#[cfg(not(feature = "store-redis"))]
|
||||
#[test]
|
||||
fn empty_store_config_passes_without_feature() {
|
||||
assert!(ensure_store_features(&Config::default()).is_ok());
|
||||
}
|
||||
|
||||
#[cfg(feature = "store-redis")]
|
||||
#[test]
|
||||
fn guard_is_noop_with_feature() {
|
||||
assert!(ensure_store_features(&config_with_redis()).is_ok());
|
||||
}
|
||||
#[cfg(feature = "store-redis")]
|
||||
#[test]
|
||||
fn guard_is_noop_with_feature() {
|
||||
assert!(ensure_store_features(&config_with_redis()).is_ok());
|
||||
}
|
||||
|
||||
/// Wiring-тасовка XDP auto-ban: `start_xdp` обязан принимать `Arc<Blacklist>`
|
||||
/// (т.е. существовать в сигнатуре с blacklist) и при выключенном `[xdp]`
|
||||
/// не трогать ни ядро, ни blacklist. Порядок `set_autoban` -> `load()`
|
||||
/// внутри enabled-ветки без ядра непроверяем — см. комментарий на месте вызова.
|
||||
#[test]
|
||||
fn start_xdp_accepts_blacklist_and_skips_kernel_when_disabled() {
|
||||
let (_tx, rx) = watch::channel(false);
|
||||
let blacklist = Arc::new(Blacklist::new());
|
||||
let started = start_xdp(&Arc::new(Config::default()), &rx, &blacklist)
|
||||
.expect("xdp disabled: no kernel work and no error");
|
||||
assert!(started.is_none());
|
||||
assert!(blacklist.is_empty());
|
||||
}
|
||||
/// Wiring-тасовка XDP auto-ban: `start_xdp` обязан принимать `Arc<Blacklist>`
|
||||
/// (т.е. существовать в сигнатуре с blacklist) и при выключенном `[xdp]`
|
||||
/// не трогать ни ядро, ни blacklist. Порядок `set_autoban` -> `load()`
|
||||
/// внутри enabled-ветки без ядра непроверяем — см. комментарий на месте вызова.
|
||||
#[test]
|
||||
fn start_xdp_accepts_blacklist_and_skips_kernel_when_disabled() {
|
||||
let (_tx, rx) = watch::channel(false);
|
||||
let blacklist = Arc::new(Blacklist::new());
|
||||
let started = start_xdp(&Arc::new(Config::default()), &rx, &blacklist)
|
||||
.expect("xdp disabled: no kernel work and no error");
|
||||
assert!(started.is_none());
|
||||
assert!(blacklist.is_empty());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,22 +9,22 @@ use tokio::sync::watch;
|
|||
/// поэтому библиотечный код остаётся свободным от lint `exit`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RunExit {
|
||||
/// Listener отработал штатно: drain уложился в таймаут.
|
||||
Ok,
|
||||
/// Истёк drain-таймаут: бинарь обязан завершить процесс немедленно
|
||||
/// (замена прежнему `process::exit(0)` внутри shutdown-таймера).
|
||||
DrainTimeout,
|
||||
/// Listener отработал штатно: drain уложился в таймаут.
|
||||
Ok,
|
||||
/// Истёк drain-таймаут: бинарь обязан завершить процесс немедленно
|
||||
/// (замена прежнему `process::exit(0)` внутри shutdown-таймера).
|
||||
DrainTimeout,
|
||||
}
|
||||
|
||||
impl RunExit {
|
||||
/// Код завершения процесса для данного результата.
|
||||
#[must_use]
|
||||
pub const fn code(self) -> i32 {
|
||||
match self {
|
||||
Self::Ok => 0,
|
||||
Self::DrainTimeout => 0,
|
||||
}
|
||||
}
|
||||
/// Код завершения процесса для данного результата.
|
||||
#[must_use]
|
||||
pub const fn code(self) -> i32 {
|
||||
match self {
|
||||
Self::Ok => 0,
|
||||
Self::DrainTimeout => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ставит фоновую shutdown-задачу.
|
||||
|
|
@ -33,35 +33,35 @@ impl RunExit {
|
|||
/// бинарь, а здесь мы лишь уведомляем `run` об истечении drain-таймаута через
|
||||
/// oneshot-канал. Логи и тайминг (5s после сигнала) сохранены без изменений.
|
||||
pub(crate) fn spawn_shutdown_drain(shutdown_tx: watch::Sender<bool>, drain_tx: oneshot::Sender<()>) {
|
||||
tokio::spawn(async move {
|
||||
wait_for_signal().await;
|
||||
tracing::info!("shutdown signal received, draining connections...");
|
||||
let _ = shutdown_tx.send(true);
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
tracing::info!("shutdown timeout reached, exiting");
|
||||
let _ = drain_tx.send(());
|
||||
});
|
||||
tokio::spawn(async move {
|
||||
wait_for_signal().await;
|
||||
tracing::info!("shutdown signal received, draining connections...");
|
||||
let _ = shutdown_tx.send(true);
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
tracing::info!("shutdown timeout reached, exiting");
|
||||
let _ = drain_tx.send(());
|
||||
});
|
||||
}
|
||||
|
||||
async fn wait_for_signal() {
|
||||
let ctrl_c = tokio::signal::ctrl_c();
|
||||
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
|
||||
.expect("failed to install SIGTERM handler");
|
||||
let ctrl_c = tokio::signal::ctrl_c();
|
||||
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
|
||||
.expect("failed to install SIGTERM handler");
|
||||
|
||||
tokio::select! {
|
||||
_ = ctrl_c => {}
|
||||
_ = term.recv() => {}
|
||||
}
|
||||
tokio::select! {
|
||||
_ = ctrl_c => {}
|
||||
_ = term.recv() => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::RunExit;
|
||||
use super::RunExit;
|
||||
|
||||
#[test]
|
||||
fn run_exit_codes_match_previous_process_exit() {
|
||||
// Штатный путь и прежний drain-timeout (`process::exit(0)`) завершались с кодом 0.
|
||||
assert_eq!(RunExit::Ok.code(), 0);
|
||||
assert_eq!(RunExit::DrainTimeout.code(), 0);
|
||||
}
|
||||
#[test]
|
||||
fn run_exit_codes_match_previous_process_exit() {
|
||||
// Штатный путь и прежний drain-timeout (`process::exit(0)`) завершались с кодом 0.
|
||||
assert_eq!(RunExit::Ok.code(), 0);
|
||||
assert_eq!(RunExit::DrainTimeout.code(), 0);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue