guard/src/xdp/probe/diagnostics/report.rs
loki5512344 a8a3057719
feat(xdp): IPv6 UDP rate limit, working loader; English comments and docs
XDP behaviour:
- udp_rate_limit6 (LRU, full 128-bit source key) plus throttle_hit6, so
  udp_policy = "rate-limit" applies to native IPv6 as well.
- scripts/xdp_ipv6_smoke.sh: phase 4 patches .rodata before load and
  verifies policy=2 on a real kernel (3 pass / 3 rate-limited).

Loader (XDP could never load before this):
- .rodata is one struct rampart_config with frozen offsets enforced by
  _Static_assert; XdpGlobals is #[repr(C)] and the image is built with
  offset_of!. Before, a 96-byte image was written into a 76-byte map at
  offsets clang had reordered, so load() failed with EINVAL.
- patch_rodata fails loudly when the map size and image size diverge.
- build.rs tracks xdp/core and xdp/hooks, not just universal_filter.c.
- build_ringbuf looked for "events_map"; the map is "events_ringbuf".
- tests/xdp_object_maps.rs checks map names and .rodata size without root.

Docs and style:
- Code comments are English, JavaDoc/Rustdoc style, without emoji or
  banners (new project rule, TODO §0.8).
- README rewritten bilingual: Russian first, English below, nav buttons,
  compact TOC and copy-paste quick start.
- docs/README.md: documentation index and maintenance rules;
  configuration.md documents the whole [xdp] section and IPv4/IPv6
  coverage; testing.md covers the real-kernel smoke; stale links removed.
2026-11-15 23:50:52 +01:00

132 lines
4.4 KiB
Rust

use anyhow::{Result, bail};
use super::types::{
AttachMode, BTF_PATH, KernelVersion, MIN_KERNEL, OSRELEASE_PATH, SystemProbe, driver_from_link,
driver_supports_native_xdp,
};
/// Structured report on how suitable the environment is for XDP.
pub struct EnvironmentReport {
pub kernel_version: Option<KernelVersion>,
pub btf_available: bool,
pub privileged: bool,
pub driver_name: Option<String>,
pub warnings: Vec<String>,
}
impl EnvironmentReport {
/// Collects the report through any [`SystemProbe`] implementation.
#[must_use]
pub fn collect(probe: &dyn SystemProbe, interface: &str) -> Self {
let kernel_version = probe
.read_file(OSRELEASE_PATH)
.ok()
.and_then(|r| KernelVersion::parse(r.trim()));
let btf_available = probe.path_exists(BTF_PATH);
let privileged = probe.effective_uid() == 0;
let driver_link = probe.symlink_target(&format!("/sys/class/net/{interface}/device/driver"));
let driver_name = driver_link.as_deref().and_then(driver_from_link);
let mut warnings = Vec::new();
if !privileged {
warnings.push(
"процесс не от root: CAP_BPF/CAP_NET_ADMIN не подтверждены, \
attach скорее всего завершится EPERM"
.to_owned(),
);
}
if !btf_available {
warnings.push(format!(
"{BTF_PATH} недоступен: CO-RE релокации невозможны, переносимость BPF-программы ограничена"
));
}
if kernel_version.is_some_and(|v| v < KernelVersion::new(5, 11, 0)) {
warnings.push(
"ядро < 5.11: память BPF-карт ограничена RLIMIT_MEMLOCK — увеличьте `ulimit -l` или обновите ядро"
.to_owned(),
);
}
if driver_name.is_none() {
warnings.push(format!(
"драйвер интерфейса '{interface}' не определён (нет device/driver symlink): ожидается generic mode"
));
}
Self {
kernel_version,
btf_available,
privileged,
driver_name,
warnings,
}
}
/// Expected attach mode according to the driver table.
#[must_use]
pub fn attach_mode(&self) -> AttachMode {
match self.driver_name.as_deref() {
Some(driver) if driver_supports_native_xdp(driver) => AttachMode::Native,
_ => AttachMode::Generic,
}
}
/// Human-readable explanation of the verdict.
#[must_use]
pub fn verdict(&self) -> String {
let kernel = self
.kernel_version
.map_or_else(|| "неизвестна".to_owned(), |v| v.to_string());
match (self.attach_mode(), self.driver_name.as_deref()) {
(AttachMode::Native, Some(driver)) => format!(
"ядро {kernel}: драйвер '{driver}' поддерживает native XDP — программа работает в драйвере, минимальные накладные расходы"
),
(_, driver) => format!(
"ядро {kernel}: драйвер '{}' не поддерживает native XDP → будет generic mode, CPU дороже",
driver.unwrap_or("неизвестный")
),
}
}
/// Fail-fast check of the minimum kernel version.
///
/// # Errors
/// The kernel version is unknown or below [`MIN_KERNEL`].
pub fn validate(&self) -> Result<()> {
let Some(version) = self.kernel_version else {
bail!("не удалось определить версию ядра ({OSRELEASE_PATH}) — XDP attach отклонён");
};
if version < MIN_KERNEL {
bail!("ядро {version} ниже минимально поддерживаемой {MIN_KERNEL}: XDP attach отклонён, обновите ядро");
}
Ok(())
}
}
/// Pre-attach diagnostics before the XDP program is loaded: a structured report in the
/// log, warnings, and a fail-fast check for an old kernel.
///
/// # Errors
/// See [`EnvironmentReport::validate`].
#[cfg(feature = "xdp")]
pub(crate) fn preflight(interface: &str) -> Result<()> {
use super::types::FilesystemProbe;
let report = EnvironmentReport::collect(&FilesystemProbe, interface);
let kernel = report
.kernel_version
.map_or_else(|| "unknown".to_owned(), |v| v.to_string());
tracing::info!(
interface,
kernel = %kernel,
btf = report.btf_available,
privileged = report.privileged,
driver = report.driver_name.as_deref().unwrap_or("unknown"),
mode = %report.attach_mode(),
"XDP environment: {}",
report.verdict()
);
for warning in &report.warnings {
tracing::warn!(interface, "{warning}");
}
report.validate()
}