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.
This commit is contained in:
Loki 2026-11-15 23:50:52 +01:00
parent b64c329125
commit a8a3057719
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
104 changed files with 2155 additions and 1030 deletions

View file

@ -1,4 +1,8 @@
//! Циклы приложения: fetch-таска (tokio) и UI-цикл (tick + события клавиатуры).
//! Application loops: the fetch task (tokio) and the UI loop (tick plus
//! keyboard events).
//!
//! Owns the wiring between a [`Fetcher`] and the terminal: the fetch task never
//! draws and the UI loop never performs I/O beyond the terminal itself.
use std::sync::Arc;
use std::time::Duration;
@ -10,14 +14,14 @@ use crate::tui::prometheus::parse;
use crate::tui::state::AppState;
use crate::tui::ui;
/// Управляемые пользователем команды (клавиши).
/// Commands the user can trigger from the keyboard.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command {
Quit,
Refresh,
}
/// Маппинг клавиш: `q`/`Esc` — выход, `r` — обновить немедленно.
/// Key mapping: `q`/`Esc` quit, `r` refreshes immediately.
#[must_use]
pub fn handle_key(code: crossterm::event::KeyCode) -> Option<Command> {
match code {
@ -27,7 +31,7 @@ pub fn handle_key(code: crossterm::event::KeyCode) -> Option<Command> {
}
}
/// Приводит результат fetch к виду для [`AppState::apply_fetch`].
/// Converts a fetch result into the shape expected by [`AppState::apply_fetch`].
pub fn normalize(result: Result<String, FetchError>) -> Result<crate::tui::prometheus::MetricSet, String> {
match result {
Ok(body) => Ok(parse(&body)),
@ -36,7 +40,10 @@ pub fn normalize(result: Result<String, FetchError>) -> Result<crate::tui::prome
}
}
/// Фоновая задача: fetch → [`AppState`]. Ошибки сети пишутся в снапшот баннером.
/// Background task: fetch into [`AppState`].
///
/// Network failures are stored in the snapshot and rendered as an error banner,
/// so a dead endpoint degrades the view instead of ending the session.
pub async fn spawn_fetch_loop(fetcher: Arc<dyn Fetcher>, state: Arc<AppState>, refresh: Duration, notify: Arc<Notify>) {
loop {
let started = std::time::Instant::now();
@ -51,10 +58,11 @@ pub async fn spawn_fetch_loop(fetcher: Arc<dyn Fetcher>, state: Arc<AppState>, r
}
}
/// UI-цикл: рисует кадр каждые ~100 мс, обрабатывает клавиши.
/// UI loop: draws a frame roughly every 100 ms and handles key presses.
///
/// # Errors
/// Возвращает ошибку терминала (draw/poll) — вызывающий восстанавливает TTY.
/// Returns the terminal error from draw/poll; the caller is responsible for
/// restoring the TTY.
pub async fn run_ui(
terminal: &mut ratatui::Terminal<impl ratatui::backend::Backend<Error = std::io::Error>>,
state: Arc<AppState>,
@ -71,13 +79,13 @@ pub async fn run_ui(
}
}
/// Неблокирующее ожидание клавиши в течение `timeout`.
/// Non-blocking wait for a key press within `timeout`.
fn poll_command(timeout: Duration) -> std::io::Result<Option<Command>> {
if !crossterm::event::poll(timeout)? {
return Ok(None);
}
if let crossterm::event::Event::Key(key) = crossterm::event::read()? {
// Реагируем только на нажатие (не автоповтор/отпускание).
// React to presses only, ignoring auto-repeat and key releases.
if key.kind == crossterm::event::KeyEventKind::Press {
return Ok(handle_key(key.code));
}

View file

@ -1,38 +1,44 @@
//! Получение тела `/metrics`: трейт [`Fetcher`] для мока в тестах и HTTP-реализация.
//! Fetching of the `/metrics` body: the [`Fetcher`] trait for test mocks plus
//! the HTTP implementation.
//!
//! Owns the transport boundary of the TUI; parsing lives in
//! [`crate::tui::prometheus`].
use std::time::Duration;
use futures::future::BoxFuture;
use thiserror::Error;
/// Ошибка загрузки метрик.
/// Metrics fetch failure.
#[derive(Debug, Error, Clone)]
pub enum FetchError {
/// Сетевая ошибка / DNS / таймаут.
/// Network error, DNS failure or timeout.
#[error("network error: {0}")]
Network(String),
/// Endpoint ответил не-200 статусом.
/// The endpoint answered with a non-200 status.
#[error("http status {0}")]
Status(u16),
}
/// Абстракция источника exposition-текста Prometheus.
/// Abstraction over a source of Prometheus exposition text.
pub trait Fetcher: Send + Sync {
/// Загружает текущий срез метрик.
/// Fetches the current metrics snapshot.
///
/// # Errors
/// Возвращает [`FetchError`] при сетевом сбое или плохом HTTP-статусе.
/// Returns [`FetchError`] on a network failure or a bad HTTP status.
fn fetch(&self) -> BoxFuture<'_, Result<String, FetchError>>;
}
/// Реализация [`Fetcher`] поверх reqwest GET.
/// [`Fetcher`] implementation on top of a reqwest GET.
pub struct HttpFetcher {
url: String,
client: reqwest::Client,
}
impl HttpFetcher {
/// Создаёт fetcher с таймаутом запроса 5 секунд.
/// Creates a fetcher with a 5 second request timeout.
///
/// Returns `None` when the HTTP client cannot be built.
pub fn new(url: impl Into<String>) -> Option<Self> {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(5))

View file

@ -1,3 +1,6 @@
//! Метрики TUI: парсер Prometheus-exposition и fetcher эндпоинтов.
//! TUI metrics: the Prometheus exposition parser and the endpoint fetchers.
//!
//! Owns the read-only side of the TUI: turning `/metrics` text into a
//! [`prometheus::MetricSet`] and pulling the body over HTTP (or a test mock).
pub mod fetch;
pub mod prometheus;

View file

@ -1,12 +1,13 @@
//! Минималистичный парсер текстового формата Prometheus (version=0.0.4).
//! Minimal parser for the Prometheus text exposition format (version 0.0.4).
//!
//! Поддерживает: комментарии (`# HELP`, `# TYPE`, `#`), строки вида
//! `metric{label="value",...} value [timestamp]` и `metric value [timestamp]`.
//! Значения `NaN`/`+Inf`/`-Inf` парсятся штатно через `f64::from_str`.
//! Owns the parsing rules for `/metrics` bodies. Accepts comment lines
//! (`# HELP`, `# TYPE`, `#`), `metric{label="value",...} value [timestamp]` and
//! `metric value [timestamp]`. `NaN`/`+Inf`/`-Inf` are parsed through
//! `f64::from_str`.
use std::collections::BTreeMap;
/// Один сэмпл из exposition-формата Prometheus.
/// One sample from the Prometheus exposition format.
#[derive(Debug, Clone, PartialEq)]
pub struct MetricSample {
pub name: String,
@ -14,21 +15,23 @@ pub struct MetricSample {
pub value: f64,
}
/// Набор сэмплов одного ответа `/metrics`.
/// All samples of a single `/metrics` response.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct MetricSet {
samples: Vec<MetricSample>,
}
impl MetricSet {
/// Сумма значений всех серий с данным именем (для counter/gauge vec).
/// Отсутствующая метрика даёт `0.0`.
/// Sums the values of every series with this name (for counter/gauge vecs).
///
/// A missing metric yields `0.0`.
#[must_use]
pub fn sum(&self, name: &str) -> f64 {
self.samples.iter().filter(|s| s.name == name).map(|s| s.value).sum()
}
/// Значение серии с именем и одной меткой; `None`, если не найдено.
/// Value of the series with this name carrying `label == value`, or `None`
/// when no such series exists.
#[must_use]
pub fn labeled(&self, name: &str, label: &str, value: &str) -> Option<f64> {
self.samples
@ -37,17 +40,17 @@ impl MetricSet {
.map(|s| s.value)
}
/// Все сэмплы (для тестов и отладки).
/// All samples (for tests and debugging).
#[must_use]
pub fn samples(&self) -> &[MetricSample] {
&self.samples
}
}
/// Парсит тело ответа `/metrics`.
/// Parses a `/metrics` response body.
///
/// Строки с ошибкой формата пропускаются (exposition-поток может быть частично
/// повреждён — TUI не должен падать на этом).
/// Lines with a malformed format are skipped: an exposition stream may be
/// partially corrupted and the TUI must not die because of it.
#[must_use]
pub fn parse(input: &str) -> MetricSet {
let mut samples = Vec::new();
@ -64,18 +67,18 @@ fn parse_line(line: &str) -> Option<MetricSample> {
if line.is_empty() || line.starts_with('#') {
return None;
}
// Формат: metric[{labels}] value [timestamp]; значения меток могут
// содержать пробелы, поэтому голову отрезаем с учётом кавычек.
// Format: metric[{labels}] value [timestamp]. Label values may contain
// spaces, so the head has to be cut with quote awareness.
let (head, rest) = split_head_and_rest(line);
let value_str = rest.split_whitespace().next()?;
// Timestamp после value игнорируем.
// A timestamp after the value is irrelevant for the TUI and dropped.
let (name, labels) = split_metric(head)?;
let value = parse_value(value_str)?;
Some(MetricSample { name, labels, value })
}
/// Отделяет `metric{...}` от хвоста `value [timestamp]`.
/// Splits `metric{...}` from the trailing `value [timestamp]`.
fn split_head_and_rest(line: &str) -> (&str, &str) {
let Some(open) = line.find('{') else {
return match line.find(char::is_whitespace) {
@ -92,7 +95,7 @@ fn split_head_and_rest(line: &str) -> (&str, &str) {
}
}
/// Индекс `}` вне кавычек, начиная с позиции `from`.
/// Index of the `}` outside quotes, starting at `from`.
fn find_closing_brace(line: &str, from: usize) -> Option<usize> {
let mut in_quotes = false;
let mut escaped = false;
@ -138,7 +141,7 @@ fn parse_labels(inner: &str) -> BTreeMap<String, String> {
labels
}
/// Разбивает `a="1", b="2"` по запятым вне кавычек.
/// Splits `a="1", b="2"` on commas outside quotes.
fn split_label_pairs(inner: &str) -> Vec<&str> {
let mut parts = Vec::new();
let mut in_quotes = false;

View file

@ -1,7 +1,10 @@
//! TUI-модуль Rampart: live-метрики edge-ноды/manager в терминале (ratatui).
//! Rampart TUI: live edge-node and manager metrics in the terminal (ratatui).
//!
//! Используется бинарём `rampart-tui`; источник данных — Prometheus
//! exposition endpoint (`/metrics`).
//! Owns the terminal front end used by the `rampart-tui` binary; the data
//! source is the Prometheus exposition endpoint (`/metrics`).
//!
//! The fetch task and the render loop communicate only through
//! [`state::AppState`], so a slow or failing endpoint never blocks the UI.
pub mod app;
pub mod metrics;

View file

@ -1,4 +1,8 @@
//! Общее состояние TUI: последний срез метрик, история pps/drops, расчёт rate.
//! Shared TUI state: the last metrics snapshot, the pps/drops history and the
//! rate calculation.
//!
//! Owns the only hand-off point between the fetch task and the UI loop; every
//! accessor is mutex-guarded and tolerates a poisoned lock.
use std::collections::VecDeque;
use std::sync::Mutex;
@ -6,17 +10,17 @@ use std::time::Instant;
use crate::tui::prometheus::MetricSet;
/// Максимальная длина скользящего окна графика.
/// Maximum length of the chart's sliding window.
pub const HISTORY_CAPACITY: usize = 120;
/// Один сэмпл истории (значения — rates, единиц/сек).
/// A single history sample; the values are rates in units per second.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct HistoryPoint {
pub packets_per_sec: f64,
pub drops_per_sec: f64,
}
/// Скользящее окно истории фиксированной ёмкости.
/// Fixed-capacity sliding window of history samples.
#[derive(Debug, Clone)]
pub struct History {
points: VecDeque<HistoryPoint>,
@ -31,7 +35,7 @@ impl Default for History {
}
impl History {
/// Добавляет точку, вытесняя старейшую при переполнении окна.
/// Appends a point, evicting the oldest one once the window is full.
pub fn push(&mut self, point: HistoryPoint) {
if self.points.len() == HISTORY_CAPACITY {
self.points.pop_front();
@ -39,14 +43,14 @@ impl History {
self.points.push_back(point);
}
/// Точки в хронологическом порядке.
/// Points in chronological order.
#[must_use]
pub fn points(&self) -> &VecDeque<HistoryPoint> {
&self.points
}
}
/// Состояние приложения, общее между fetch-потоком и UI-циклом.
/// Application state shared between the fetch task and the UI loop.
#[derive(Debug)]
pub struct AppState {
url: String,
@ -56,7 +60,7 @@ pub struct AppState {
}
impl AppState {
/// Создаёт состояние с URL источника метрик (для статус-панели).
/// Creates the state for a metrics source URL (shown in the status panel).
#[must_use]
pub fn new(url: impl Into<String>) -> Self {
Self {
@ -67,14 +71,14 @@ impl AppState {
}
}
/// URL источника метрик.
/// URL of the metrics source.
#[must_use]
pub fn url(&self) -> &str {
&self.url
}
}
/// Последний успешный/неуспешный результат fetch.
/// Result of the latest successful or failed fetch.
#[derive(Debug, Default, Clone)]
pub struct Snapshot {
pub metrics: Option<MetricSet>,
@ -83,7 +87,7 @@ pub struct Snapshot {
}
impl AppState {
/// Записывает результат очередного fetch и обновляет историю rate.
/// Records the result of the latest fetch and extends the rate history.
pub fn apply_fetch(&self, result: Result<MetricSet, String>, elapsed_secs: f64) {
let mut snapshot = match self.snapshot.lock() {
Ok(guard) => guard,
@ -119,9 +123,9 @@ impl AppState {
}
}
/// Копия среза метрик + истории для отрисовки кадра.
/// Copy of the metrics snapshot plus history for rendering one frame.
///
/// UI не держит лок — рисуем по снимку.
/// The UI never holds a lock: it draws from the copy.
#[must_use]
pub fn frame_data(&self) -> FrameData {
let snapshot = self.snapshot.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
@ -139,21 +143,21 @@ impl AppState {
}
}
/// Снимок для одного кадра UI.
/// Snapshot consumed by a single UI frame.
#[derive(Debug, Default, Clone)]
pub struct FrameData {
/// URL источника метрик.
/// URL of the metrics source.
pub url: String,
pub snapshot: Snapshot,
pub history: History,
/// Время работы TUI (сек).
/// TUI uptime in seconds.
pub uptime_secs: u64,
}
/// Rate счётчика из двух сэмплов: `(current - previous) / dt`.
/// Counter rate from two samples: `(current - previous) / dt`.
///
/// `None` у предыдущего значения (первый сэмпл) даёт 0.0. Сброс счётчика
/// (`current < previous`) трактуетcя как рестарт процесса → 0.0.
/// A `None` previous value (first sample) yields 0.0. A counter reset
/// (`current < previous`) is treated as a process restart and also yields 0.0.
#[must_use]
pub fn counter_rate(previous: Option<f64>, current: Option<f64>, elapsed_secs: f64) -> f64 {
let (Some(previous), Some(current)) = (previous, current) else {

View file

@ -1,4 +1,7 @@
//! Отрисовка кадра ratatui: статус-панель, таблица счётчиков, график pps/drops, помощь.
//! ratatui frame rendering: status panel, counters table, pps/drops chart and
//! the key help line.
//!
//! Owns the visual layout only; all values come from [`FrameData`].
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
@ -9,7 +12,7 @@ use ratatui::widgets::{Axis, Block, Borders, Chart, Dataset, GraphType, Paragrap
use crate::tui::state::{FrameData, HistoryPoint};
/// Имена метрик edge/manager (см. src/metrics.rs и src/xdp/metrics.rs).
/// Edge/manager metric names (see src/metrics.rs and src/xdp/metrics.rs).
mod names {
pub const XDP_TOTAL: &str = "rampart_xdp_total";
pub const XDP_TCP: &str = "rampart_xdp_tcp";
@ -27,7 +30,7 @@ mod names {
pub const ATTACK_STATUS: &str = "rampart_attack_status";
}
/// Рисует весь кадр.
/// Draws the whole frame.
pub fn render(frame: &mut Frame, data: &FrameData) {
let [header, body, help] =
Layout::vertical([Constraint::Length(3), Constraint::Min(3), Constraint::Length(1)]).areas(frame.area());
@ -69,7 +72,7 @@ fn render_header(frame: &mut Frame, area: Rect, data: &FrameData) {
frame.render_widget(Paragraph::new(line).block(Block::new().borders(Borders::ALL)), area);
}
/// Пары «подпись → имя метрики» для таблицы.
/// Counter label to metric name pairs for the table.
const COUNTER_ROWS: &[(&str, &str)] = &[
("XDP total", names::XDP_TOTAL),
("XDP tcp", names::XDP_TCP),