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