feat(xdp): startup diagnostics with container detection, shared report and attach hints
This commit is contained in:
parent
4fc9b6eaf9
commit
2b4e32ed52
10 changed files with 197 additions and 48 deletions
|
|
@ -74,7 +74,7 @@ impl XdpFilter {
|
|||
/// attach failure no program is left installed.
|
||||
pub fn load(&mut self) -> Result<()> {
|
||||
// Diagnostics before loading: fail fast on an unsupported kernel or driver.
|
||||
super::probe::preflight(&self.interface)?;
|
||||
let report = super::probe::preflight(&self.interface)?;
|
||||
|
||||
let bpf_obj = include_bytes!(concat!(env!("OUT_DIR"), "/universal_filter.o"));
|
||||
// The object name is set explicitly: with `open_memory` libbpf does not know the
|
||||
|
|
@ -86,7 +86,12 @@ impl XdpFilter {
|
|||
.open_memory(bpf_obj)
|
||||
.context("Failed to open XDP object")?;
|
||||
patch_rodata(&mut open_obj, &self.globals)?;
|
||||
let obj = open_obj.load().context("Failed to load XDP object (verifier error?)")?;
|
||||
let obj = open_obj.load().with_context(|| {
|
||||
format!(
|
||||
"Failed to load XDP object (verifier error?); hint: {}",
|
||||
report.failure_hint()
|
||||
)
|
||||
})?;
|
||||
|
||||
let c_interface = interface_cstr(&self.interface)?;
|
||||
// SAFETY: `c_interface` is a valid, NUL-terminated C string and is kept
|
||||
|
|
@ -103,7 +108,14 @@ impl XdpFilter {
|
|||
super::metrics::init();
|
||||
let rbuf = build_ringbuf(&obj, self.blacklist.clone(), self.autoban)?;
|
||||
|
||||
let (attach_flags, mode, guard) = attach_program(&obj, ifindex as i32, &self.interface)?;
|
||||
let (attach_flags, mode, guard) = attach_program(&obj, ifindex as i32, &self.interface).with_context(|| {
|
||||
format!(
|
||||
"XDP attach to '{}' failed ({}); hint: {}",
|
||||
self.interface,
|
||||
report.verdict(),
|
||||
report.failure_hint()
|
||||
)
|
||||
})?;
|
||||
guard.disarm();
|
||||
|
||||
self.obj = Some(obj);
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
use anyhow::{Result, bail};
|
||||
|
||||
use super::types::{
|
||||
AttachMode, BTF_PATH, KernelVersion, MIN_KERNEL, OSRELEASE_PATH, SystemProbe, driver_from_link,
|
||||
driver_supports_native_xdp,
|
||||
AttachMode, BTF_PATH, KernelVersion, MIN_KERNEL, OSRELEASE_PATH, SystemProbe, container_blocks_xdp,
|
||||
detect_container, driver_from_link, driver_supports_native_xdp,
|
||||
};
|
||||
|
||||
/// Structured report on how suitable the environment is for XDP.
|
||||
|
|
@ -11,6 +11,8 @@ pub struct EnvironmentReport {
|
|||
pub btf_available: bool,
|
||||
pub privileged: bool,
|
||||
pub driver_name: Option<String>,
|
||||
/// Container the process runs in (`lxc`, `openvz`, `docker`, ...), if any.
|
||||
pub container: Option<String>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
|
|
@ -27,7 +29,15 @@ impl EnvironmentReport {
|
|||
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 container = detect_container(probe);
|
||||
|
||||
let mut warnings = Vec::new();
|
||||
if let Some(kind) = container.as_deref().filter(|k| container_blocks_xdp(k)) {
|
||||
warnings.push(format!(
|
||||
"запуск внутри контейнера '{kind}': гостю обычно недоступен BPF/XDP attach — \
|
||||
используйте KVM/bare metal или запускайте edge без [xdp]"
|
||||
));
|
||||
}
|
||||
if !privileged {
|
||||
warnings.push(
|
||||
"процесс не от root: CAP_BPF/CAP_NET_ADMIN не подтверждены, \
|
||||
|
|
@ -57,10 +67,65 @@ impl EnvironmentReport {
|
|||
btf_available,
|
||||
privileged,
|
||||
driver_name,
|
||||
container,
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
|
||||
/// Ordered `(label, value)` pairs describing the environment. Shared by the daemon
|
||||
/// log and `rampart-cli doctor`, so both print exactly the same facts.
|
||||
#[must_use]
|
||||
pub fn summary_fields(&self, interface: &str) -> Vec<(&'static str, String)> {
|
||||
vec![
|
||||
("interface", interface.to_owned()),
|
||||
(
|
||||
"kernel",
|
||||
self.kernel_version
|
||||
.map_or_else(|| "unknown".to_owned(), |v| v.to_string()),
|
||||
),
|
||||
("virt", self.container.clone().unwrap_or_else(|| "none/vm".to_owned())),
|
||||
(
|
||||
"btf",
|
||||
if self.btf_available { "available" } else { "missing" }.to_owned(),
|
||||
),
|
||||
(
|
||||
"privileges",
|
||||
if self.privileged { "root" } else { "non-root" }.to_owned(),
|
||||
),
|
||||
(
|
||||
"driver",
|
||||
self.driver_name.clone().unwrap_or_else(|| "unknown".to_owned()),
|
||||
),
|
||||
("expected_mode", self.expected_mode_label().to_owned()),
|
||||
]
|
||||
}
|
||||
|
||||
/// Predicted attach mode. Generic is spelled `generic (skb)` so it is never mistaken
|
||||
/// for driver-level XDP; the real mode is logged after attach.
|
||||
#[must_use]
|
||||
pub fn expected_mode_label(&self) -> &'static str {
|
||||
match self.attach_mode() {
|
||||
AttachMode::Native => "native (drv), prediction by driver table",
|
||||
AttachMode::Generic => "generic (skb)",
|
||||
AttachMode::Offload => "offload",
|
||||
}
|
||||
}
|
||||
|
||||
/// One-line hint appended to attach failures so `journalctl` explains what to do.
|
||||
#[must_use]
|
||||
pub fn failure_hint(&self) -> String {
|
||||
if let Some(kind) = self.container.as_deref().filter(|k| container_blocks_xdp(k)) {
|
||||
return format!("контейнер '{kind}' не поддерживает XDP: нужна KVM-VDS или bare metal");
|
||||
}
|
||||
if !self.privileged {
|
||||
return "запустите от root или выдайте CAP_BPF, CAP_NET_ADMIN, CAP_PERFMON".to_owned();
|
||||
}
|
||||
if !self.btf_available {
|
||||
return "ядро без BTF (/sys/kernel/btf/vmlinux): используйте ядро с CONFIG_DEBUG_INFO_BTF=y".to_owned();
|
||||
}
|
||||
"см. docs/troubleshooting.md, раздел «XDP не загружается»".to_owned()
|
||||
}
|
||||
|
||||
/// Expected attach mode according to the driver table.
|
||||
#[must_use]
|
||||
pub fn attach_mode(&self) -> AttachMode {
|
||||
|
|
@ -103,30 +168,26 @@ impl EnvironmentReport {
|
|||
}
|
||||
|
||||
/// 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.
|
||||
/// log, warnings, and a fail-fast check for an old kernel. Returns the report so the
|
||||
/// caller can attach it to a later attach failure.
|
||||
///
|
||||
/// # Errors
|
||||
/// See [`EnvironmentReport::validate`].
|
||||
#[cfg(feature = "xdp")]
|
||||
pub(crate) fn preflight(interface: &str) -> Result<()> {
|
||||
pub(crate) fn preflight(interface: &str) -> Result<EnvironmentReport> {
|
||||
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()
|
||||
);
|
||||
let fields = report
|
||||
.summary_fields(interface)
|
||||
.into_iter()
|
||||
.map(|(k, v)| format!("{k}={v}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
tracing::info!("XDP environment: {fields}; {}", report.verdict());
|
||||
for warning in &report.warnings {
|
||||
tracing::warn!(interface, "{warning}");
|
||||
}
|
||||
report.validate()
|
||||
report.validate()?;
|
||||
Ok(report)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,36 @@ pub(super) const OSRELEASE_PATH: &str = "/proc/sys/kernel/osrelease";
|
|||
pub(super) const BTF_PATH: &str = "/sys/kernel/btf/vmlinux";
|
||||
const STATUS_PATH: &str = "/proc/self/status";
|
||||
|
||||
pub(super) const SYSTEMD_CONTAINER_PATH: &str = "/run/systemd/container";
|
||||
const OPENVZ_PATH: &str = "/proc/vz";
|
||||
const OPENVZ_HOST_PATH: &str = "/proc/bc";
|
||||
const DOCKERENV_PATH: &str = "/.dockerenv";
|
||||
|
||||
/// Detects the container/virtualization layer the process runs in, if it is a container.
|
||||
///
|
||||
/// Returns the systemd container id (`lxc`, `docker`, ...) or `openvz`. Full VMs (KVM,
|
||||
/// VMware) are not reported: for XDP they only matter through the NIC driver.
|
||||
pub(super) fn detect_container(probe: &dyn SystemProbe) -> Option<String> {
|
||||
if let Ok(raw) = probe.read_file(SYSTEMD_CONTAINER_PATH) {
|
||||
let id = raw.trim();
|
||||
if !id.is_empty() {
|
||||
return Some(id.to_owned());
|
||||
}
|
||||
}
|
||||
// `/proc/vz` without `/proc/bc` is the guest side of OpenVZ/Virtuozzo.
|
||||
if probe.path_exists(OPENVZ_PATH) && !probe.path_exists(OPENVZ_HOST_PATH) {
|
||||
return Some("openvz".to_owned());
|
||||
}
|
||||
probe.path_exists(DOCKERENV_PATH).then(|| "docker".to_owned())
|
||||
}
|
||||
|
||||
/// Whether the container kind is known to block BPF/XDP attach (shared host kernel
|
||||
/// without BPF privileges for the guest).
|
||||
#[must_use]
|
||||
pub fn container_blocks_xdp(kind: &str) -> bool {
|
||||
matches!(kind, "openvz" | "lxc" | "lxc-libvirt")
|
||||
}
|
||||
|
||||
/// Drivers with known native XDP support (from the upstream kernel's native/generic
|
||||
/// matrices). Absence from this list does not mean support is missing, but for such
|
||||
/// drivers generic mode is predicted.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue