Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
321 changes: 321 additions & 0 deletions data_plane/examples/packets_bench.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,321 @@
//! Packet table bench, in process: the network eval's `packets` table fed
//! as Remote Write rows (one sample per packet, as the eval's feeder sends
//! them: labels `dst_ip, dst_port, proto, src_ip, src_p16, src_p24`, value
//! = bytes), then an intent's rounds. Measures what the table layout
//! changes: ingest CPU and wall time per row, raw bytes, series interned,
//! peak RSS, and each query's latency per round. Writes every round's
//! answers to `ANSWERS_OUT` (JSON lines) so two layouts can be compared.
//!
//! `ROWS` is a `net_dump` file: 24-byte little-endian records in time
//! order (ts_ms i64 since the stream epoch, src u32, dst u32, sport u16,
//! dport u16, proto u8, pad u8, bytes u16). Rows of `[0, FEED_S)` are fed
//! unpaced in 250 ms requests (encoded on their own thread, `encoder`,
//! not counted as engine CPU), the windows closed by a barrier at
//! `FEED_S`, then `ROUNDS` rounds 10 s apart ending at `FEED_S`.
//!
//! Environment: `TABLE_LAYOUTS=path.json` declares the tables' series keys
//! (`--table-layouts`); `INGEST_THREADS`, `QUERY_THREADS`; `ANSWERS_OUT`.
//!
//! `cargo run --release -p data_plane --example packets_bench -- INTENT_PLAN INTENT_NAME ROWS FEED_S [ROUNDS]`

#[global_allocator]
static ALLOCATOR: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;

use std::io::Write as _;
use std::sync::Arc;
use std::time::{Duration, Instant};

use axum::body::Body;
use axum::http::{Request, StatusCode};
use data_plane::engine::EngineOptions;
use data_plane::intent::{BindMode, IntentLoop, IntentPlan, IntentSchedule};
use data_plane::metrics::thread_cpu_seconds;
use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest};
use data_plane::{router, DataPlane};
use tower::ServiceExt;

/// Event time of the stream's epoch: 2023-11-14, a multiple of 10 s, in
/// the past (the data plane drops samples from the future).
const EPOCH_MS: i64 = 1_700_000_000_000;
const REQUEST_MS: i64 = 250;
const ROUND_MS: i64 = 10_000;

struct Packet {
ts_ms: i64,
src: u32,
dst: u32,
dport: u16,
proto: u8,
bytes: u16,
}

fn packets(path: &str, feed_ms: i64) -> Vec<Packet> {
let data = std::fs::read(path).unwrap();
data.chunks_exact(24)
.map(|r| Packet {
ts_ms: i64::from_le_bytes(r[0..8].try_into().unwrap()),
src: u32::from_le_bytes(r[8..12].try_into().unwrap()),
dst: u32::from_le_bytes(r[12..16].try_into().unwrap()),
dport: u16::from_le_bytes(r[18..20].try_into().unwrap()),
proto: r[20],
bytes: u16::from_le_bytes(r[22..24].try_into().unwrap()),
})
.take_while(|p| p.ts_ms < feed_ms)
.collect()
}

/// One Remote Write request per 250 ms of rows, each row its own
/// `TimeSeries` (labels sorted by name, as the eval's feeder sends them).
fn encode_requests(rows: &[Packet], out: std::sync::mpsc::SyncSender<(usize, Vec<u8>)>) {
let mut start = 0;
while start < rows.len() {
let request_end = (rows[start].ts_ms / REQUEST_MS + 1) * REQUEST_MS;
let end = start + rows[start..].partition_point(|p| p.ts_ms < request_end);
let timeseries = rows[start..end]
.iter()
.map(|p| {
let labels = [
("__name__", "packets".to_string()),
("dst_ip", p.dst.to_string()),
("dst_port", p.dport.to_string()),
("proto", p.proto.to_string()),
("src_ip", p.src.to_string()),
("src_p16", (p.src / 65536).to_string()),
("src_p24", (p.src / 256).to_string()),
]
.into_iter()
.map(|(name, value)| Label {
name: name.into(),
value,
})
.collect();
TimeSeries {
labels,
samples: vec![Sample {
timestamp: EPOCH_MS + p.ts_ms,
value: p.bytes as f64,
}],
}
})
.collect();
if out
.send((end - start, encode(&WriteRequest { timeseries })))
.is_err()
{
return;
}
start = end;
}
}

/// Peak and current resident set, in MiB.
fn rss_mib() -> (f64, f64) {
let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default();
let field = |name: &str| {
status
.lines()
.find_map(|l| l.strip_prefix(name))
.and_then(|v| v.trim().trim_end_matches(" kB").trim().parse::<f64>().ok())
.map_or(0.0, |kb| kb / 1024.0)
};
(field("VmHWM:"), field("VmRSS:"))
}

fn metric(text: &str, name: &str) -> f64 {
text.lines()
.find_map(|l| l.strip_prefix(name).and_then(|v| v.trim().parse().ok()))
.unwrap_or(f64::NAN)
}

#[tokio::main(flavor = "multi_thread")]
async fn main() {
let args: Vec<String> = std::env::args().collect();
let plan: IntentPlan =
serde_json::from_str(&std::fs::read_to_string(&args[1]).unwrap()).unwrap();
let intent_name = &args[2];
let feed_ms = args[4].parse::<i64>().unwrap() * 1000;
let rounds: i64 = args.get(5).map_or(3, |a| a.parse().unwrap());
let env_usize = |name: &str| {
std::env::var(name)
.ok()
.map(|v| v.parse::<usize>().unwrap())
};

let loaded = Instant::now();
let rows = Arc::new(packets(&args[3], feed_ms));
println!(
"rows {} of [0, {} s) loaded in {:.1} s",
rows.len(),
feed_ms / 1000,
loaded.elapsed().as_secs_f64()
);

let mut options = EngineOptions {
no_forward: true,
..EngineOptions::default()
};
if let Some(threads) = env_usize("INGEST_THREADS") {
options.ingest_threads = threads;
}
if let Some(threads) = env_usize("QUERY_THREADS") {
options.query_threads = threads;
}
if let Ok(path) = std::env::var("TABLE_LAYOUTS") {
options.table_layouts = data_plane::table_layout::TableLayouts::from_json(
&std::fs::read_to_string(path).unwrap(),
)
.unwrap();
}
let state = Arc::new(
DataPlane::with_options(
serde_json::to_string(&plan.plan).unwrap(),
"http://127.0.0.1:1".into(),
options,
)
.unwrap(),
);
let app = router(state.clone());

// Ingest: unpaced, the bodies encoded ahead on their own thread.
let (sender, bodies) = std::sync::mpsc::sync_channel(64);
let encoder_rows = rows.clone();
std::thread::Builder::new()
.name("encoder".into())
.spawn(move || encode_requests(&encoder_rows, sender))
.unwrap();
let cpu_before = thread_cpu_seconds();
let started = Instant::now();
let (mut sent, mut retries, mut in_write) = (0usize, 0u64, Duration::ZERO);
while let Ok((count, body)) = bodies.recv() {
let body = axum::body::Bytes::from(body);
loop {
let call = Instant::now();
let response = app
.clone()
.oneshot(
Request::post("/api/v1/write")
.body(Body::from(body.clone()))
.unwrap(),
)
.await
.unwrap();
in_write += call.elapsed();
match response.status() {
StatusCode::NO_CONTENT => break,
StatusCode::SERVICE_UNAVAILABLE => {
retries += 1;
tokio::time::sleep(Duration::from_millis(1)).await;
}
status => panic!("Remote Write answered {status}"),
}
}
sent += count;
}
let acknowledged = started.elapsed().as_secs_f64();
while state.engine.queued_samples() > 0 {
tokio::time::sleep(Duration::from_millis(5)).await;
}
let appended = started.elapsed().as_secs_f64();
let barrier = app
.clone()
.oneshot(
Request::post(format!(
"/api/v1/precompute/watermark?time_ms={}",
EPOCH_MS + feed_ms
))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(barrier.status(), StatusCode::OK);
let refreshed = started.elapsed().as_secs_f64();
let cpu_after = thread_cpu_seconds();
let text = state.engine.render_metrics();
let (peak_mib, rss_mib_now) = rss_mib();
println!(
"ingest: {sent} rows; acknowledged {acknowledged:.2} s ({:.0} rows/s), appended {appended:.2} s, \
refreshed {refreshed:.2} s; in write handler {:.2} s; 503 retries {retries}",
sent as f64 / acknowledged,
in_write.as_secs_f64()
);
let mut engine_cpu = 0.0;
for (name, after) in &cpu_after {
let cpu = after - cpu_before.get(name).copied().unwrap_or(0.0);
if name != "encoder" {
engine_cpu += cpu;
}
if cpu > 0.05 {
println!(" cpu {name:<24} {cpu:8.2} s");
}
}
println!(
" engine cpu {engine_cpu:.2} s = {:.2} us/row; raw bytes {:.1} MiB ({:.1} B/row); \
raw samples {}; series interned {}; RSS peak {peak_mib:.0} MiB, now {rss_mib_now:.0} MiB \
(includes the bench's rows: {:.0} MiB)",
engine_cpu * 1e6 / sent.max(1) as f64,
metric(&text, "asap_raw_data_bytes") / 1048576.0,
metric(&text, "asap_raw_data_bytes") / sent.max(1) as f64,
metric(&text, "asap_raw_data_samples"),
data_plane::series_ids::interned_count(),
(rows.len() * std::mem::size_of::<Packet>()) as f64 / 1048576.0,
);

// Rounds, 10 s apart, the last at the barrier.
let schedule = IntentSchedule::per_clock_from_intent_plan(&plan, intent_name)
.unwrap()
.remove(0);
let intent =
IntentLoop::new(schedule, BindMode::ParameterSlot, Duration::from_secs(600)).unwrap();
let mut answers = std::env::var("ANSWERS_OUT")
.ok()
.map(|path| std::fs::File::create(path).unwrap());
for round in 0..rounds {
let time_ms = EPOCH_MS + feed_ms - (rounds - 1 - round) * ROUND_MS;
let cpu_before = thread_cpu_seconds();
let record = intent.run_round(&state.engine, round as u64, time_ms).await;
let cpu_after = thread_cpu_seconds();
let cpu: f64 = cpu_after
.iter()
.map(|(name, after)| after - cpu_before.get(name).copied().unwrap_or(0.0))
.sum();
let latencies: Vec<String> = record
.queries
.iter()
.map(|q| {
format!(
"{} {:?} {} rows {}",
q.query_id,
q.status,
q.latency_ms.map_or("-".into(), |l| format!("{l:.1} ms")),
q.answer.len()
)
})
.collect();
println!(
"round {round} at +{} s: {:.1} ms, cpu {cpu:.2} s; {}",
(time_ms - EPOCH_MS) / 1000,
record.duration_ms,
latencies.join("; ")
);
if let Some(file) = answers.as_mut() {
for q in &record.queries {
let mut rows: Vec<String> = q
.answer
.iter()
.map(|r| format!("{:?} {:?}", r.labels, r.value))
.collect();
rows.sort();
let line = serde_json::json!({
"round": round, "time_ms": time_ms, "query": q.query_id,
"status": format!("{:?}", q.status), "bindings": format!("{:?}", q.bindings),
"rows": rows,
});
writeln!(file, "{line}").unwrap();
}
}
}
let (peak_mib, _) = rss_mib();
println!("RSS peak after rounds {peak_mib:.0} MiB");
state.engine.stop();
}
12 changes: 12 additions & 0 deletions data_plane/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,14 @@ pub struct EngineOptions {
/// once per evaluation time, as the plan says; `false` computes it in
/// every query's run (for comparison).
pub share_one_evaluation_results: bool,
/// Raw reads return only the series a `Scan`'s label predicates
/// select ([`crate::label_selection`]); `false` reads every series in
/// the time range (for comparison). The answers are the same.
pub label_pushdown: bool,
/// The series key of each SQL table that declares one
/// (`--table-layouts`, [`crate::table_layout`]); other tables and
/// metrics keep one series per label set.
pub table_layouts: crate::table_layout::TableLayouts,
/// How long a query-time result is kept after its evaluation time,
/// counted back from the newest evaluation time computed.
pub query_time_results_retention_ms: u64,
Expand Down Expand Up @@ -215,6 +223,8 @@ impl Default for EngineOptions {
run_memory_limit_bytes: 4 << 30,
query_threads: std::thread::available_parallelism().map_or(1, usize::from),
share_one_evaluation_results: true,
label_pushdown: true,
table_layouts: Default::default(),
query_time_results_retention_ms: 60_000,
query_time_results_max_bytes: 1 << 30,
result_cache: true,
Expand Down Expand Up @@ -467,6 +477,7 @@ impl EngineHandle {
.map(|(width_ms, views)| (width_ms, views.iter().map(ToString::to_string).collect()))
.collect();
let mut metrics = Metrics::new(&groups, &query_texts);
let query = query.with_raw_reads(options.label_pushdown, metrics.query_raw_reads.clone());
if let Some(tier) = &tier {
let _ = metrics.view_tier.set(tier.clone());
}
Expand Down Expand Up @@ -2735,6 +2746,7 @@ mod tests {
labels: series,
timestamp_ms: 15_000,
value: 1.0,
fields: Box::default(),
};
let routed = ingestion.routing().route(vec![sample], 25_000);
assert_eq!(routed.accepted.len(), 1, "{:?}", routed.stats);
Expand Down
Loading