LCOV - code coverage report
Current view: top level - pageserver/pagebench/src/cmd - getpage_latest_lsn.rs (source / functions) Coverage Total Hit
Test: f8d8f5b90fa487a9e82c42da223f012f5d4fece7.info Lines: 0.0 % 271 0
Test Date: 2024-09-19 20:36:02 Functions: 0.0 % 53 0

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

Generated by: LCOV version 2.1-beta