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