Line data Source code
1 : use std::collections::{HashSet, VecDeque};
2 : use std::future::Future;
3 : use std::num::NonZeroUsize;
4 : use std::pin::Pin;
5 : use std::sync::atomic::{AtomicU64, Ordering};
6 : use std::sync::{Arc, Mutex};
7 : use std::time::{Duration, Instant};
8 :
9 : use anyhow::Context;
10 : use camino::Utf8PathBuf;
11 : use pageserver_api::key::Key;
12 : use pageserver_api::keyspace::KeySpaceAccum;
13 : use pageserver_api::models::{PagestreamGetPageRequest, PagestreamRequest};
14 : use pageserver_api::shard::TenantShardId;
15 : use rand::prelude::*;
16 : use tokio::task::JoinSet;
17 : use tokio_util::sync::CancellationToken;
18 : use tracing::info;
19 : use utils::id::TenantTimelineId;
20 : use utils::lsn::Lsn;
21 :
22 : use crate::util::tokio_thread_local_stats::AllThreadLocalStats;
23 : use crate::util::{request_stats, tokio_thread_local_stats};
24 :
25 : /// GetPage@LatestLSN, uniformly distributed across the compute-accessible keyspace.
26 : #[derive(clap::Parser)]
27 : pub(crate) struct Args {
28 : #[clap(long, default_value = "http://localhost:9898")]
29 0 : mgmt_api_endpoint: String,
30 : #[clap(long, default_value = "postgres://postgres@localhost:64000")]
31 0 : page_service_connstring: String,
32 : #[clap(long)]
33 : pageserver_jwt: Option<String>,
34 : #[clap(long, default_value = "1")]
35 0 : num_clients: NonZeroUsize,
36 : #[clap(long)]
37 : runtime: Option<humantime::Duration>,
38 : /// Each client sends requests at the given rate.
39 : ///
40 : /// If a request takes too long and we should be issuing a new request already,
41 : /// we skip that request and account it as `MISSED`.
42 : #[clap(long)]
43 : per_client_rate: Option<usize>,
44 : /// Probability for sending `latest=true` in the request (uniform distribution).
45 : #[clap(long, default_value = "1")]
46 0 : req_latest_probability: f64,
47 : #[clap(long)]
48 : limit_to_first_n_targets: Option<usize>,
49 : /// For large pageserver installations, enumerating the keyspace takes a lot of time.
50 : /// If specified, the specified path is used to maintain a cache of the keyspace enumeration result.
51 : /// The cache is tagged and auto-invalided by the tenant/timeline ids only.
52 : /// It doesn't get invalidated if the keyspace changes under the hood, e.g., due to new ingested data or compaction.
53 : #[clap(long)]
54 : keyspace_cache: Option<Utf8PathBuf>,
55 : /// Before starting the benchmark, live-reconfigure the pageserver to use the given
56 : /// [`pageserver_api::models::virtual_file::IoEngineKind`].
57 : #[clap(long)]
58 : set_io_engine: Option<pageserver_api::models::virtual_file::IoEngineKind>,
59 :
60 : /// Before starting the benchmark, live-reconfigure the pageserver to use specified io mode (buffered vs. direct).
61 : #[clap(long)]
62 : set_io_mode: Option<pageserver_api::models::virtual_file::IoMode>,
63 :
64 : /// Queue depth generated in each client.
65 : #[clap(long, default_value = "1")]
66 0 : queue_depth: NonZeroUsize,
67 :
68 0 : targets: Option<Vec<TenantTimelineId>>,
69 : }
70 :
71 : #[derive(Debug, Default)]
72 : struct LiveStats {
73 : completed_requests: AtomicU64,
74 : missed: AtomicU64,
75 : }
76 :
77 : impl LiveStats {
78 0 : fn request_done(&self) {
79 0 : self.completed_requests.fetch_add(1, Ordering::Relaxed);
80 0 : }
81 0 : fn missed(&self, n: u64) {
82 0 : self.missed.fetch_add(n, Ordering::Relaxed);
83 0 : }
84 : }
85 :
86 0 : #[derive(Clone, serde::Serialize, serde::Deserialize)]
87 : struct KeyRange {
88 : timeline: TenantTimelineId,
89 : timeline_lsn: Lsn,
90 : start: i128,
91 : end: i128,
92 : }
93 :
94 : impl KeyRange {
95 0 : fn len(&self) -> i128 {
96 0 : self.end - self.start
97 0 : }
98 : }
99 :
100 : #[derive(PartialEq, Eq, Hash, Copy, Clone)]
101 : struct WorkerId {
102 : timeline: TenantTimelineId,
103 : num_client: usize, // from 0..args.num_clients
104 : }
105 :
106 : #[derive(serde::Serialize)]
107 : struct Output {
108 : total: request_stats::Output,
109 : }
110 :
111 : tokio_thread_local_stats::declare!(STATS: request_stats::Stats);
112 :
113 0 : pub(crate) fn main(args: Args) -> anyhow::Result<()> {
114 0 : tokio_thread_local_stats::main!(STATS, move |thread_local_stats| {
115 0 : main_impl(args, thread_local_stats)
116 0 : })
117 0 : }
118 :
119 0 : async fn main_impl(
120 0 : args: Args,
121 0 : all_thread_local_stats: AllThreadLocalStats<request_stats::Stats>,
122 0 : ) -> anyhow::Result<()> {
123 0 : let args: &'static Args = Box::leak(Box::new(args));
124 :
125 0 : let mgmt_api_client = Arc::new(pageserver_client::mgmt_api::Client::new(
126 0 : args.mgmt_api_endpoint.clone(),
127 0 : args.pageserver_jwt.as_deref(),
128 0 : None, // TODO: support ssl_ca_file for https APIs in pagebench.
129 0 : )?);
130 :
131 0 : if let Some(engine_str) = &args.set_io_engine {
132 0 : mgmt_api_client.put_io_engine(engine_str).await?;
133 0 : }
134 :
135 0 : if let Some(mode) = &args.set_io_mode {
136 0 : mgmt_api_client.put_io_mode(mode).await?;
137 0 : }
138 :
139 : // discover targets
140 0 : let timelines: Vec<TenantTimelineId> = crate::util::cli::targets::discover(
141 0 : &mgmt_api_client,
142 0 : crate::util::cli::targets::Spec {
143 0 : limit_to_first_n_targets: args.limit_to_first_n_targets,
144 0 : targets: args.targets.clone(),
145 0 : },
146 0 : )
147 0 : .await?;
148 :
149 0 : #[derive(serde::Deserialize)]
150 : struct KeyspaceCacheDe {
151 : tag: Vec<TenantTimelineId>,
152 : data: Vec<KeyRange>,
153 : }
154 : #[derive(serde::Serialize)]
155 : struct KeyspaceCacheSer<'a> {
156 : tag: &'a [TenantTimelineId],
157 : data: &'a [KeyRange],
158 : }
159 0 : let cache = args
160 0 : .keyspace_cache
161 0 : .as_ref()
162 0 : .map(|keyspace_cache_file| {
163 0 : let contents = match std::fs::read(keyspace_cache_file) {
164 0 : Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
165 0 : return anyhow::Ok(None);
166 : }
167 0 : x => x.context("read keyspace cache file")?,
168 : };
169 0 : let cache: KeyspaceCacheDe =
170 0 : serde_json::from_slice(&contents).context("deserialize cache file")?;
171 0 : let tag_ok = HashSet::<TenantTimelineId>::from_iter(cache.tag.into_iter())
172 0 : == HashSet::from_iter(timelines.iter().cloned());
173 0 : info!("keyspace cache file matches tag: {tag_ok}");
174 0 : anyhow::Ok(if tag_ok { Some(cache.data) } else { None })
175 0 : })
176 0 : .transpose()?
177 0 : .flatten();
178 0 : let all_ranges: Vec<KeyRange> = if let Some(cached) = cache {
179 0 : info!("using keyspace cache file");
180 0 : cached
181 : } else {
182 0 : let mut js = JoinSet::new();
183 0 : for timeline in &timelines {
184 0 : js.spawn({
185 0 : let mgmt_api_client = Arc::clone(&mgmt_api_client);
186 0 : let timeline = *timeline;
187 0 : async move {
188 0 : let partitioning = mgmt_api_client
189 0 : .keyspace(
190 0 : TenantShardId::unsharded(timeline.tenant_id),
191 0 : timeline.timeline_id,
192 0 : )
193 0 : .await?;
194 0 : let lsn = partitioning.at_lsn;
195 0 : let start = Instant::now();
196 0 : let mut filtered = KeySpaceAccum::new();
197 : // let's hope this is inlined and vectorized...
198 : // TODO: turn this loop into a is_rel_block_range() function.
199 0 : for r in partitioning.keys.ranges.iter() {
200 0 : let mut i = r.start;
201 0 : while i != r.end {
202 0 : if i.is_rel_block_key() {
203 0 : filtered.add_key(i);
204 0 : }
205 0 : i = i.next();
206 : }
207 : }
208 0 : let filtered = filtered.to_keyspace();
209 0 : let filter_duration = start.elapsed();
210 0 :
211 0 : anyhow::Ok((
212 0 : filter_duration,
213 0 : filtered.ranges.into_iter().map(move |r| KeyRange {
214 0 : timeline,
215 0 : timeline_lsn: lsn,
216 0 : start: r.start.to_i128(),
217 0 : end: r.end.to_i128(),
218 0 : }),
219 0 : ))
220 0 : }
221 0 : });
222 0 : }
223 0 : let mut total_filter_duration = Duration::from_secs(0);
224 0 : let mut all_ranges: Vec<KeyRange> = Vec::new();
225 0 : while let Some(res) = js.join_next().await {
226 0 : let (filter_duration, range) = res.unwrap().unwrap();
227 0 : all_ranges.extend(range);
228 0 : total_filter_duration += filter_duration;
229 0 : }
230 0 : info!("filter duration: {}", total_filter_duration.as_secs_f64());
231 0 : if let Some(cachefile) = args.keyspace_cache.as_ref() {
232 0 : let cache = KeyspaceCacheSer {
233 0 : tag: &timelines,
234 0 : data: &all_ranges,
235 0 : };
236 0 : let bytes = serde_json::to_vec(&cache).context("serialize keyspace for cache file")?;
237 0 : std::fs::write(cachefile, bytes).context("write keyspace cache file to disk")?;
238 0 : info!("successfully wrote keyspace cache file");
239 0 : }
240 0 : all_ranges
241 : };
242 :
243 0 : let live_stats = Arc::new(LiveStats::default());
244 0 :
245 0 : let num_live_stats_dump = 1;
246 0 : let num_work_sender_tasks = args.num_clients.get() * timelines.len();
247 0 : let num_main_impl = 1;
248 0 :
249 0 : let start_work_barrier = Arc::new(tokio::sync::Barrier::new(
250 0 : num_live_stats_dump + num_work_sender_tasks + num_main_impl,
251 0 : ));
252 0 :
253 0 : tokio::spawn({
254 0 : let stats = Arc::clone(&live_stats);
255 0 : let start_work_barrier = Arc::clone(&start_work_barrier);
256 0 : async move {
257 0 : start_work_barrier.wait().await;
258 : loop {
259 0 : let start = std::time::Instant::now();
260 0 : tokio::time::sleep(std::time::Duration::from_secs(1)).await;
261 0 : let completed_requests = stats.completed_requests.swap(0, Ordering::Relaxed);
262 0 : let missed = stats.missed.swap(0, Ordering::Relaxed);
263 0 : let elapsed = start.elapsed();
264 0 : info!(
265 0 : "RPS: {:.0} MISSED: {:.0}",
266 0 : completed_requests as f64 / elapsed.as_secs_f64(),
267 0 : missed as f64 / elapsed.as_secs_f64()
268 : );
269 : }
270 0 : }
271 0 : });
272 0 :
273 0 : let cancel = CancellationToken::new();
274 0 :
275 0 : let rps_period = args
276 0 : .per_client_rate
277 0 : .map(|rps_limit| Duration::from_secs_f64(1.0 / (rps_limit as f64)));
278 0 : let make_worker: &dyn Fn(WorkerId) -> Pin<Box<dyn Send + Future<Output = ()>>> = &|worker_id| {
279 0 : let live_stats = live_stats.clone();
280 0 : let start_work_barrier = start_work_barrier.clone();
281 0 : let ranges: Vec<KeyRange> = all_ranges
282 0 : .iter()
283 0 : .filter(|r| r.timeline == worker_id.timeline)
284 0 : .cloned()
285 0 : .collect();
286 0 : let weights =
287 0 : rand::distributions::weighted::WeightedIndex::new(ranges.iter().map(|v| v.len()))
288 0 : .unwrap();
289 0 :
290 0 : let cancel = cancel.clone();
291 0 : Box::pin(async move {
292 0 : let client =
293 0 : pageserver_client::page_service::Client::new(args.page_service_connstring.clone())
294 0 : .await
295 0 : .unwrap();
296 0 : let mut client = client
297 0 : .pagestream(worker_id.timeline.tenant_id, worker_id.timeline.timeline_id)
298 0 : .await
299 0 : .unwrap();
300 0 :
301 0 : start_work_barrier.wait().await;
302 0 : let client_start = Instant::now();
303 0 : let mut ticks_processed = 0;
304 0 : let mut inflight = VecDeque::new();
305 0 : while !cancel.is_cancelled() {
306 : // Detect if a request took longer than the RPS rate
307 0 : if let Some(period) = &rps_period {
308 0 : let periods_passed_until_now =
309 0 : usize::try_from(client_start.elapsed().as_micros() / period.as_micros())
310 0 : .unwrap();
311 0 :
312 0 : if periods_passed_until_now > ticks_processed {
313 0 : live_stats.missed((periods_passed_until_now - ticks_processed) as u64);
314 0 : }
315 0 : ticks_processed = periods_passed_until_now;
316 0 : }
317 :
318 0 : while inflight.len() < args.queue_depth.get() {
319 0 : let start = Instant::now();
320 0 : let req = {
321 0 : let mut rng = rand::thread_rng();
322 0 : let r = &ranges[weights.sample(&mut rng)];
323 0 : let key: i128 = rng.gen_range(r.start..r.end);
324 0 : let key = Key::from_i128(key);
325 0 : assert!(key.is_rel_block_key());
326 0 : let (rel_tag, block_no) = key
327 0 : .to_rel_block()
328 0 : .expect("we filter non-rel-block keys out above");
329 0 : PagestreamGetPageRequest {
330 0 : hdr: PagestreamRequest {
331 0 : reqid: 0,
332 0 : request_lsn: if rng.gen_bool(args.req_latest_probability) {
333 0 : Lsn::MAX
334 : } else {
335 0 : r.timeline_lsn
336 : },
337 0 : not_modified_since: r.timeline_lsn,
338 0 : },
339 0 : rel: rel_tag,
340 0 : blkno: block_no,
341 0 : }
342 0 : };
343 0 : client.getpage_send(req).await.unwrap();
344 0 : inflight.push_back(start);
345 : }
346 :
347 0 : let start = inflight.pop_front().unwrap();
348 0 : client.getpage_recv().await.unwrap();
349 0 : let end = Instant::now();
350 0 : live_stats.request_done();
351 0 : ticks_processed += 1;
352 0 : STATS.with(|stats| {
353 0 : stats
354 0 : .borrow()
355 0 : .lock()
356 0 : .unwrap()
357 0 : .observe(end.duration_since(start))
358 0 : .unwrap();
359 0 : });
360 :
361 0 : if let Some(period) = &rps_period {
362 0 : let next_at = client_start
363 0 : + Duration::from_micros(
364 0 : (ticks_processed) as u64 * u64::try_from(period.as_micros()).unwrap(),
365 0 : );
366 0 : tokio::time::sleep_until(next_at.into()).await;
367 0 : }
368 : }
369 0 : })
370 0 : };
371 :
372 0 : info!("spawning workers");
373 0 : let mut workers = JoinSet::new();
374 0 : for timeline in timelines.iter().cloned() {
375 0 : for num_client in 0..args.num_clients.get() {
376 0 : let worker_id = WorkerId {
377 0 : timeline,
378 0 : num_client,
379 0 : };
380 0 : workers.spawn(make_worker(worker_id));
381 0 : }
382 : }
383 0 : let workers = async move {
384 0 : while let Some(res) = workers.join_next().await {
385 0 : res.unwrap();
386 0 : }
387 0 : };
388 :
389 0 : info!("waiting for everything to become ready");
390 0 : start_work_barrier.wait().await;
391 0 : info!("work started");
392 0 : if let Some(runtime) = args.runtime {
393 0 : tokio::time::sleep(runtime.into()).await;
394 0 : info!("runtime over, signalling cancellation");
395 0 : cancel.cancel();
396 0 : workers.await;
397 0 : info!("work sender exited");
398 : } else {
399 0 : workers.await;
400 0 : unreachable!("work sender never terminates");
401 : }
402 :
403 0 : let output = Output {
404 : total: {
405 0 : let mut agg_stats = request_stats::Stats::new();
406 0 : for stats in all_thread_local_stats.lock().unwrap().iter() {
407 0 : let stats = stats.lock().unwrap();
408 0 : agg_stats.add(&stats);
409 0 : }
410 0 : agg_stats.output()
411 0 : },
412 0 : };
413 0 :
414 0 : let output = serde_json::to_string_pretty(&output).unwrap();
415 0 : println!("{output}");
416 0 :
417 0 : anyhow::Ok(())
418 0 : }
|