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