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 0 :
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 : ));
129 :
130 0 : if let Some(engine_str) = &args.set_io_engine {
131 0 : mgmt_api_client.put_io_engine(engine_str).await?;
132 0 : }
133 :
134 0 : if let Some(mode) = &args.set_io_mode {
135 0 : mgmt_api_client.put_io_mode(mode).await?;
136 0 : }
137 :
138 : // discover targets
139 0 : let timelines: Vec<TenantTimelineId> = crate::util::cli::targets::discover(
140 0 : &mgmt_api_client,
141 0 : crate::util::cli::targets::Spec {
142 0 : limit_to_first_n_targets: args.limit_to_first_n_targets,
143 0 : targets: args.targets.clone(),
144 0 : },
145 0 : )
146 0 : .await?;
147 :
148 0 : #[derive(serde::Deserialize)]
149 : struct KeyspaceCacheDe {
150 : tag: Vec<TenantTimelineId>,
151 : data: Vec<KeyRange>,
152 : }
153 : #[derive(serde::Serialize)]
154 : struct KeyspaceCacheSer<'a> {
155 : tag: &'a [TenantTimelineId],
156 : data: &'a [KeyRange],
157 : }
158 0 : let cache = args
159 0 : .keyspace_cache
160 0 : .as_ref()
161 0 : .map(|keyspace_cache_file| {
162 0 : let contents = match std::fs::read(keyspace_cache_file) {
163 0 : Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
164 0 : return anyhow::Ok(None);
165 : }
166 0 : x => x.context("read keyspace cache file")?,
167 : };
168 0 : let cache: KeyspaceCacheDe =
169 0 : serde_json::from_slice(&contents).context("deserialize cache file")?;
170 0 : let tag_ok = HashSet::<TenantTimelineId>::from_iter(cache.tag.into_iter())
171 0 : == HashSet::from_iter(timelines.iter().cloned());
172 0 : info!("keyspace cache file matches tag: {tag_ok}");
173 0 : anyhow::Ok(if tag_ok { Some(cache.data) } else { None })
174 0 : })
175 0 : .transpose()?
176 0 : .flatten();
177 0 : let all_ranges: Vec<KeyRange> = if let Some(cached) = cache {
178 0 : info!("using keyspace cache file");
179 0 : cached
180 : } else {
181 0 : let mut js = JoinSet::new();
182 0 : for timeline in &timelines {
183 0 : js.spawn({
184 0 : let mgmt_api_client = Arc::clone(&mgmt_api_client);
185 0 : let timeline = *timeline;
186 0 : async move {
187 0 : let partitioning = mgmt_api_client
188 0 : .keyspace(
189 0 : TenantShardId::unsharded(timeline.tenant_id),
190 0 : timeline.timeline_id,
191 0 : )
192 0 : .await?;
193 0 : let lsn = partitioning.at_lsn;
194 0 : let start = Instant::now();
195 0 : let mut filtered = KeySpaceAccum::new();
196 : // let's hope this is inlined and vectorized...
197 : // TODO: turn this loop into a is_rel_block_range() function.
198 0 : for r in partitioning.keys.ranges.iter() {
199 0 : let mut i = r.start;
200 0 : while i != r.end {
201 0 : if i.is_rel_block_key() {
202 0 : filtered.add_key(i);
203 0 : }
204 0 : i = i.next();
205 : }
206 : }
207 0 : let filtered = filtered.to_keyspace();
208 0 : let filter_duration = start.elapsed();
209 0 :
210 0 : anyhow::Ok((
211 0 : filter_duration,
212 0 : filtered.ranges.into_iter().map(move |r| KeyRange {
213 0 : timeline,
214 0 : timeline_lsn: lsn,
215 0 : start: r.start.to_i128(),
216 0 : end: r.end.to_i128(),
217 0 : }),
218 0 : ))
219 0 : }
220 0 : });
221 0 : }
222 0 : let mut total_filter_duration = Duration::from_secs(0);
223 0 : let mut all_ranges: Vec<KeyRange> = Vec::new();
224 0 : while let Some(res) = js.join_next().await {
225 0 : let (filter_duration, range) = res.unwrap().unwrap();
226 0 : all_ranges.extend(range);
227 0 : total_filter_duration += filter_duration;
228 0 : }
229 0 : info!("filter duration: {}", total_filter_duration.as_secs_f64());
230 0 : if let Some(cachefile) = args.keyspace_cache.as_ref() {
231 0 : let cache = KeyspaceCacheSer {
232 0 : tag: &timelines,
233 0 : data: &all_ranges,
234 0 : };
235 0 : let bytes = serde_json::to_vec(&cache).context("serialize keyspace for cache file")?;
236 0 : std::fs::write(cachefile, bytes).context("write keyspace cache file to disk")?;
237 0 : info!("successfully wrote keyspace cache file");
238 0 : }
239 0 : all_ranges
240 : };
241 :
242 0 : let live_stats = Arc::new(LiveStats::default());
243 0 :
244 0 : let num_live_stats_dump = 1;
245 0 : let num_work_sender_tasks = args.num_clients.get() * timelines.len();
246 0 : let num_main_impl = 1;
247 0 :
248 0 : let start_work_barrier = Arc::new(tokio::sync::Barrier::new(
249 0 : num_live_stats_dump + num_work_sender_tasks + num_main_impl,
250 0 : ));
251 0 :
252 0 : tokio::spawn({
253 0 : let stats = Arc::clone(&live_stats);
254 0 : let start_work_barrier = Arc::clone(&start_work_barrier);
255 0 : async move {
256 0 : start_work_barrier.wait().await;
257 : loop {
258 0 : let start = std::time::Instant::now();
259 0 : tokio::time::sleep(std::time::Duration::from_secs(1)).await;
260 0 : let completed_requests = stats.completed_requests.swap(0, Ordering::Relaxed);
261 0 : let missed = stats.missed.swap(0, Ordering::Relaxed);
262 0 : let elapsed = start.elapsed();
263 0 : info!(
264 0 : "RPS: {:.0} MISSED: {:.0}",
265 0 : completed_requests as f64 / elapsed.as_secs_f64(),
266 0 : missed as f64 / elapsed.as_secs_f64()
267 : );
268 : }
269 0 : }
270 0 : });
271 0 :
272 0 : let cancel = CancellationToken::new();
273 0 :
274 0 : let rps_period = args
275 0 : .per_client_rate
276 0 : .map(|rps_limit| Duration::from_secs_f64(1.0 / (rps_limit as f64)));
277 0 : let make_worker: &dyn Fn(WorkerId) -> Pin<Box<dyn Send + Future<Output = ()>>> = &|worker_id| {
278 0 : let live_stats = live_stats.clone();
279 0 : let start_work_barrier = start_work_barrier.clone();
280 0 : let ranges: Vec<KeyRange> = all_ranges
281 0 : .iter()
282 0 : .filter(|r| r.timeline == worker_id.timeline)
283 0 : .cloned()
284 0 : .collect();
285 0 : let weights =
286 0 : rand::distributions::weighted::WeightedIndex::new(ranges.iter().map(|v| v.len()))
287 0 : .unwrap();
288 0 :
289 0 : let cancel = cancel.clone();
290 0 : Box::pin(async move {
291 0 : let client =
292 0 : pageserver_client::page_service::Client::new(args.page_service_connstring.clone())
293 0 : .await
294 0 : .unwrap();
295 0 : let mut client = client
296 0 : .pagestream(worker_id.timeline.tenant_id, worker_id.timeline.timeline_id)
297 0 : .await
298 0 : .unwrap();
299 0 :
300 0 : start_work_barrier.wait().await;
301 0 : let client_start = Instant::now();
302 0 : let mut ticks_processed = 0;
303 0 : let mut inflight = VecDeque::new();
304 0 : while !cancel.is_cancelled() {
305 : // Detect if a request took longer than the RPS rate
306 0 : if let Some(period) = &rps_period {
307 0 : let periods_passed_until_now =
308 0 : usize::try_from(client_start.elapsed().as_micros() / period.as_micros())
309 0 : .unwrap();
310 0 :
311 0 : if periods_passed_until_now > ticks_processed {
312 0 : live_stats.missed((periods_passed_until_now - ticks_processed) as u64);
313 0 : }
314 0 : ticks_processed = periods_passed_until_now;
315 0 : }
316 :
317 0 : while inflight.len() < args.queue_depth.get() {
318 0 : let start = Instant::now();
319 0 : let req = {
320 0 : let mut rng = rand::thread_rng();
321 0 : let r = &ranges[weights.sample(&mut rng)];
322 0 : let key: i128 = rng.gen_range(r.start..r.end);
323 0 : let key = Key::from_i128(key);
324 0 : assert!(key.is_rel_block_key());
325 0 : let (rel_tag, block_no) = key
326 0 : .to_rel_block()
327 0 : .expect("we filter non-rel-block keys out above");
328 0 : PagestreamGetPageRequest {
329 0 : hdr: PagestreamRequest {
330 0 : reqid: 0,
331 0 : request_lsn: if rng.gen_bool(args.req_latest_probability) {
332 0 : Lsn::MAX
333 : } else {
334 0 : r.timeline_lsn
335 : },
336 0 : not_modified_since: r.timeline_lsn,
337 0 : },
338 0 : rel: rel_tag,
339 0 : blkno: block_no,
340 0 : }
341 0 : };
342 0 : client.getpage_send(req).await.unwrap();
343 0 : inflight.push_back(start);
344 : }
345 :
346 0 : let start = inflight.pop_front().unwrap();
347 0 : client.getpage_recv().await.unwrap();
348 0 : let end = Instant::now();
349 0 : live_stats.request_done();
350 0 : ticks_processed += 1;
351 0 : STATS.with(|stats| {
352 0 : stats
353 0 : .borrow()
354 0 : .lock()
355 0 : .unwrap()
356 0 : .observe(end.duration_since(start))
357 0 : .unwrap();
358 0 : });
359 :
360 0 : if let Some(period) = &rps_period {
361 0 : let next_at = client_start
362 0 : + Duration::from_micros(
363 0 : (ticks_processed) as u64 * u64::try_from(period.as_micros()).unwrap(),
364 0 : );
365 0 : tokio::time::sleep_until(next_at.into()).await;
366 0 : }
367 : }
368 0 : })
369 0 : };
370 :
371 0 : info!("spawning workers");
372 0 : let mut workers = JoinSet::new();
373 0 : for timeline in timelines.iter().cloned() {
374 0 : for num_client in 0..args.num_clients.get() {
375 0 : let worker_id = WorkerId {
376 0 : timeline,
377 0 : num_client,
378 0 : };
379 0 : workers.spawn(make_worker(worker_id));
380 0 : }
381 : }
382 0 : let workers = async move {
383 0 : while let Some(res) = workers.join_next().await {
384 0 : res.unwrap();
385 0 : }
386 0 : };
387 :
388 0 : info!("waiting for everything to become ready");
389 0 : start_work_barrier.wait().await;
390 0 : info!("work started");
391 0 : if let Some(runtime) = args.runtime {
392 0 : tokio::time::sleep(runtime.into()).await;
393 0 : info!("runtime over, signalling cancellation");
394 0 : cancel.cancel();
395 0 : workers.await;
396 0 : info!("work sender exited");
397 : } else {
398 0 : workers.await;
399 0 : unreachable!("work sender never terminates");
400 : }
401 :
402 0 : let output = Output {
403 : total: {
404 0 : let mut agg_stats = request_stats::Stats::new();
405 0 : for stats in all_thread_local_stats.lock().unwrap().iter() {
406 0 : let stats = stats.lock().unwrap();
407 0 : agg_stats.add(&stats);
408 0 : }
409 0 : agg_stats.output()
410 0 : },
411 0 : };
412 0 :
413 0 : let output = serde_json::to_string_pretty(&output).unwrap();
414 0 : println!("{output}");
415 0 :
416 0 : anyhow::Ok(())
417 0 : }
|