Line data Source code
1 : //! The Page Service listens for client connections and serves their GetPage@LSN
2 : //! requests.
3 :
4 : use std::borrow::Cow;
5 : use std::num::NonZeroUsize;
6 : use std::os::fd::AsRawFd;
7 : use std::str::FromStr;
8 : use std::sync::Arc;
9 : use std::time::{Duration, Instant, SystemTime};
10 : use std::{io, str};
11 :
12 : use anyhow::{Context, bail};
13 : use async_compression::tokio::write::GzipEncoder;
14 : use bytes::Buf;
15 : use futures::FutureExt;
16 : use itertools::Itertools;
17 : use once_cell::sync::OnceCell;
18 : use pageserver_api::config::{
19 : PageServicePipeliningConfig, PageServicePipeliningConfigPipelined,
20 : PageServiceProtocolPipelinedExecutionStrategy,
21 : };
22 : use pageserver_api::key::rel_block_to_key;
23 : use pageserver_api::models::{
24 : self, PageTraceEvent, PagestreamBeMessage, PagestreamDbSizeRequest, PagestreamDbSizeResponse,
25 : PagestreamErrorResponse, PagestreamExistsRequest, PagestreamExistsResponse,
26 : PagestreamFeMessage, PagestreamGetPageRequest, PagestreamGetSlruSegmentRequest,
27 : PagestreamGetSlruSegmentResponse, PagestreamNblocksRequest, PagestreamNblocksResponse,
28 : PagestreamProtocolVersion, PagestreamRequest, TenantState,
29 : };
30 : use pageserver_api::reltag::SlruKind;
31 : use pageserver_api::shard::TenantShardId;
32 : use postgres_backend::{
33 : AuthType, PostgresBackend, PostgresBackendReader, QueryError, is_expected_io_error,
34 : };
35 : use postgres_ffi::BLCKSZ;
36 : use postgres_ffi::pg_constants::DEFAULTTABLESPACE_OID;
37 : use pq_proto::framed::ConnectionError;
38 : use pq_proto::{BeMessage, FeMessage, FeStartupPacket, RowDescriptor};
39 : use strum_macros::IntoStaticStr;
40 : use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, BufWriter};
41 : use tokio::task::JoinHandle;
42 : use tokio_util::sync::CancellationToken;
43 : use tracing::*;
44 : use utils::auth::{Claims, Scope, SwappableJwtAuth};
45 : use utils::failpoint_support;
46 : use utils::id::{TenantId, TimelineId};
47 : use utils::logging::log_slow;
48 : use utils::lsn::Lsn;
49 : use utils::simple_rcu::RcuReadGuard;
50 : use utils::sync::gate::{Gate, GateGuard};
51 : use utils::sync::spsc_fold;
52 :
53 : use crate::auth::check_permission;
54 : use crate::basebackup::BasebackupError;
55 : use crate::config::PageServerConf;
56 : use crate::context::{DownloadBehavior, RequestContext};
57 : use crate::metrics::{
58 : self, COMPUTE_COMMANDS_COUNTERS, ComputeCommandKind, LIVE_CONNECTIONS, SmgrOpTimer,
59 : };
60 : use crate::pgdatadir_mapping::Version;
61 : use crate::span::{
62 : debug_assert_current_span_has_tenant_and_timeline_id,
63 : debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id,
64 : };
65 : use crate::task_mgr::{self, COMPUTE_REQUEST_RUNTIME, TaskKind};
66 : use crate::tenant::mgr::{
67 : GetActiveTenantError, GetTenantError, ShardResolveResult, ShardSelector, TenantManager,
68 : };
69 : use crate::tenant::storage_layer::IoConcurrency;
70 : use crate::tenant::timeline::{self, WaitLsnError};
71 : use crate::tenant::{GetTimelineError, PageReconstructError, Timeline};
72 : use crate::{basebackup, timed_after_cancellation};
73 :
74 : /// How long we may wait for a [`crate::tenant::mgr::TenantSlot::InProgress`]` and/or a [`crate::tenant::Tenant`] which
75 : /// is not yet in state [`TenantState::Active`].
76 : ///
77 : /// NB: this is a different value than [`crate::http::routes::ACTIVE_TENANT_TIMEOUT`].
78 : const ACTIVE_TENANT_TIMEOUT: Duration = Duration::from_millis(30000);
79 :
80 : /// Threshold at which to log slow GetPage requests.
81 : const LOG_SLOW_GETPAGE_THRESHOLD: Duration = Duration::from_secs(30);
82 :
83 : ///////////////////////////////////////////////////////////////////////////////
84 :
85 : pub struct Listener {
86 : cancel: CancellationToken,
87 : /// Cancel the listener task through `listen_cancel` to shut down the listener
88 : /// and get a handle on the existing connections.
89 : task: JoinHandle<Connections>,
90 : }
91 :
92 : pub struct Connections {
93 : cancel: CancellationToken,
94 : tasks: tokio::task::JoinSet<ConnectionHandlerResult>,
95 : gate: Gate,
96 : }
97 :
98 0 : pub fn spawn(
99 0 : conf: &'static PageServerConf,
100 0 : tenant_manager: Arc<TenantManager>,
101 0 : pg_auth: Option<Arc<SwappableJwtAuth>>,
102 0 : tcp_listener: tokio::net::TcpListener,
103 0 : ) -> Listener {
104 0 : let cancel = CancellationToken::new();
105 0 : let libpq_ctx = RequestContext::todo_child(
106 0 : TaskKind::LibpqEndpointListener,
107 0 : // listener task shouldn't need to download anything. (We will
108 0 : // create a separate sub-contexts for each connection, with their
109 0 : // own download behavior. This context is used only to listen and
110 0 : // accept connections.)
111 0 : DownloadBehavior::Error,
112 0 : );
113 0 : let task = COMPUTE_REQUEST_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
114 0 : "libpq listener",
115 0 : libpq_listener_main(
116 0 : conf,
117 0 : tenant_manager,
118 0 : pg_auth,
119 0 : tcp_listener,
120 0 : conf.pg_auth_type,
121 0 : conf.page_service_pipelining.clone(),
122 0 : libpq_ctx,
123 0 : cancel.clone(),
124 0 : )
125 0 : .map(anyhow::Ok),
126 0 : ));
127 0 :
128 0 : Listener { cancel, task }
129 0 : }
130 :
131 : impl Listener {
132 0 : pub async fn stop_accepting(self) -> Connections {
133 0 : self.cancel.cancel();
134 0 : self.task
135 0 : .await
136 0 : .expect("unreachable: we wrap the listener task in task_mgr::exit_on_panic_or_error")
137 0 : }
138 : }
139 : impl Connections {
140 0 : pub(crate) async fn shutdown(self) {
141 0 : let Self {
142 0 : cancel,
143 0 : mut tasks,
144 0 : gate,
145 0 : } = self;
146 0 : cancel.cancel();
147 0 : while let Some(res) = tasks.join_next().await {
148 0 : Self::handle_connection_completion(res);
149 0 : }
150 0 : gate.close().await;
151 0 : }
152 :
153 0 : fn handle_connection_completion(res: Result<anyhow::Result<()>, tokio::task::JoinError>) {
154 0 : match res {
155 0 : Ok(Ok(())) => {}
156 0 : Ok(Err(e)) => error!("error in page_service connection task: {:?}", e),
157 0 : Err(e) => error!("page_service connection task panicked: {:?}", e),
158 : }
159 0 : }
160 : }
161 :
162 : ///
163 : /// Main loop of the page service.
164 : ///
165 : /// Listens for connections, and launches a new handler task for each.
166 : ///
167 : /// Returns Ok(()) upon cancellation via `cancel`, returning the set of
168 : /// open connections.
169 : ///
170 : #[allow(clippy::too_many_arguments)]
171 0 : pub async fn libpq_listener_main(
172 0 : conf: &'static PageServerConf,
173 0 : tenant_manager: Arc<TenantManager>,
174 0 : auth: Option<Arc<SwappableJwtAuth>>,
175 0 : listener: tokio::net::TcpListener,
176 0 : auth_type: AuthType,
177 0 : pipelining_config: PageServicePipeliningConfig,
178 0 : listener_ctx: RequestContext,
179 0 : listener_cancel: CancellationToken,
180 0 : ) -> Connections {
181 0 : let connections_cancel = CancellationToken::new();
182 0 : let connections_gate = Gate::default();
183 0 : let mut connection_handler_tasks = tokio::task::JoinSet::default();
184 :
185 : loop {
186 0 : let gate_guard = match connections_gate.enter() {
187 0 : Ok(guard) => guard,
188 0 : Err(_) => break,
189 : };
190 :
191 0 : let accepted = tokio::select! {
192 : biased;
193 0 : _ = listener_cancel.cancelled() => break,
194 0 : next = connection_handler_tasks.join_next(), if !connection_handler_tasks.is_empty() => {
195 0 : let res = next.expect("we dont poll while empty");
196 0 : Connections::handle_connection_completion(res);
197 0 : continue;
198 : }
199 0 : accepted = listener.accept() => accepted,
200 0 : };
201 0 :
202 0 : match accepted {
203 0 : Ok((socket, peer_addr)) => {
204 0 : // Connection established. Spawn a new task to handle it.
205 0 : debug!("accepted connection from {}", peer_addr);
206 0 : let local_auth = auth.clone();
207 0 : let connection_ctx = listener_ctx
208 0 : .detached_child(TaskKind::PageRequestHandler, DownloadBehavior::Download);
209 0 : connection_handler_tasks.spawn(page_service_conn_main(
210 0 : conf,
211 0 : tenant_manager.clone(),
212 0 : local_auth,
213 0 : socket,
214 0 : auth_type,
215 0 : pipelining_config.clone(),
216 0 : connection_ctx,
217 0 : connections_cancel.child_token(),
218 0 : gate_guard,
219 0 : ));
220 : }
221 0 : Err(err) => {
222 0 : // accept() failed. Log the error, and loop back to retry on next connection.
223 0 : error!("accept() failed: {:?}", err);
224 : }
225 : }
226 : }
227 :
228 0 : debug!("page_service listener loop terminated");
229 :
230 0 : Connections {
231 0 : cancel: connections_cancel,
232 0 : tasks: connection_handler_tasks,
233 0 : gate: connections_gate,
234 0 : }
235 0 : }
236 :
237 : type ConnectionHandlerResult = anyhow::Result<()>;
238 :
239 : #[instrument(skip_all, fields(peer_addr, application_name))]
240 : #[allow(clippy::too_many_arguments)]
241 : async fn page_service_conn_main(
242 : conf: &'static PageServerConf,
243 : tenant_manager: Arc<TenantManager>,
244 : auth: Option<Arc<SwappableJwtAuth>>,
245 : socket: tokio::net::TcpStream,
246 : auth_type: AuthType,
247 : pipelining_config: PageServicePipeliningConfig,
248 : connection_ctx: RequestContext,
249 : cancel: CancellationToken,
250 : gate_guard: GateGuard,
251 : ) -> ConnectionHandlerResult {
252 : let _guard = LIVE_CONNECTIONS
253 : .with_label_values(&["page_service"])
254 : .guard();
255 :
256 : socket
257 : .set_nodelay(true)
258 : .context("could not set TCP_NODELAY")?;
259 :
260 : let socket_fd = socket.as_raw_fd();
261 :
262 : let peer_addr = socket.peer_addr().context("get peer address")?;
263 : tracing::Span::current().record("peer_addr", field::display(peer_addr));
264 :
265 : // setup read timeout of 10 minutes. the timeout is rather arbitrary for requirements:
266 : // - long enough for most valid compute connections
267 : // - less than infinite to stop us from "leaking" connections to long-gone computes
268 : //
269 : // no write timeout is used, because the kernel is assumed to error writes after some time.
270 : let mut socket = tokio_io_timeout::TimeoutReader::new(socket);
271 :
272 : let default_timeout_ms = 10 * 60 * 1000; // 10 minutes by default
273 0 : let socket_timeout_ms = (|| {
274 0 : fail::fail_point!("simulated-bad-compute-connection", |avg_timeout_ms| {
275 : // Exponential distribution for simulating
276 : // poor network conditions, expect about avg_timeout_ms to be around 15
277 : // in tests
278 0 : if let Some(avg_timeout_ms) = avg_timeout_ms {
279 0 : let avg = avg_timeout_ms.parse::<i64>().unwrap() as f32;
280 0 : let u = rand::random::<f32>();
281 0 : ((1.0 - u).ln() / (-avg)) as u64
282 : } else {
283 0 : default_timeout_ms
284 : }
285 0 : });
286 0 : default_timeout_ms
287 : })();
288 :
289 : // A timeout here does not mean the client died, it can happen if it's just idle for
290 : // a while: we will tear down this PageServerHandler and instantiate a new one if/when
291 : // they reconnect.
292 : socket.set_timeout(Some(std::time::Duration::from_millis(socket_timeout_ms)));
293 : let socket = Box::pin(socket);
294 :
295 : fail::fail_point!("ps::connection-start::pre-login");
296 :
297 : // XXX: pgbackend.run() should take the connection_ctx,
298 : // and create a child per-query context when it invokes process_query.
299 : // But it's in a shared crate, so, we store connection_ctx inside PageServerHandler
300 : // and create the per-query context in process_query ourselves.
301 : let mut conn_handler = PageServerHandler::new(
302 : conf,
303 : tenant_manager,
304 : auth,
305 : pipelining_config,
306 : connection_ctx,
307 : cancel.clone(),
308 : gate_guard,
309 : );
310 : let pgbackend = PostgresBackend::new_from_io(socket_fd, socket, peer_addr, auth_type, None)?;
311 :
312 : match pgbackend.run(&mut conn_handler, &cancel).await {
313 : Ok(()) => {
314 : // we've been requested to shut down
315 : Ok(())
316 : }
317 : Err(QueryError::Disconnected(ConnectionError::Io(io_error))) => {
318 : if is_expected_io_error(&io_error) {
319 : info!("Postgres client disconnected ({io_error})");
320 : Ok(())
321 : } else {
322 : let tenant_id = conn_handler.timeline_handles.as_ref().unwrap().tenant_id();
323 : Err(io_error).context(format!(
324 : "Postgres connection error for tenant_id={:?} client at peer_addr={}",
325 : tenant_id, peer_addr
326 : ))
327 : }
328 : }
329 : other => {
330 : let tenant_id = conn_handler.timeline_handles.as_ref().unwrap().tenant_id();
331 : other.context(format!(
332 : "Postgres query error for tenant_id={:?} client peer_addr={}",
333 : tenant_id, peer_addr
334 : ))
335 : }
336 : }
337 : }
338 :
339 : struct PageServerHandler {
340 : conf: &'static PageServerConf,
341 : auth: Option<Arc<SwappableJwtAuth>>,
342 : claims: Option<Claims>,
343 :
344 : /// The context created for the lifetime of the connection
345 : /// services by this PageServerHandler.
346 : /// For each query received over the connection,
347 : /// `process_query` creates a child context from this one.
348 : connection_ctx: RequestContext,
349 :
350 : cancel: CancellationToken,
351 :
352 : /// None only while pagestream protocol is being processed.
353 : timeline_handles: Option<TimelineHandles>,
354 :
355 : pipelining_config: PageServicePipeliningConfig,
356 :
357 : gate_guard: GateGuard,
358 : }
359 :
360 : struct TimelineHandles {
361 : wrapper: TenantManagerWrapper,
362 : /// Note on size: the typical size of this map is 1. The largest size we expect
363 : /// to see is the number of shards divided by the number of pageservers (typically < 2),
364 : /// or the ratio used when splitting shards (i.e. how many children created from one)
365 : /// parent shard, where a "large" number might be ~8.
366 : handles: timeline::handle::Cache<TenantManagerTypes>,
367 : }
368 :
369 : impl TimelineHandles {
370 0 : fn new(tenant_manager: Arc<TenantManager>) -> Self {
371 0 : Self {
372 0 : wrapper: TenantManagerWrapper {
373 0 : tenant_manager,
374 0 : tenant_id: OnceCell::new(),
375 0 : },
376 0 : handles: Default::default(),
377 0 : }
378 0 : }
379 0 : async fn get(
380 0 : &mut self,
381 0 : tenant_id: TenantId,
382 0 : timeline_id: TimelineId,
383 0 : shard_selector: ShardSelector,
384 0 : ) -> Result<timeline::handle::Handle<TenantManagerTypes>, GetActiveTimelineError> {
385 0 : if *self.wrapper.tenant_id.get_or_init(|| tenant_id) != tenant_id {
386 0 : return Err(GetActiveTimelineError::Tenant(
387 0 : GetActiveTenantError::SwitchedTenant,
388 0 : ));
389 0 : }
390 0 : self.handles
391 0 : .get(timeline_id, shard_selector, &self.wrapper)
392 0 : .await
393 0 : .map_err(|e| match e {
394 0 : timeline::handle::GetError::TenantManager(e) => e,
395 : timeline::handle::GetError::TimelineGateClosed => {
396 0 : trace!("timeline gate closed");
397 0 : GetActiveTimelineError::Timeline(GetTimelineError::ShuttingDown)
398 : }
399 : timeline::handle::GetError::PerTimelineStateShutDown => {
400 0 : trace!("per-timeline state shut down");
401 0 : GetActiveTimelineError::Timeline(GetTimelineError::ShuttingDown)
402 : }
403 0 : })
404 0 : }
405 :
406 0 : fn tenant_id(&self) -> Option<TenantId> {
407 0 : self.wrapper.tenant_id.get().copied()
408 0 : }
409 : }
410 :
411 : pub(crate) struct TenantManagerWrapper {
412 : tenant_manager: Arc<TenantManager>,
413 : // We do not support switching tenant_id on a connection at this point.
414 : // We can can add support for this later if needed without changing
415 : // the protocol.
416 : tenant_id: once_cell::sync::OnceCell<TenantId>,
417 : }
418 :
419 : #[derive(Debug)]
420 : pub(crate) struct TenantManagerTypes;
421 :
422 : impl timeline::handle::Types for TenantManagerTypes {
423 : type TenantManagerError = GetActiveTimelineError;
424 : type TenantManager = TenantManagerWrapper;
425 : type Timeline = Arc<Timeline>;
426 : }
427 :
428 : impl timeline::handle::ArcTimeline<TenantManagerTypes> for Arc<Timeline> {
429 0 : fn gate(&self) -> &utils::sync::gate::Gate {
430 0 : &self.gate
431 0 : }
432 :
433 0 : fn shard_timeline_id(&self) -> timeline::handle::ShardTimelineId {
434 0 : Timeline::shard_timeline_id(self)
435 0 : }
436 :
437 0 : fn per_timeline_state(&self) -> &timeline::handle::PerTimelineState<TenantManagerTypes> {
438 0 : &self.handles
439 0 : }
440 :
441 0 : fn get_shard_identity(&self) -> &pageserver_api::shard::ShardIdentity {
442 0 : Timeline::get_shard_identity(self)
443 0 : }
444 : }
445 :
446 : impl timeline::handle::TenantManager<TenantManagerTypes> for TenantManagerWrapper {
447 0 : async fn resolve(
448 0 : &self,
449 0 : timeline_id: TimelineId,
450 0 : shard_selector: ShardSelector,
451 0 : ) -> Result<Arc<Timeline>, GetActiveTimelineError> {
452 0 : let tenant_id = self.tenant_id.get().expect("we set this in get()");
453 0 : let timeout = ACTIVE_TENANT_TIMEOUT;
454 0 : let wait_start = Instant::now();
455 0 : let deadline = wait_start + timeout;
456 0 : let tenant_shard = loop {
457 0 : let resolved = self
458 0 : .tenant_manager
459 0 : .resolve_attached_shard(tenant_id, shard_selector);
460 0 : match resolved {
461 0 : ShardResolveResult::Found(tenant_shard) => break tenant_shard,
462 : ShardResolveResult::NotFound => {
463 0 : return Err(GetActiveTimelineError::Tenant(
464 0 : GetActiveTenantError::NotFound(GetTenantError::NotFound(*tenant_id)),
465 0 : ));
466 : }
467 0 : ShardResolveResult::InProgress(barrier) => {
468 0 : // We can't authoritatively answer right now: wait for InProgress state
469 0 : // to end, then try again
470 0 : tokio::select! {
471 0 : _ = barrier.wait() => {
472 0 : // The barrier completed: proceed around the loop to try looking up again
473 0 : },
474 0 : _ = tokio::time::sleep(deadline.duration_since(Instant::now())) => {
475 0 : return Err(GetActiveTimelineError::Tenant(GetActiveTenantError::WaitForActiveTimeout {
476 0 : latest_state: None,
477 0 : wait_time: timeout,
478 0 : }));
479 : }
480 : }
481 : }
482 : };
483 : };
484 :
485 0 : tracing::debug!("Waiting for tenant to enter active state...");
486 0 : tenant_shard
487 0 : .wait_to_become_active(deadline.duration_since(Instant::now()))
488 0 : .await
489 0 : .map_err(GetActiveTimelineError::Tenant)?;
490 :
491 0 : let timeline = tenant_shard
492 0 : .get_timeline(timeline_id, true)
493 0 : .map_err(GetActiveTimelineError::Timeline)?;
494 0 : Ok(timeline)
495 0 : }
496 : }
497 :
498 : #[derive(thiserror::Error, Debug)]
499 : enum PageStreamError {
500 : /// We encountered an error that should prompt the client to reconnect:
501 : /// in practice this means we drop the connection without sending a response.
502 : #[error("Reconnect required: {0}")]
503 : Reconnect(Cow<'static, str>),
504 :
505 : /// We were instructed to shutdown while processing the query
506 : #[error("Shutting down")]
507 : Shutdown,
508 :
509 : /// Something went wrong reading a page: this likely indicates a pageserver bug
510 : #[error("Read error")]
511 : Read(#[source] PageReconstructError),
512 :
513 : /// Ran out of time waiting for an LSN
514 : #[error("LSN timeout: {0}")]
515 : LsnTimeout(WaitLsnError),
516 :
517 : /// The entity required to serve the request (tenant or timeline) is not found,
518 : /// or is not found in a suitable state to serve a request.
519 : #[error("Not found: {0}")]
520 : NotFound(Cow<'static, str>),
521 :
522 : /// Request asked for something that doesn't make sense, like an invalid LSN
523 : #[error("Bad request: {0}")]
524 : BadRequest(Cow<'static, str>),
525 : }
526 :
527 : impl From<PageReconstructError> for PageStreamError {
528 0 : fn from(value: PageReconstructError) -> Self {
529 0 : match value {
530 0 : PageReconstructError::Cancelled => Self::Shutdown,
531 0 : e => Self::Read(e),
532 : }
533 0 : }
534 : }
535 :
536 : impl From<GetActiveTimelineError> for PageStreamError {
537 0 : fn from(value: GetActiveTimelineError) -> Self {
538 0 : match value {
539 : GetActiveTimelineError::Tenant(GetActiveTenantError::Cancelled)
540 : | GetActiveTimelineError::Tenant(GetActiveTenantError::WillNotBecomeActive(
541 : TenantState::Stopping { .. },
542 : ))
543 0 : | GetActiveTimelineError::Timeline(GetTimelineError::ShuttingDown) => Self::Shutdown,
544 0 : GetActiveTimelineError::Tenant(e) => Self::NotFound(format!("{e}").into()),
545 0 : GetActiveTimelineError::Timeline(e) => Self::NotFound(format!("{e}").into()),
546 : }
547 0 : }
548 : }
549 :
550 : impl From<WaitLsnError> for PageStreamError {
551 0 : fn from(value: WaitLsnError) -> Self {
552 0 : match value {
553 0 : e @ WaitLsnError::Timeout(_) => Self::LsnTimeout(e),
554 0 : WaitLsnError::Shutdown => Self::Shutdown,
555 0 : e @ WaitLsnError::BadState { .. } => Self::Reconnect(format!("{e}").into()),
556 : }
557 0 : }
558 : }
559 :
560 : impl From<WaitLsnError> for QueryError {
561 0 : fn from(value: WaitLsnError) -> Self {
562 0 : match value {
563 0 : e @ WaitLsnError::Timeout(_) => Self::Other(anyhow::Error::new(e)),
564 0 : WaitLsnError::Shutdown => Self::Shutdown,
565 0 : WaitLsnError::BadState { .. } => Self::Reconnect,
566 : }
567 0 : }
568 : }
569 :
570 : #[derive(thiserror::Error, Debug)]
571 : struct BatchedPageStreamError {
572 : req: PagestreamRequest,
573 : err: PageStreamError,
574 : }
575 :
576 : impl std::fmt::Display for BatchedPageStreamError {
577 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
578 0 : self.err.fmt(f)
579 0 : }
580 : }
581 :
582 : struct BatchedGetPageRequest {
583 : req: PagestreamGetPageRequest,
584 : timer: SmgrOpTimer,
585 : }
586 :
587 : #[cfg(feature = "testing")]
588 : struct BatchedTestRequest {
589 : req: models::PagestreamTestRequest,
590 : timer: SmgrOpTimer,
591 : }
592 :
593 : /// NB: we only hold [`timeline::handle::WeakHandle`] inside this enum,
594 : /// so that we don't keep the [`Timeline::gate`] open while the batch
595 : /// is being built up inside the [`spsc_fold`] (pagestream pipelining).
596 : #[derive(IntoStaticStr)]
597 : enum BatchedFeMessage {
598 : Exists {
599 : span: Span,
600 : timer: SmgrOpTimer,
601 : shard: timeline::handle::WeakHandle<TenantManagerTypes>,
602 : req: models::PagestreamExistsRequest,
603 : },
604 : Nblocks {
605 : span: Span,
606 : timer: SmgrOpTimer,
607 : shard: timeline::handle::WeakHandle<TenantManagerTypes>,
608 : req: models::PagestreamNblocksRequest,
609 : },
610 : GetPage {
611 : span: Span,
612 : shard: timeline::handle::WeakHandle<TenantManagerTypes>,
613 : effective_request_lsn: Lsn,
614 : pages: smallvec::SmallVec<[BatchedGetPageRequest; 1]>,
615 : },
616 : DbSize {
617 : span: Span,
618 : timer: SmgrOpTimer,
619 : shard: timeline::handle::WeakHandle<TenantManagerTypes>,
620 : req: models::PagestreamDbSizeRequest,
621 : },
622 : GetSlruSegment {
623 : span: Span,
624 : timer: SmgrOpTimer,
625 : shard: timeline::handle::WeakHandle<TenantManagerTypes>,
626 : req: models::PagestreamGetSlruSegmentRequest,
627 : },
628 : #[cfg(feature = "testing")]
629 : Test {
630 : span: Span,
631 : shard: timeline::handle::WeakHandle<TenantManagerTypes>,
632 : requests: Vec<BatchedTestRequest>,
633 : },
634 : RespondError {
635 : span: Span,
636 : error: BatchedPageStreamError,
637 : },
638 : }
639 :
640 : impl BatchedFeMessage {
641 0 : fn as_static_str(&self) -> &'static str {
642 0 : self.into()
643 0 : }
644 :
645 0 : fn observe_execution_start(&mut self, at: Instant) {
646 0 : match self {
647 0 : BatchedFeMessage::Exists { timer, .. }
648 0 : | BatchedFeMessage::Nblocks { timer, .. }
649 0 : | BatchedFeMessage::DbSize { timer, .. }
650 0 : | BatchedFeMessage::GetSlruSegment { timer, .. } => {
651 0 : timer.observe_execution_start(at);
652 0 : }
653 0 : BatchedFeMessage::GetPage { pages, .. } => {
654 0 : for page in pages {
655 0 : page.timer.observe_execution_start(at);
656 0 : }
657 : }
658 : #[cfg(feature = "testing")]
659 0 : BatchedFeMessage::Test { requests, .. } => {
660 0 : for req in requests {
661 0 : req.timer.observe_execution_start(at);
662 0 : }
663 : }
664 0 : BatchedFeMessage::RespondError { .. } => {}
665 : }
666 0 : }
667 : }
668 :
669 : impl PageServerHandler {
670 0 : pub fn new(
671 0 : conf: &'static PageServerConf,
672 0 : tenant_manager: Arc<TenantManager>,
673 0 : auth: Option<Arc<SwappableJwtAuth>>,
674 0 : pipelining_config: PageServicePipeliningConfig,
675 0 : connection_ctx: RequestContext,
676 0 : cancel: CancellationToken,
677 0 : gate_guard: GateGuard,
678 0 : ) -> Self {
679 0 : PageServerHandler {
680 0 : conf,
681 0 : auth,
682 0 : claims: None,
683 0 : connection_ctx,
684 0 : timeline_handles: Some(TimelineHandles::new(tenant_manager)),
685 0 : cancel,
686 0 : pipelining_config,
687 0 : gate_guard,
688 0 : }
689 0 : }
690 :
691 : /// This function always respects cancellation of any timeline in `[Self::shard_timelines]`. Pass in
692 : /// a cancellation token at the next scope up (such as a tenant cancellation token) to ensure we respect
693 : /// cancellation if there aren't any timelines in the cache.
694 : ///
695 : /// If calling from a function that doesn't use the `[Self::shard_timelines]` cache, then pass in the
696 : /// timeline cancellation token.
697 0 : async fn flush_cancellable<IO>(
698 0 : &self,
699 0 : pgb: &mut PostgresBackend<IO>,
700 0 : cancel: &CancellationToken,
701 0 : ) -> Result<(), QueryError>
702 0 : where
703 0 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
704 0 : {
705 0 : tokio::select!(
706 0 : flush_r = pgb.flush() => {
707 0 : Ok(flush_r?)
708 : },
709 0 : _ = cancel.cancelled() => {
710 0 : Err(QueryError::Shutdown)
711 : }
712 : )
713 0 : }
714 :
715 : #[allow(clippy::too_many_arguments)]
716 0 : async fn pagestream_read_message<IO>(
717 0 : pgb: &mut PostgresBackendReader<IO>,
718 0 : tenant_id: TenantId,
719 0 : timeline_id: TimelineId,
720 0 : timeline_handles: &mut TimelineHandles,
721 0 : cancel: &CancellationToken,
722 0 : ctx: &RequestContext,
723 0 : protocol_version: PagestreamProtocolVersion,
724 0 : parent_span: Span,
725 0 : ) -> Result<Option<BatchedFeMessage>, QueryError>
726 0 : where
727 0 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
728 0 : {
729 0 : let msg = tokio::select! {
730 : biased;
731 0 : _ = cancel.cancelled() => {
732 0 : return Err(QueryError::Shutdown)
733 : }
734 0 : msg = pgb.read_message() => { msg }
735 0 : };
736 0 :
737 0 : let received_at = Instant::now();
738 :
739 0 : let copy_data_bytes = match msg? {
740 0 : Some(FeMessage::CopyData(bytes)) => bytes,
741 : Some(FeMessage::Terminate) => {
742 0 : return Ok(None);
743 : }
744 0 : Some(m) => {
745 0 : return Err(QueryError::Other(anyhow::anyhow!(
746 0 : "unexpected message: {m:?} during COPY"
747 0 : )));
748 : }
749 : None => {
750 0 : return Ok(None);
751 : } // client disconnected
752 : };
753 0 : trace!("query: {copy_data_bytes:?}");
754 :
755 0 : fail::fail_point!("ps::handle-pagerequest-message");
756 :
757 : // parse request
758 0 : let neon_fe_msg =
759 0 : PagestreamFeMessage::parse(&mut copy_data_bytes.reader(), protocol_version)?;
760 :
761 : // TODO: turn in to async closure once available to avoid repeating received_at
762 0 : async fn record_op_start_and_throttle(
763 0 : shard: &timeline::handle::Handle<TenantManagerTypes>,
764 0 : op: metrics::SmgrQueryType,
765 0 : received_at: Instant,
766 0 : ) -> Result<SmgrOpTimer, QueryError> {
767 0 : // It's important to start the smgr op metric recorder as early as possible
768 0 : // so that the _started counters are incremented before we do
769 0 : // any serious waiting, e.g., for throttle, batching, or actual request handling.
770 0 : let mut timer = shard.query_metrics.start_smgr_op(op, received_at);
771 0 : let now = Instant::now();
772 0 : timer.observe_throttle_start(now);
773 0 : let throttled = tokio::select! {
774 0 : res = shard.pagestream_throttle.throttle(1, now) => res,
775 0 : _ = shard.cancel.cancelled() => return Err(QueryError::Shutdown),
776 : };
777 0 : timer.observe_throttle_done(throttled);
778 0 : Ok(timer)
779 0 : }
780 :
781 0 : let batched_msg = match neon_fe_msg {
782 0 : PagestreamFeMessage::Exists(req) => {
783 0 : let shard = timeline_handles
784 0 : .get(tenant_id, timeline_id, ShardSelector::Zero)
785 0 : .await?;
786 0 : debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
787 0 : let span = tracing::info_span!(parent: &parent_span, "handle_get_rel_exists_request", rel = %req.rel, req_lsn = %req.hdr.request_lsn, shard_id = %shard.tenant_shard_id.shard_slug());
788 0 : let timer = record_op_start_and_throttle(
789 0 : &shard,
790 0 : metrics::SmgrQueryType::GetRelExists,
791 0 : received_at,
792 0 : )
793 0 : .await?;
794 0 : BatchedFeMessage::Exists {
795 0 : span,
796 0 : timer,
797 0 : shard: shard.downgrade(),
798 0 : req,
799 0 : }
800 : }
801 0 : PagestreamFeMessage::Nblocks(req) => {
802 0 : let shard = timeline_handles
803 0 : .get(tenant_id, timeline_id, ShardSelector::Zero)
804 0 : .await?;
805 0 : let span = tracing::info_span!(parent: &parent_span, "handle_get_nblocks_request", rel = %req.rel, req_lsn = %req.hdr.request_lsn, shard_id = %shard.tenant_shard_id.shard_slug());
806 0 : let timer = record_op_start_and_throttle(
807 0 : &shard,
808 0 : metrics::SmgrQueryType::GetRelSize,
809 0 : received_at,
810 0 : )
811 0 : .await?;
812 0 : BatchedFeMessage::Nblocks {
813 0 : span,
814 0 : timer,
815 0 : shard: shard.downgrade(),
816 0 : req,
817 0 : }
818 : }
819 0 : PagestreamFeMessage::DbSize(req) => {
820 0 : let shard = timeline_handles
821 0 : .get(tenant_id, timeline_id, ShardSelector::Zero)
822 0 : .await?;
823 0 : let span = tracing::info_span!(parent: &parent_span, "handle_db_size_request", dbnode = %req.dbnode, req_lsn = %req.hdr.request_lsn, shard_id = %shard.tenant_shard_id.shard_slug());
824 0 : let timer = record_op_start_and_throttle(
825 0 : &shard,
826 0 : metrics::SmgrQueryType::GetDbSize,
827 0 : received_at,
828 0 : )
829 0 : .await?;
830 0 : BatchedFeMessage::DbSize {
831 0 : span,
832 0 : timer,
833 0 : shard: shard.downgrade(),
834 0 : req,
835 0 : }
836 : }
837 0 : PagestreamFeMessage::GetSlruSegment(req) => {
838 0 : let shard = timeline_handles
839 0 : .get(tenant_id, timeline_id, ShardSelector::Zero)
840 0 : .await?;
841 0 : let span = tracing::info_span!(parent: &parent_span, "handle_get_slru_segment_request", kind = %req.kind, segno = %req.segno, req_lsn = %req.hdr.request_lsn, shard_id = %shard.tenant_shard_id.shard_slug());
842 0 : let timer = record_op_start_and_throttle(
843 0 : &shard,
844 0 : metrics::SmgrQueryType::GetSlruSegment,
845 0 : received_at,
846 0 : )
847 0 : .await?;
848 0 : BatchedFeMessage::GetSlruSegment {
849 0 : span,
850 0 : timer,
851 0 : shard: shard.downgrade(),
852 0 : req,
853 0 : }
854 : }
855 0 : PagestreamFeMessage::GetPage(req) => {
856 : // avoid a somewhat costly Span::record() by constructing the entire span in one go.
857 : macro_rules! mkspan {
858 : (before shard routing) => {{
859 : tracing::info_span!(parent: &parent_span, "handle_get_page_request", rel = %req.rel, blkno = %req.blkno, req_lsn = %req.hdr.request_lsn)
860 : }};
861 : ($shard_id:expr) => {{
862 : tracing::info_span!(parent: &parent_span, "handle_get_page_request", rel = %req.rel, blkno = %req.blkno, req_lsn = %req.hdr.request_lsn, shard_id = %$shard_id)
863 : }};
864 : }
865 :
866 : macro_rules! respond_error {
867 : ($span:expr, $error:expr) => {{
868 : let error = BatchedFeMessage::RespondError {
869 : span: $span,
870 : error: BatchedPageStreamError {
871 : req: req.hdr,
872 : err: $error,
873 : },
874 : };
875 : Ok(Some(error))
876 : }};
877 : }
878 :
879 0 : let key = rel_block_to_key(req.rel, req.blkno);
880 0 : let shard = match timeline_handles
881 0 : .get(tenant_id, timeline_id, ShardSelector::Page(key))
882 0 : .await
883 : {
884 0 : Ok(tl) => tl,
885 0 : Err(e) => {
886 0 : let span = mkspan!(before shard routing);
887 0 : match e {
888 : GetActiveTimelineError::Tenant(GetActiveTenantError::NotFound(_)) => {
889 : // We already know this tenant exists in general, because we resolved it at
890 : // start of connection. Getting a NotFound here indicates that the shard containing
891 : // the requested page is not present on this node: the client's knowledge of shard->pageserver
892 : // mapping is out of date.
893 : //
894 : // Closing the connection by returning ``::Reconnect` has the side effect of rate-limiting above message, via
895 : // client's reconnect backoff, as well as hopefully prompting the client to load its updated configuration
896 : // and talk to a different pageserver.
897 0 : return respond_error!(
898 0 : span,
899 0 : PageStreamError::Reconnect(
900 0 : "getpage@lsn request routed to wrong shard".into()
901 0 : )
902 0 : );
903 : }
904 0 : e => {
905 0 : return respond_error!(span, e.into());
906 : }
907 : }
908 : }
909 : };
910 0 : let span = mkspan!(shard.tenant_shard_id.shard_slug());
911 :
912 0 : let timer = record_op_start_and_throttle(
913 0 : &shard,
914 0 : metrics::SmgrQueryType::GetPageAtLsn,
915 0 : received_at,
916 0 : )
917 0 : .await?;
918 :
919 : // We're holding the Handle
920 0 : let effective_request_lsn = match Self::wait_or_get_last_lsn(
921 0 : &shard,
922 0 : req.hdr.request_lsn,
923 0 : req.hdr.not_modified_since,
924 0 : &shard.get_applied_gc_cutoff_lsn(),
925 0 : ctx,
926 0 : )
927 0 : // TODO: if we actually need to wait for lsn here, it delays the entire batch which doesn't need to wait
928 0 : .await
929 : {
930 0 : Ok(lsn) => lsn,
931 0 : Err(e) => {
932 0 : return respond_error!(span, e);
933 : }
934 : };
935 : BatchedFeMessage::GetPage {
936 0 : span,
937 0 : shard: shard.downgrade(),
938 0 : effective_request_lsn,
939 0 : pages: smallvec::smallvec![BatchedGetPageRequest { req, timer }],
940 : }
941 : }
942 : #[cfg(feature = "testing")]
943 0 : PagestreamFeMessage::Test(req) => {
944 0 : let shard = timeline_handles
945 0 : .get(tenant_id, timeline_id, ShardSelector::Zero)
946 0 : .await?;
947 0 : let span = tracing::info_span!(parent: &parent_span, "handle_test_request", shard_id = %shard.tenant_shard_id.shard_slug());
948 0 : let timer =
949 0 : record_op_start_and_throttle(&shard, metrics::SmgrQueryType::Test, received_at)
950 0 : .await?;
951 0 : BatchedFeMessage::Test {
952 0 : span,
953 0 : shard: shard.downgrade(),
954 0 : requests: vec![BatchedTestRequest { req, timer }],
955 0 : }
956 : }
957 : };
958 0 : Ok(Some(batched_msg))
959 0 : }
960 :
961 : /// Post-condition: `batch` is Some()
962 : #[instrument(skip_all, level = tracing::Level::TRACE)]
963 : #[allow(clippy::boxed_local)]
964 : fn pagestream_do_batch(
965 : max_batch_size: NonZeroUsize,
966 : batch: &mut Result<BatchedFeMessage, QueryError>,
967 : this_msg: Result<BatchedFeMessage, QueryError>,
968 : ) -> Result<(), Result<BatchedFeMessage, QueryError>> {
969 : debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
970 :
971 : let this_msg = match this_msg {
972 : Ok(this_msg) => this_msg,
973 : Err(e) => return Err(Err(e)),
974 : };
975 :
976 : match (&mut *batch, this_msg) {
977 : // something batched already, let's see if we can add this message to the batch
978 : (
979 : Ok(BatchedFeMessage::GetPage {
980 : span: _,
981 : shard: accum_shard,
982 : pages: accum_pages,
983 : effective_request_lsn: accum_lsn,
984 : }),
985 : BatchedFeMessage::GetPage {
986 : span: _,
987 : shard: this_shard,
988 : pages: this_pages,
989 : effective_request_lsn: this_lsn,
990 : },
991 0 : ) if (|| {
992 0 : assert_eq!(this_pages.len(), 1);
993 0 : if accum_pages.len() >= max_batch_size.get() {
994 0 : trace!(%accum_lsn, %this_lsn, %max_batch_size, "stopping batching because of batch size");
995 0 : assert_eq!(accum_pages.len(), max_batch_size.get());
996 0 : return false;
997 0 : }
998 0 : if !accum_shard.is_same_handle_as(&this_shard) {
999 0 : trace!(%accum_lsn, %this_lsn, "stopping batching because timeline object mismatch");
1000 : // TODO: we _could_ batch & execute each shard seperately (and in parallel).
1001 : // But the current logic for keeping responses in order does not support that.
1002 0 : return false;
1003 0 : }
1004 0 : // the vectored get currently only supports a single LSN, so, bounce as soon
1005 0 : // as the effective request_lsn changes
1006 0 : if *accum_lsn != this_lsn {
1007 0 : trace!(%accum_lsn, %this_lsn, "stopping batching because LSN changed");
1008 0 : return false;
1009 0 : }
1010 0 : true
1011 : })() =>
1012 : {
1013 : // ok to batch
1014 : accum_pages.extend(this_pages);
1015 : Ok(())
1016 : }
1017 : #[cfg(feature = "testing")]
1018 : (
1019 : Ok(BatchedFeMessage::Test {
1020 : shard: accum_shard,
1021 : requests: accum_requests,
1022 : ..
1023 : }),
1024 : BatchedFeMessage::Test {
1025 : shard: this_shard,
1026 : requests: this_requests,
1027 : ..
1028 : },
1029 0 : ) if (|| {
1030 0 : assert!(this_requests.len() == 1);
1031 0 : if accum_requests.len() >= max_batch_size.get() {
1032 0 : trace!(%max_batch_size, "stopping batching because of batch size");
1033 0 : assert_eq!(accum_requests.len(), max_batch_size.get());
1034 0 : return false;
1035 0 : }
1036 0 : if !accum_shard.is_same_handle_as(&this_shard) {
1037 0 : trace!("stopping batching because timeline object mismatch");
1038 : // TODO: we _could_ batch & execute each shard seperately (and in parallel).
1039 : // But the current logic for keeping responses in order does not support that.
1040 0 : return false;
1041 0 : }
1042 0 : let this_batch_key = this_requests[0].req.batch_key;
1043 0 : let accum_batch_key = accum_requests[0].req.batch_key;
1044 0 : if this_requests[0].req.batch_key != accum_requests[0].req.batch_key {
1045 0 : trace!(%accum_batch_key, %this_batch_key, "stopping batching because batch key changed");
1046 0 : return false;
1047 0 : }
1048 0 : true
1049 : })() =>
1050 : {
1051 : // ok to batch
1052 : accum_requests.extend(this_requests);
1053 : Ok(())
1054 : }
1055 : // something batched already but this message is unbatchable
1056 : (_, this_msg) => {
1057 : // by default, don't continue batching
1058 : Err(Ok(this_msg))
1059 : }
1060 : }
1061 : }
1062 :
1063 0 : #[instrument(level = tracing::Level::DEBUG, skip_all)]
1064 : async fn pagesteam_handle_batched_message<IO>(
1065 : &mut self,
1066 : pgb_writer: &mut PostgresBackend<IO>,
1067 : batch: BatchedFeMessage,
1068 : io_concurrency: IoConcurrency,
1069 : cancel: &CancellationToken,
1070 : protocol_version: PagestreamProtocolVersion,
1071 : ctx: &RequestContext,
1072 : ) -> Result<(), QueryError>
1073 : where
1074 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
1075 : {
1076 : let started_at = Instant::now();
1077 : let batch = {
1078 : let mut batch = batch;
1079 : batch.observe_execution_start(started_at);
1080 : batch
1081 : };
1082 :
1083 : // Dispatch the batch to the appropriate request handler.
1084 : let (mut handler_results, span) = log_slow(
1085 : batch.as_static_str(),
1086 : LOG_SLOW_GETPAGE_THRESHOLD,
1087 : self.pagestream_dispatch_batched_message(batch, io_concurrency, ctx),
1088 : )
1089 : .await?;
1090 :
1091 : // We purposefully don't count flush time into the smgr operation timer.
1092 : //
1093 : // The reason is that current compute client will not perform protocol processing
1094 : // if the postgres backend process is doing things other than `->smgr_read()`.
1095 : // This is especially the case for prefetch.
1096 : //
1097 : // If the compute doesn't read from the connection, eventually TCP will backpressure
1098 : // all the way into our flush call below.
1099 : //
1100 : // The timer's underlying metric is used for a storage-internal latency SLO and
1101 : // we don't want to include latency in it that we can't control.
1102 : // And as pointed out above, in this case, we don't control the time that flush will take.
1103 : //
1104 : // We put each response in the batch onto the wire in a separate pgb_writer.flush()
1105 : // call, which (all unmeasured) adds syscall overhead but reduces time to first byte
1106 : // and avoids building up a "giant" contiguous userspace buffer to hold the entire response.
1107 : // TODO: vectored socket IO would be great, but pgb_writer doesn't support that.
1108 : let flush_timers = {
1109 : let flushing_start_time = Instant::now();
1110 : let mut flush_timers = Vec::with_capacity(handler_results.len());
1111 : for handler_result in &mut handler_results {
1112 : let flush_timer = match handler_result {
1113 : Ok((_, timer)) => Some(
1114 : timer
1115 : .observe_execution_end(flushing_start_time)
1116 : .expect("we are the first caller"),
1117 : ),
1118 : Err(_) => {
1119 : // TODO: measure errors
1120 : None
1121 : }
1122 : };
1123 : flush_timers.push(flush_timer);
1124 : }
1125 : assert_eq!(flush_timers.len(), handler_results.len());
1126 : flush_timers
1127 : };
1128 :
1129 : // Map handler result to protocol behavior.
1130 : // Some handler errors cause exit from pagestream protocol.
1131 : // Other handler errors are sent back as an error message and we stay in pagestream protocol.
1132 : for (handler_result, flushing_timer) in handler_results.into_iter().zip(flush_timers) {
1133 : let response_msg = match handler_result {
1134 : Err(e) => match &e.err {
1135 : PageStreamError::Shutdown => {
1136 : // If we fail to fulfil a request during shutdown, which may be _because_ of
1137 : // shutdown, then do not send the error to the client. Instead just drop the
1138 : // connection.
1139 0 : span.in_scope(|| info!("dropping connection due to shutdown"));
1140 : return Err(QueryError::Shutdown);
1141 : }
1142 : PageStreamError::Reconnect(reason) => {
1143 0 : span.in_scope(|| info!("handler requested reconnect: {reason}"));
1144 : return Err(QueryError::Reconnect);
1145 : }
1146 : PageStreamError::Read(_)
1147 : | PageStreamError::LsnTimeout(_)
1148 : | PageStreamError::NotFound(_)
1149 : | PageStreamError::BadRequest(_) => {
1150 : // print the all details to the log with {:#}, but for the client the
1151 : // error message is enough. Do not log if shutting down, as the anyhow::Error
1152 : // here includes cancellation which is not an error.
1153 : let full = utils::error::report_compact_sources(&e.err);
1154 0 : span.in_scope(|| {
1155 0 : error!("error reading relation or page version: {full:#}")
1156 0 : });
1157 :
1158 : PagestreamBeMessage::Error(PagestreamErrorResponse {
1159 : req: e.req,
1160 : message: e.err.to_string(),
1161 : })
1162 : }
1163 : },
1164 : Ok((response_msg, _op_timer_already_observed)) => response_msg,
1165 : };
1166 :
1167 : //
1168 : // marshal & transmit response message
1169 : //
1170 :
1171 : pgb_writer.write_message_noflush(&BeMessage::CopyData(
1172 : &response_msg.serialize(protocol_version),
1173 : ))?;
1174 :
1175 : failpoint_support::sleep_millis_async!("before-pagestream-msg-flush", cancel);
1176 :
1177 : // what we want to do
1178 : let socket_fd = pgb_writer.socket_fd;
1179 : let flush_fut = pgb_writer.flush();
1180 : // metric for how long flushing takes
1181 : let flush_fut = match flushing_timer {
1182 : Some(flushing_timer) => futures::future::Either::Left(flushing_timer.measure(
1183 : Instant::now(),
1184 : flush_fut,
1185 : socket_fd,
1186 : )),
1187 : None => futures::future::Either::Right(flush_fut),
1188 : };
1189 : // do it while respecting cancellation
1190 0 : let _: () = async move {
1191 0 : tokio::select! {
1192 : biased;
1193 0 : _ = cancel.cancelled() => {
1194 : // We were requested to shut down.
1195 0 : info!("shutdown request received in page handler");
1196 0 : return Err(QueryError::Shutdown)
1197 : }
1198 0 : res = flush_fut => {
1199 0 : res?;
1200 : }
1201 : }
1202 0 : Ok(())
1203 0 : }
1204 : .await?;
1205 : }
1206 : Ok(())
1207 : }
1208 :
1209 : /// Helper which dispatches a batched message to the appropriate handler.
1210 : /// Returns a vec of results, along with the extracted trace span.
1211 0 : async fn pagestream_dispatch_batched_message(
1212 0 : &mut self,
1213 0 : batch: BatchedFeMessage,
1214 0 : io_concurrency: IoConcurrency,
1215 0 : ctx: &RequestContext,
1216 0 : ) -> Result<
1217 0 : (
1218 0 : Vec<Result<(PagestreamBeMessage, SmgrOpTimer), BatchedPageStreamError>>,
1219 0 : Span,
1220 0 : ),
1221 0 : QueryError,
1222 0 : > {
1223 0 : Ok(match batch {
1224 : BatchedFeMessage::Exists {
1225 0 : span,
1226 0 : timer,
1227 0 : shard,
1228 0 : req,
1229 0 : } => {
1230 0 : fail::fail_point!("ps::handle-pagerequest-message::exists");
1231 0 : (
1232 0 : vec![
1233 0 : self.handle_get_rel_exists_request(&*shard.upgrade()?, &req, ctx)
1234 0 : .instrument(span.clone())
1235 0 : .await
1236 0 : .map(|msg| (msg, timer))
1237 0 : .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
1238 0 : ],
1239 0 : span,
1240 : )
1241 : }
1242 : BatchedFeMessage::Nblocks {
1243 0 : span,
1244 0 : timer,
1245 0 : shard,
1246 0 : req,
1247 0 : } => {
1248 0 : fail::fail_point!("ps::handle-pagerequest-message::nblocks");
1249 0 : (
1250 0 : vec![
1251 0 : self.handle_get_nblocks_request(&*shard.upgrade()?, &req, ctx)
1252 0 : .instrument(span.clone())
1253 0 : .await
1254 0 : .map(|msg| (msg, timer))
1255 0 : .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
1256 0 : ],
1257 0 : span,
1258 : )
1259 : }
1260 : BatchedFeMessage::GetPage {
1261 0 : span,
1262 0 : shard,
1263 0 : effective_request_lsn,
1264 0 : pages,
1265 0 : } => {
1266 0 : fail::fail_point!("ps::handle-pagerequest-message::getpage");
1267 0 : (
1268 0 : {
1269 0 : let npages = pages.len();
1270 0 : trace!(npages, "handling getpage request");
1271 0 : let res = self
1272 0 : .handle_get_page_at_lsn_request_batched(
1273 0 : &*shard.upgrade()?,
1274 0 : effective_request_lsn,
1275 0 : pages,
1276 0 : io_concurrency,
1277 0 : ctx,
1278 0 : )
1279 0 : .instrument(span.clone())
1280 0 : .await;
1281 0 : assert_eq!(res.len(), npages);
1282 0 : res
1283 0 : },
1284 0 : span,
1285 : )
1286 : }
1287 : BatchedFeMessage::DbSize {
1288 0 : span,
1289 0 : timer,
1290 0 : shard,
1291 0 : req,
1292 0 : } => {
1293 0 : fail::fail_point!("ps::handle-pagerequest-message::dbsize");
1294 0 : (
1295 0 : vec![
1296 0 : self.handle_db_size_request(&*shard.upgrade()?, &req, ctx)
1297 0 : .instrument(span.clone())
1298 0 : .await
1299 0 : .map(|msg| (msg, timer))
1300 0 : .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
1301 0 : ],
1302 0 : span,
1303 : )
1304 : }
1305 : BatchedFeMessage::GetSlruSegment {
1306 0 : span,
1307 0 : timer,
1308 0 : shard,
1309 0 : req,
1310 0 : } => {
1311 0 : fail::fail_point!("ps::handle-pagerequest-message::slrusegment");
1312 0 : (
1313 0 : vec![
1314 0 : self.handle_get_slru_segment_request(&*shard.upgrade()?, &req, ctx)
1315 0 : .instrument(span.clone())
1316 0 : .await
1317 0 : .map(|msg| (msg, timer))
1318 0 : .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
1319 0 : ],
1320 0 : span,
1321 : )
1322 : }
1323 : #[cfg(feature = "testing")]
1324 : BatchedFeMessage::Test {
1325 0 : span,
1326 0 : shard,
1327 0 : requests,
1328 0 : } => {
1329 0 : fail::fail_point!("ps::handle-pagerequest-message::test");
1330 0 : (
1331 0 : {
1332 0 : let npages = requests.len();
1333 0 : trace!(npages, "handling getpage request");
1334 0 : let res = self
1335 0 : .handle_test_request_batch(&*shard.upgrade()?, requests, ctx)
1336 0 : .instrument(span.clone())
1337 0 : .await;
1338 0 : assert_eq!(res.len(), npages);
1339 0 : res
1340 0 : },
1341 0 : span,
1342 : )
1343 : }
1344 0 : BatchedFeMessage::RespondError { span, error } => {
1345 0 : // We've already decided to respond with an error, so we don't need to
1346 0 : // call the handler.
1347 0 : (vec![Err(error)], span)
1348 : }
1349 : })
1350 0 : }
1351 :
1352 : /// Pagestream sub-protocol handler.
1353 : ///
1354 : /// It is a simple request-response protocol inside a COPYBOTH session.
1355 : ///
1356 : /// # Coding Discipline
1357 : ///
1358 : /// Coding discipline within this function: all interaction with the `pgb` connection
1359 : /// needs to be sensitive to connection shutdown, currently signalled via [`Self::cancel`].
1360 : /// This is so that we can shutdown page_service quickly.
1361 : #[instrument(skip_all)]
1362 : async fn handle_pagerequests<IO>(
1363 : &mut self,
1364 : pgb: &mut PostgresBackend<IO>,
1365 : tenant_id: TenantId,
1366 : timeline_id: TimelineId,
1367 : protocol_version: PagestreamProtocolVersion,
1368 : ctx: RequestContext,
1369 : ) -> Result<(), QueryError>
1370 : where
1371 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
1372 : {
1373 : debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
1374 :
1375 : // switch client to COPYBOTH
1376 : pgb.write_message_noflush(&BeMessage::CopyBothResponse)?;
1377 : tokio::select! {
1378 : biased;
1379 : _ = self.cancel.cancelled() => {
1380 : return Err(QueryError::Shutdown)
1381 : }
1382 : res = pgb.flush() => {
1383 : res?;
1384 : }
1385 : }
1386 :
1387 : let io_concurrency = IoConcurrency::spawn_from_conf(
1388 : self.conf,
1389 : match self.gate_guard.try_clone() {
1390 : Ok(guard) => guard,
1391 : Err(_) => {
1392 : info!("shutdown request received in page handler");
1393 : return Err(QueryError::Shutdown);
1394 : }
1395 : },
1396 : );
1397 :
1398 : let pgb_reader = pgb
1399 : .split()
1400 : .context("implementation error: split pgb into reader and writer")?;
1401 :
1402 : let timeline_handles = self
1403 : .timeline_handles
1404 : .take()
1405 : .expect("implementation error: timeline_handles should not be locked");
1406 :
1407 : let request_span = info_span!("request");
1408 : let ((pgb_reader, timeline_handles), result) = match self.pipelining_config.clone() {
1409 : PageServicePipeliningConfig::Pipelined(pipelining_config) => {
1410 : self.handle_pagerequests_pipelined(
1411 : pgb,
1412 : pgb_reader,
1413 : tenant_id,
1414 : timeline_id,
1415 : timeline_handles,
1416 : request_span,
1417 : pipelining_config,
1418 : protocol_version,
1419 : io_concurrency,
1420 : &ctx,
1421 : )
1422 : .await
1423 : }
1424 : PageServicePipeliningConfig::Serial => {
1425 : self.handle_pagerequests_serial(
1426 : pgb,
1427 : pgb_reader,
1428 : tenant_id,
1429 : timeline_id,
1430 : timeline_handles,
1431 : request_span,
1432 : protocol_version,
1433 : io_concurrency,
1434 : &ctx,
1435 : )
1436 : .await
1437 : }
1438 : };
1439 :
1440 : debug!("pagestream subprotocol shut down cleanly");
1441 :
1442 : pgb.unsplit(pgb_reader)
1443 : .context("implementation error: unsplit pgb")?;
1444 :
1445 : let replaced = self.timeline_handles.replace(timeline_handles);
1446 : assert!(replaced.is_none());
1447 :
1448 : result
1449 : }
1450 :
1451 : #[allow(clippy::too_many_arguments)]
1452 0 : async fn handle_pagerequests_serial<IO>(
1453 0 : &mut self,
1454 0 : pgb_writer: &mut PostgresBackend<IO>,
1455 0 : mut pgb_reader: PostgresBackendReader<IO>,
1456 0 : tenant_id: TenantId,
1457 0 : timeline_id: TimelineId,
1458 0 : mut timeline_handles: TimelineHandles,
1459 0 : request_span: Span,
1460 0 : protocol_version: PagestreamProtocolVersion,
1461 0 : io_concurrency: IoConcurrency,
1462 0 : ctx: &RequestContext,
1463 0 : ) -> (
1464 0 : (PostgresBackendReader<IO>, TimelineHandles),
1465 0 : Result<(), QueryError>,
1466 0 : )
1467 0 : where
1468 0 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
1469 0 : {
1470 0 : let cancel = self.cancel.clone();
1471 0 : let err = loop {
1472 0 : let msg = Self::pagestream_read_message(
1473 0 : &mut pgb_reader,
1474 0 : tenant_id,
1475 0 : timeline_id,
1476 0 : &mut timeline_handles,
1477 0 : &cancel,
1478 0 : ctx,
1479 0 : protocol_version,
1480 0 : request_span.clone(),
1481 0 : )
1482 0 : .await;
1483 0 : let msg = match msg {
1484 0 : Ok(msg) => msg,
1485 0 : Err(e) => break e,
1486 : };
1487 0 : let msg = match msg {
1488 0 : Some(msg) => msg,
1489 : None => {
1490 0 : debug!("pagestream subprotocol end observed");
1491 0 : return ((pgb_reader, timeline_handles), Ok(()));
1492 : }
1493 : };
1494 :
1495 0 : let result = self
1496 0 : .pagesteam_handle_batched_message(
1497 0 : pgb_writer,
1498 0 : msg,
1499 0 : io_concurrency.clone(),
1500 0 : &cancel,
1501 0 : protocol_version,
1502 0 : ctx,
1503 0 : )
1504 0 : .await;
1505 0 : match result {
1506 0 : Ok(()) => {}
1507 0 : Err(e) => break e,
1508 : }
1509 : };
1510 0 : ((pgb_reader, timeline_handles), Err(err))
1511 0 : }
1512 :
1513 : /// # Cancel-Safety
1514 : ///
1515 : /// May leak tokio tasks if not polled to completion.
1516 : #[allow(clippy::too_many_arguments)]
1517 0 : async fn handle_pagerequests_pipelined<IO>(
1518 0 : &mut self,
1519 0 : pgb_writer: &mut PostgresBackend<IO>,
1520 0 : pgb_reader: PostgresBackendReader<IO>,
1521 0 : tenant_id: TenantId,
1522 0 : timeline_id: TimelineId,
1523 0 : mut timeline_handles: TimelineHandles,
1524 0 : request_span: Span,
1525 0 : pipelining_config: PageServicePipeliningConfigPipelined,
1526 0 : protocol_version: PagestreamProtocolVersion,
1527 0 : io_concurrency: IoConcurrency,
1528 0 : ctx: &RequestContext,
1529 0 : ) -> (
1530 0 : (PostgresBackendReader<IO>, TimelineHandles),
1531 0 : Result<(), QueryError>,
1532 0 : )
1533 0 : where
1534 0 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
1535 0 : {
1536 0 : //
1537 0 : // Pipelined pagestream handling consists of
1538 0 : // - a Batcher that reads requests off the wire and
1539 0 : // and batches them if possible,
1540 0 : // - an Executor that processes the batched requests.
1541 0 : //
1542 0 : // The batch is built up inside an `spsc_fold` channel,
1543 0 : // shared betwen Batcher (Sender) and Executor (Receiver).
1544 0 : //
1545 0 : // The Batcher continously folds client requests into the batch,
1546 0 : // while the Executor can at any time take out what's in the batch
1547 0 : // in order to process it.
1548 0 : // This means the next batch builds up while the Executor
1549 0 : // executes the last batch.
1550 0 : //
1551 0 : // CANCELLATION
1552 0 : //
1553 0 : // We run both Batcher and Executor futures to completion before
1554 0 : // returning from this function.
1555 0 : //
1556 0 : // If Executor exits first, it signals cancellation to the Batcher
1557 0 : // via a CancellationToken that is child of `self.cancel`.
1558 0 : // If Batcher exits first, it signals cancellation to the Executor
1559 0 : // by dropping the spsc_fold channel Sender.
1560 0 : //
1561 0 : // CLEAN SHUTDOWN
1562 0 : //
1563 0 : // Clean shutdown means that the client ends the COPYBOTH session.
1564 0 : // In response to such a client message, the Batcher exits.
1565 0 : // The Executor continues to run, draining the spsc_fold channel.
1566 0 : // Once drained, the spsc_fold recv will fail with a distinct error
1567 0 : // indicating that the sender disconnected.
1568 0 : // The Executor exits with Ok(()) in response to that error.
1569 0 : //
1570 0 : // Server initiated shutdown is not clean shutdown, but instead
1571 0 : // is an error Err(QueryError::Shutdown) that is propagated through
1572 0 : // error propagation.
1573 0 : //
1574 0 : // ERROR PROPAGATION
1575 0 : //
1576 0 : // When the Batcher encounter an error, it sends it as a value
1577 0 : // through the spsc_fold channel and exits afterwards.
1578 0 : // When the Executor observes such an error in the channel,
1579 0 : // it exits returning that error value.
1580 0 : //
1581 0 : // This design ensures that the Executor stage will still process
1582 0 : // the batch that was in flight when the Batcher encountered an error,
1583 0 : // thereby beahving identical to a serial implementation.
1584 0 :
1585 0 : let PageServicePipeliningConfigPipelined {
1586 0 : max_batch_size,
1587 0 : execution,
1588 0 : } = pipelining_config;
1589 :
1590 : // Macro to _define_ a pipeline stage.
1591 : macro_rules! pipeline_stage {
1592 : ($name:literal, $cancel:expr, $make_fut:expr) => {{
1593 : let cancel: CancellationToken = $cancel;
1594 : let stage_fut = $make_fut(cancel.clone());
1595 0 : async move {
1596 0 : scopeguard::defer! {
1597 0 : debug!("exiting");
1598 0 : }
1599 0 : timed_after_cancellation(stage_fut, $name, Duration::from_millis(100), &cancel)
1600 0 : .await
1601 0 : }
1602 : .instrument(tracing::info_span!($name))
1603 : }};
1604 : }
1605 :
1606 : //
1607 : // Batcher
1608 : //
1609 :
1610 0 : let cancel_batcher = self.cancel.child_token();
1611 0 : let (mut batch_tx, mut batch_rx) = spsc_fold::channel();
1612 0 : let batcher = pipeline_stage!("batcher", cancel_batcher.clone(), move |cancel_batcher| {
1613 0 : let ctx = ctx.attached_child();
1614 0 : async move {
1615 0 : let mut pgb_reader = pgb_reader;
1616 0 : let mut exit = false;
1617 0 : while !exit {
1618 0 : let read_res = Self::pagestream_read_message(
1619 0 : &mut pgb_reader,
1620 0 : tenant_id,
1621 0 : timeline_id,
1622 0 : &mut timeline_handles,
1623 0 : &cancel_batcher,
1624 0 : &ctx,
1625 0 : protocol_version,
1626 0 : request_span.clone(),
1627 0 : )
1628 0 : .await;
1629 0 : let Some(read_res) = read_res.transpose() else {
1630 0 : debug!("client-initiated shutdown");
1631 0 : break;
1632 : };
1633 0 : exit |= read_res.is_err();
1634 0 : let could_send = batch_tx
1635 0 : .send(read_res, |batch, res| {
1636 0 : Self::pagestream_do_batch(max_batch_size, batch, res)
1637 0 : })
1638 0 : .await;
1639 0 : exit |= could_send.is_err();
1640 : }
1641 0 : (pgb_reader, timeline_handles)
1642 0 : }
1643 0 : });
1644 :
1645 : //
1646 : // Executor
1647 : //
1648 :
1649 0 : let executor = pipeline_stage!("executor", self.cancel.clone(), move |cancel| {
1650 0 : let ctx = ctx.attached_child();
1651 0 : async move {
1652 0 : let _cancel_batcher = cancel_batcher.drop_guard();
1653 : loop {
1654 0 : let maybe_batch = batch_rx.recv().await;
1655 0 : let batch = match maybe_batch {
1656 0 : Ok(batch) => batch,
1657 : Err(spsc_fold::RecvError::SenderGone) => {
1658 0 : debug!("upstream gone");
1659 0 : return Ok(());
1660 : }
1661 : };
1662 0 : let batch = match batch {
1663 0 : Ok(batch) => batch,
1664 0 : Err(e) => {
1665 0 : return Err(e);
1666 : }
1667 : };
1668 0 : self.pagesteam_handle_batched_message(
1669 0 : pgb_writer,
1670 0 : batch,
1671 0 : io_concurrency.clone(),
1672 0 : &cancel,
1673 0 : protocol_version,
1674 0 : &ctx,
1675 0 : )
1676 0 : .await?;
1677 : }
1678 0 : }
1679 0 : });
1680 :
1681 : //
1682 : // Execute the stages.
1683 : //
1684 :
1685 0 : match execution {
1686 : PageServiceProtocolPipelinedExecutionStrategy::ConcurrentFutures => {
1687 0 : tokio::join!(batcher, executor)
1688 : }
1689 : PageServiceProtocolPipelinedExecutionStrategy::Tasks => {
1690 : // These tasks are not tracked anywhere.
1691 0 : let read_messages_task = tokio::spawn(batcher);
1692 0 : let (read_messages_task_res, executor_res_) =
1693 0 : tokio::join!(read_messages_task, executor,);
1694 0 : (
1695 0 : read_messages_task_res.expect("propagated panic from read_messages"),
1696 0 : executor_res_,
1697 0 : )
1698 : }
1699 : }
1700 0 : }
1701 :
1702 : /// Helper function to handle the LSN from client request.
1703 : ///
1704 : /// Each GetPage (and Exists and Nblocks) request includes information about
1705 : /// which version of the page is being requested. The primary compute node
1706 : /// will always request the latest page version, by setting 'request_lsn' to
1707 : /// the last inserted or flushed WAL position, while a standby will request
1708 : /// a version at the LSN that it's currently caught up to.
1709 : ///
1710 : /// In either case, if the page server hasn't received the WAL up to the
1711 : /// requested LSN yet, we will wait for it to arrive. The return value is
1712 : /// the LSN that should be used to look up the page versions.
1713 : ///
1714 : /// In addition to the request LSN, each request carries another LSN,
1715 : /// 'not_modified_since', which is a hint to the pageserver that the client
1716 : /// knows that the page has not been modified between 'not_modified_since'
1717 : /// and the request LSN. This allows skipping the wait, as long as the WAL
1718 : /// up to 'not_modified_since' has arrived. If the client doesn't have any
1719 : /// information about when the page was modified, it will use
1720 : /// not_modified_since == lsn. If the client lies and sends a too low
1721 : /// not_modified_hint such that there are in fact later page versions, the
1722 : /// behavior is undefined: the pageserver may return any of the page versions
1723 : /// or an error.
1724 0 : async fn wait_or_get_last_lsn(
1725 0 : timeline: &Timeline,
1726 0 : request_lsn: Lsn,
1727 0 : not_modified_since: Lsn,
1728 0 : latest_gc_cutoff_lsn: &RcuReadGuard<Lsn>,
1729 0 : ctx: &RequestContext,
1730 0 : ) -> Result<Lsn, PageStreamError> {
1731 0 : let last_record_lsn = timeline.get_last_record_lsn();
1732 0 :
1733 0 : // Sanity check the request
1734 0 : if request_lsn < not_modified_since {
1735 0 : return Err(PageStreamError::BadRequest(
1736 0 : format!(
1737 0 : "invalid request with request LSN {} and not_modified_since {}",
1738 0 : request_lsn, not_modified_since,
1739 0 : )
1740 0 : .into(),
1741 0 : ));
1742 0 : }
1743 0 :
1744 0 : // Check explicitly for INVALID just to get a less scary error message if the request is obviously bogus
1745 0 : if request_lsn == Lsn::INVALID {
1746 0 : return Err(PageStreamError::BadRequest(
1747 0 : "invalid LSN(0) in request".into(),
1748 0 : ));
1749 0 : }
1750 0 :
1751 0 : // Clients should only read from recent LSNs on their timeline, or from locations holding an LSN lease.
1752 0 : //
1753 0 : // We may have older data available, but we make a best effort to detect this case and return an error,
1754 0 : // to distinguish a misbehaving client (asking for old LSN) from a storage issue (data missing at a legitimate LSN).
1755 0 : if request_lsn < **latest_gc_cutoff_lsn && !timeline.is_gc_blocked_by_lsn_lease_deadline() {
1756 0 : let gc_info = &timeline.gc_info.read().unwrap();
1757 0 : if !gc_info.lsn_covered_by_lease(request_lsn) {
1758 0 : return Err(
1759 0 : PageStreamError::BadRequest(format!(
1760 0 : "tried to request a page version that was garbage collected. requested at {} gc cutoff {}",
1761 0 : request_lsn, **latest_gc_cutoff_lsn
1762 0 : ).into())
1763 0 : );
1764 0 : }
1765 0 : }
1766 :
1767 : // Wait for WAL up to 'not_modified_since' to arrive, if necessary
1768 0 : if not_modified_since > last_record_lsn {
1769 0 : timeline
1770 0 : .wait_lsn(
1771 0 : not_modified_since,
1772 0 : crate::tenant::timeline::WaitLsnWaiter::PageService,
1773 0 : timeline::WaitLsnTimeout::Default,
1774 0 : ctx,
1775 0 : )
1776 0 : .await?;
1777 : // Since we waited for 'not_modified_since' to arrive, that is now the last
1778 : // record LSN. (Or close enough for our purposes; the last-record LSN can
1779 : // advance immediately after we return anyway)
1780 0 : Ok(not_modified_since)
1781 : } else {
1782 : // It might be better to use max(not_modified_since, latest_gc_cutoff_lsn)
1783 : // here instead. That would give the same result, since we know that there
1784 : // haven't been any modifications since 'not_modified_since'. Using an older
1785 : // LSN might be faster, because that could allow skipping recent layers when
1786 : // finding the page. However, we have historically used 'last_record_lsn', so
1787 : // stick to that for now.
1788 0 : Ok(std::cmp::min(last_record_lsn, request_lsn))
1789 : }
1790 0 : }
1791 :
1792 : /// Handles the lsn lease request.
1793 : /// If a lease cannot be obtained, the client will receive NULL.
1794 : #[instrument(skip_all, fields(shard_id, %lsn))]
1795 : async fn handle_make_lsn_lease<IO>(
1796 : &mut self,
1797 : pgb: &mut PostgresBackend<IO>,
1798 : tenant_shard_id: TenantShardId,
1799 : timeline_id: TimelineId,
1800 : lsn: Lsn,
1801 : ctx: &RequestContext,
1802 : ) -> Result<(), QueryError>
1803 : where
1804 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
1805 : {
1806 : let timeline = self
1807 : .timeline_handles
1808 : .as_mut()
1809 : .unwrap()
1810 : .get(
1811 : tenant_shard_id.tenant_id,
1812 : timeline_id,
1813 : ShardSelector::Known(tenant_shard_id.to_index()),
1814 : )
1815 : .await?;
1816 : set_tracing_field_shard_id(&timeline);
1817 :
1818 : let lease = timeline
1819 : .renew_lsn_lease(lsn, timeline.get_lsn_lease_length(), ctx)
1820 0 : .inspect_err(|e| {
1821 0 : warn!("{e}");
1822 0 : })
1823 : .ok();
1824 0 : let valid_until_str = lease.map(|l| {
1825 0 : l.valid_until
1826 0 : .duration_since(SystemTime::UNIX_EPOCH)
1827 0 : .expect("valid_until is earlier than UNIX_EPOCH")
1828 0 : .as_millis()
1829 0 : .to_string()
1830 0 : });
1831 :
1832 : info!(
1833 : "acquired lease for {} until {}",
1834 : lsn,
1835 : valid_until_str.as_deref().unwrap_or("<unknown>")
1836 : );
1837 :
1838 0 : let bytes = valid_until_str.as_ref().map(|x| x.as_bytes());
1839 :
1840 : pgb.write_message_noflush(&BeMessage::RowDescription(&[RowDescriptor::text_col(
1841 : b"valid_until",
1842 : )]))?
1843 : .write_message_noflush(&BeMessage::DataRow(&[bytes]))?;
1844 :
1845 : Ok(())
1846 : }
1847 :
1848 : #[instrument(skip_all, fields(shard_id))]
1849 : async fn handle_get_rel_exists_request(
1850 : &mut self,
1851 : timeline: &Timeline,
1852 : req: &PagestreamExistsRequest,
1853 : ctx: &RequestContext,
1854 : ) -> Result<PagestreamBeMessage, PageStreamError> {
1855 : let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
1856 : let lsn = Self::wait_or_get_last_lsn(
1857 : timeline,
1858 : req.hdr.request_lsn,
1859 : req.hdr.not_modified_since,
1860 : &latest_gc_cutoff_lsn,
1861 : ctx,
1862 : )
1863 : .await?;
1864 :
1865 : let exists = timeline
1866 : .get_rel_exists(req.rel, Version::Lsn(lsn), ctx)
1867 : .await?;
1868 :
1869 : Ok(PagestreamBeMessage::Exists(PagestreamExistsResponse {
1870 : req: *req,
1871 : exists,
1872 : }))
1873 : }
1874 :
1875 : #[instrument(skip_all, fields(shard_id))]
1876 : async fn handle_get_nblocks_request(
1877 : &mut self,
1878 : timeline: &Timeline,
1879 : req: &PagestreamNblocksRequest,
1880 : ctx: &RequestContext,
1881 : ) -> Result<PagestreamBeMessage, PageStreamError> {
1882 : let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
1883 : let lsn = Self::wait_or_get_last_lsn(
1884 : timeline,
1885 : req.hdr.request_lsn,
1886 : req.hdr.not_modified_since,
1887 : &latest_gc_cutoff_lsn,
1888 : ctx,
1889 : )
1890 : .await?;
1891 :
1892 : let n_blocks = timeline
1893 : .get_rel_size(req.rel, Version::Lsn(lsn), ctx)
1894 : .await?;
1895 :
1896 : Ok(PagestreamBeMessage::Nblocks(PagestreamNblocksResponse {
1897 : req: *req,
1898 : n_blocks,
1899 : }))
1900 : }
1901 :
1902 : #[instrument(skip_all, fields(shard_id))]
1903 : async fn handle_db_size_request(
1904 : &mut self,
1905 : timeline: &Timeline,
1906 : req: &PagestreamDbSizeRequest,
1907 : ctx: &RequestContext,
1908 : ) -> Result<PagestreamBeMessage, PageStreamError> {
1909 : let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
1910 : let lsn = Self::wait_or_get_last_lsn(
1911 : timeline,
1912 : req.hdr.request_lsn,
1913 : req.hdr.not_modified_since,
1914 : &latest_gc_cutoff_lsn,
1915 : ctx,
1916 : )
1917 : .await?;
1918 :
1919 : let total_blocks = timeline
1920 : .get_db_size(DEFAULTTABLESPACE_OID, req.dbnode, Version::Lsn(lsn), ctx)
1921 : .await?;
1922 : let db_size = total_blocks as i64 * BLCKSZ as i64;
1923 :
1924 : Ok(PagestreamBeMessage::DbSize(PagestreamDbSizeResponse {
1925 : req: *req,
1926 : db_size,
1927 : }))
1928 : }
1929 :
1930 : #[instrument(skip_all)]
1931 : async fn handle_get_page_at_lsn_request_batched(
1932 : &mut self,
1933 : timeline: &Timeline,
1934 : effective_lsn: Lsn,
1935 : requests: smallvec::SmallVec<[BatchedGetPageRequest; 1]>,
1936 : io_concurrency: IoConcurrency,
1937 : ctx: &RequestContext,
1938 : ) -> Vec<Result<(PagestreamBeMessage, SmgrOpTimer), BatchedPageStreamError>> {
1939 : debug_assert_current_span_has_tenant_and_timeline_id();
1940 :
1941 : timeline
1942 : .query_metrics
1943 : .observe_getpage_batch_start(requests.len());
1944 :
1945 : // If a page trace is running, submit an event for this request.
1946 : if let Some(page_trace) = timeline.page_trace.load().as_ref() {
1947 : let time = SystemTime::now();
1948 : for batch in &requests {
1949 : let key = rel_block_to_key(batch.req.rel, batch.req.blkno).to_compact();
1950 : // Ignore error (trace buffer may be full or tracer may have disconnected).
1951 : _ = page_trace.try_send(PageTraceEvent {
1952 : key,
1953 : effective_lsn,
1954 : time,
1955 : });
1956 : }
1957 : }
1958 :
1959 : let results = timeline
1960 : .get_rel_page_at_lsn_batched(
1961 0 : requests.iter().map(|p| (&p.req.rel, &p.req.blkno)),
1962 : effective_lsn,
1963 : io_concurrency,
1964 : ctx,
1965 : )
1966 : .await;
1967 : assert_eq!(results.len(), requests.len());
1968 :
1969 : // TODO: avoid creating the new Vec here
1970 : Vec::from_iter(
1971 : requests
1972 : .into_iter()
1973 : .zip(results.into_iter())
1974 0 : .map(|(req, res)| {
1975 0 : res.map(|page| {
1976 0 : (
1977 0 : PagestreamBeMessage::GetPage(models::PagestreamGetPageResponse {
1978 0 : req: req.req,
1979 0 : page,
1980 0 : }),
1981 0 : req.timer,
1982 0 : )
1983 0 : })
1984 0 : .map_err(|e| BatchedPageStreamError {
1985 0 : err: PageStreamError::from(e),
1986 0 : req: req.req.hdr,
1987 0 : })
1988 0 : }),
1989 : )
1990 : }
1991 :
1992 : #[instrument(skip_all, fields(shard_id))]
1993 : async fn handle_get_slru_segment_request(
1994 : &mut self,
1995 : timeline: &Timeline,
1996 : req: &PagestreamGetSlruSegmentRequest,
1997 : ctx: &RequestContext,
1998 : ) -> Result<PagestreamBeMessage, PageStreamError> {
1999 : let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
2000 : let lsn = Self::wait_or_get_last_lsn(
2001 : timeline,
2002 : req.hdr.request_lsn,
2003 : req.hdr.not_modified_since,
2004 : &latest_gc_cutoff_lsn,
2005 : ctx,
2006 : )
2007 : .await?;
2008 :
2009 : let kind = SlruKind::from_repr(req.kind)
2010 : .ok_or(PageStreamError::BadRequest("invalid SLRU kind".into()))?;
2011 : let segment = timeline.get_slru_segment(kind, req.segno, lsn, ctx).await?;
2012 :
2013 : Ok(PagestreamBeMessage::GetSlruSegment(
2014 : PagestreamGetSlruSegmentResponse { req: *req, segment },
2015 : ))
2016 : }
2017 :
2018 : // NB: this impl mimics what we do for batched getpage requests.
2019 : #[cfg(feature = "testing")]
2020 : #[instrument(skip_all, fields(shard_id))]
2021 : async fn handle_test_request_batch(
2022 : &mut self,
2023 : timeline: &Timeline,
2024 : requests: Vec<BatchedTestRequest>,
2025 : _ctx: &RequestContext,
2026 : ) -> Vec<Result<(PagestreamBeMessage, SmgrOpTimer), BatchedPageStreamError>> {
2027 : // real requests would do something with the timeline
2028 : let mut results = Vec::with_capacity(requests.len());
2029 : for _req in requests.iter() {
2030 : tokio::task::yield_now().await;
2031 :
2032 : results.push({
2033 : if timeline.cancel.is_cancelled() {
2034 : Err(PageReconstructError::Cancelled)
2035 : } else {
2036 : Ok(())
2037 : }
2038 : });
2039 : }
2040 :
2041 : // TODO: avoid creating the new Vec here
2042 : Vec::from_iter(
2043 : requests
2044 : .into_iter()
2045 : .zip(results.into_iter())
2046 0 : .map(|(req, res)| {
2047 0 : res.map(|()| {
2048 0 : (
2049 0 : PagestreamBeMessage::Test(models::PagestreamTestResponse {
2050 0 : req: req.req.clone(),
2051 0 : }),
2052 0 : req.timer,
2053 0 : )
2054 0 : })
2055 0 : .map_err(|e| BatchedPageStreamError {
2056 0 : err: PageStreamError::from(e),
2057 0 : req: req.req.hdr,
2058 0 : })
2059 0 : }),
2060 : )
2061 : }
2062 :
2063 : /// Note on "fullbackup":
2064 : /// Full basebackups should only be used for debugging purposes.
2065 : /// Originally, it was introduced to enable breaking storage format changes,
2066 : /// but that is not applicable anymore.
2067 : ///
2068 : /// # Coding Discipline
2069 : ///
2070 : /// Coding discipline within this function: all interaction with the `pgb` connection
2071 : /// needs to be sensitive to connection shutdown, currently signalled via [`Self::cancel`].
2072 : /// This is so that we can shutdown page_service quickly.
2073 : ///
2074 : /// TODO: wrap the pgb that we pass to the basebackup handler so that it's sensitive
2075 : /// to connection cancellation.
2076 : #[allow(clippy::too_many_arguments)]
2077 : #[instrument(skip_all, fields(shard_id, ?lsn, ?prev_lsn, %full_backup))]
2078 : async fn handle_basebackup_request<IO>(
2079 : &mut self,
2080 : pgb: &mut PostgresBackend<IO>,
2081 : tenant_id: TenantId,
2082 : timeline_id: TimelineId,
2083 : lsn: Option<Lsn>,
2084 : prev_lsn: Option<Lsn>,
2085 : full_backup: bool,
2086 : gzip: bool,
2087 : replica: bool,
2088 : ctx: &RequestContext,
2089 : ) -> Result<(), QueryError>
2090 : where
2091 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
2092 : {
2093 0 : fn map_basebackup_error(err: BasebackupError) -> QueryError {
2094 0 : match err {
2095 : // TODO: passthrough the error site to the final error message?
2096 0 : BasebackupError::Client(e, _) => QueryError::Disconnected(ConnectionError::Io(e)),
2097 0 : BasebackupError::Server(e) => QueryError::Other(e),
2098 : }
2099 0 : }
2100 :
2101 : let started = std::time::Instant::now();
2102 :
2103 : let timeline = self
2104 : .timeline_handles
2105 : .as_mut()
2106 : .unwrap()
2107 : .get(tenant_id, timeline_id, ShardSelector::Zero)
2108 : .await?;
2109 : set_tracing_field_shard_id(&timeline);
2110 :
2111 : if timeline.is_archived() == Some(true) {
2112 : tracing::info!(
2113 : "timeline {tenant_id}/{timeline_id} is archived, but got basebackup request for it."
2114 : );
2115 : return Err(QueryError::NotFound("timeline is archived".into()));
2116 : }
2117 :
2118 : let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
2119 : if let Some(lsn) = lsn {
2120 : // Backup was requested at a particular LSN. Wait for it to arrive.
2121 : info!("waiting for {}", lsn);
2122 : timeline
2123 : .wait_lsn(
2124 : lsn,
2125 : crate::tenant::timeline::WaitLsnWaiter::PageService,
2126 : crate::tenant::timeline::WaitLsnTimeout::Default,
2127 : ctx,
2128 : )
2129 : .await?;
2130 : timeline
2131 : .check_lsn_is_in_scope(lsn, &latest_gc_cutoff_lsn)
2132 : .context("invalid basebackup lsn")?;
2133 : }
2134 :
2135 : let lsn_awaited_after = started.elapsed();
2136 :
2137 : // switch client to COPYOUT
2138 : pgb.write_message_noflush(&BeMessage::CopyOutResponse)
2139 : .map_err(QueryError::Disconnected)?;
2140 : self.flush_cancellable(pgb, &self.cancel).await?;
2141 :
2142 : // Send a tarball of the latest layer on the timeline. Compress if not
2143 : // fullbackup. TODO Compress in that case too (tests need to be updated)
2144 : if full_backup {
2145 : let mut writer = pgb.copyout_writer();
2146 : basebackup::send_basebackup_tarball(
2147 : &mut writer,
2148 : &timeline,
2149 : lsn,
2150 : prev_lsn,
2151 : full_backup,
2152 : replica,
2153 : ctx,
2154 : )
2155 : .await
2156 : .map_err(map_basebackup_error)?;
2157 : } else {
2158 : let mut writer = BufWriter::new(pgb.copyout_writer());
2159 : if gzip {
2160 : let mut encoder = GzipEncoder::with_quality(
2161 : &mut writer,
2162 : // NOTE using fast compression because it's on the critical path
2163 : // for compute startup. For an empty database, we get
2164 : // <100KB with this method. The Level::Best compression method
2165 : // gives us <20KB, but maybe we should add basebackup caching
2166 : // on compute shutdown first.
2167 : async_compression::Level::Fastest,
2168 : );
2169 : basebackup::send_basebackup_tarball(
2170 : &mut encoder,
2171 : &timeline,
2172 : lsn,
2173 : prev_lsn,
2174 : full_backup,
2175 : replica,
2176 : ctx,
2177 : )
2178 : .await
2179 : .map_err(map_basebackup_error)?;
2180 : // shutdown the encoder to ensure the gzip footer is written
2181 : encoder
2182 : .shutdown()
2183 : .await
2184 0 : .map_err(|e| QueryError::Disconnected(ConnectionError::Io(e)))?;
2185 : } else {
2186 : basebackup::send_basebackup_tarball(
2187 : &mut writer,
2188 : &timeline,
2189 : lsn,
2190 : prev_lsn,
2191 : full_backup,
2192 : replica,
2193 : ctx,
2194 : )
2195 : .await
2196 : .map_err(map_basebackup_error)?;
2197 : }
2198 0 : writer.flush().await.map_err(|e| {
2199 0 : map_basebackup_error(BasebackupError::Client(
2200 0 : e,
2201 0 : "handle_basebackup_request,flush",
2202 0 : ))
2203 0 : })?;
2204 : }
2205 :
2206 : pgb.write_message_noflush(&BeMessage::CopyDone)
2207 : .map_err(QueryError::Disconnected)?;
2208 : self.flush_cancellable(pgb, &timeline.cancel).await?;
2209 :
2210 : let basebackup_after = started
2211 : .elapsed()
2212 : .checked_sub(lsn_awaited_after)
2213 : .unwrap_or(Duration::ZERO);
2214 :
2215 : info!(
2216 : lsn_await_millis = lsn_awaited_after.as_millis(),
2217 : basebackup_millis = basebackup_after.as_millis(),
2218 : "basebackup complete"
2219 : );
2220 :
2221 : Ok(())
2222 : }
2223 :
2224 : // when accessing management api supply None as an argument
2225 : // when using to authorize tenant pass corresponding tenant id
2226 0 : fn check_permission(&self, tenant_id: Option<TenantId>) -> Result<(), QueryError> {
2227 0 : if self.auth.is_none() {
2228 : // auth is set to Trust, nothing to check so just return ok
2229 0 : return Ok(());
2230 0 : }
2231 0 : // auth is some, just checked above, when auth is some
2232 0 : // then claims are always present because of checks during connection init
2233 0 : // so this expect won't trigger
2234 0 : let claims = self
2235 0 : .claims
2236 0 : .as_ref()
2237 0 : .expect("claims presence already checked");
2238 0 : check_permission(claims, tenant_id).map_err(|e| QueryError::Unauthorized(e.0))
2239 0 : }
2240 : }
2241 :
2242 : /// `basebackup tenant timeline [lsn] [--gzip] [--replica]`
2243 : #[derive(Debug, Clone, Eq, PartialEq)]
2244 : struct BaseBackupCmd {
2245 : tenant_id: TenantId,
2246 : timeline_id: TimelineId,
2247 : lsn: Option<Lsn>,
2248 : gzip: bool,
2249 : replica: bool,
2250 : }
2251 :
2252 : /// `fullbackup tenant timeline [lsn] [prev_lsn]`
2253 : #[derive(Debug, Clone, Eq, PartialEq)]
2254 : struct FullBackupCmd {
2255 : tenant_id: TenantId,
2256 : timeline_id: TimelineId,
2257 : lsn: Option<Lsn>,
2258 : prev_lsn: Option<Lsn>,
2259 : }
2260 :
2261 : /// `pagestream_v2 tenant timeline`
2262 : #[derive(Debug, Clone, Eq, PartialEq)]
2263 : struct PageStreamCmd {
2264 : tenant_id: TenantId,
2265 : timeline_id: TimelineId,
2266 : protocol_version: PagestreamProtocolVersion,
2267 : }
2268 :
2269 : /// `lease lsn tenant timeline lsn`
2270 : #[derive(Debug, Clone, Eq, PartialEq)]
2271 : struct LeaseLsnCmd {
2272 : tenant_shard_id: TenantShardId,
2273 : timeline_id: TimelineId,
2274 : lsn: Lsn,
2275 : }
2276 :
2277 : #[derive(Debug, Clone, Eq, PartialEq)]
2278 : enum PageServiceCmd {
2279 : Set,
2280 : PageStream(PageStreamCmd),
2281 : BaseBackup(BaseBackupCmd),
2282 : FullBackup(FullBackupCmd),
2283 : LeaseLsn(LeaseLsnCmd),
2284 : }
2285 :
2286 : impl PageStreamCmd {
2287 12 : fn parse(query: &str, protocol_version: PagestreamProtocolVersion) -> anyhow::Result<Self> {
2288 12 : let parameters = query.split_whitespace().collect_vec();
2289 12 : if parameters.len() != 2 {
2290 4 : bail!(
2291 4 : "invalid number of parameters for pagestream command: {}",
2292 4 : query
2293 4 : );
2294 8 : }
2295 8 : let tenant_id = TenantId::from_str(parameters[0])
2296 8 : .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
2297 4 : let timeline_id = TimelineId::from_str(parameters[1])
2298 4 : .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
2299 4 : Ok(Self {
2300 4 : tenant_id,
2301 4 : timeline_id,
2302 4 : protocol_version,
2303 4 : })
2304 12 : }
2305 : }
2306 :
2307 : impl FullBackupCmd {
2308 8 : fn parse(query: &str) -> anyhow::Result<Self> {
2309 8 : let parameters = query.split_whitespace().collect_vec();
2310 8 : if parameters.len() < 2 || parameters.len() > 4 {
2311 0 : bail!(
2312 0 : "invalid number of parameters for basebackup command: {}",
2313 0 : query
2314 0 : );
2315 8 : }
2316 8 : let tenant_id = TenantId::from_str(parameters[0])
2317 8 : .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
2318 8 : let timeline_id = TimelineId::from_str(parameters[1])
2319 8 : .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
2320 : // The caller is responsible for providing correct lsn and prev_lsn.
2321 8 : let lsn = if let Some(lsn_str) = parameters.get(2) {
2322 : Some(
2323 4 : Lsn::from_str(lsn_str)
2324 4 : .with_context(|| format!("Failed to parse Lsn from {lsn_str}"))?,
2325 : )
2326 : } else {
2327 4 : None
2328 : };
2329 8 : let prev_lsn = if let Some(prev_lsn_str) = parameters.get(3) {
2330 : Some(
2331 4 : Lsn::from_str(prev_lsn_str)
2332 4 : .with_context(|| format!("Failed to parse Lsn from {prev_lsn_str}"))?,
2333 : )
2334 : } else {
2335 4 : None
2336 : };
2337 8 : Ok(Self {
2338 8 : tenant_id,
2339 8 : timeline_id,
2340 8 : lsn,
2341 8 : prev_lsn,
2342 8 : })
2343 8 : }
2344 : }
2345 :
2346 : impl BaseBackupCmd {
2347 36 : fn parse(query: &str) -> anyhow::Result<Self> {
2348 36 : let parameters = query.split_whitespace().collect_vec();
2349 36 : if parameters.len() < 2 {
2350 0 : bail!(
2351 0 : "invalid number of parameters for basebackup command: {}",
2352 0 : query
2353 0 : );
2354 36 : }
2355 36 : let tenant_id = TenantId::from_str(parameters[0])
2356 36 : .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
2357 36 : let timeline_id = TimelineId::from_str(parameters[1])
2358 36 : .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
2359 : let lsn;
2360 : let flags_parse_from;
2361 36 : if let Some(maybe_lsn) = parameters.get(2) {
2362 32 : if *maybe_lsn == "latest" {
2363 4 : lsn = None;
2364 4 : flags_parse_from = 3;
2365 28 : } else if maybe_lsn.starts_with("--") {
2366 20 : lsn = None;
2367 20 : flags_parse_from = 2;
2368 20 : } else {
2369 : lsn = Some(
2370 8 : Lsn::from_str(maybe_lsn)
2371 8 : .with_context(|| format!("Failed to parse lsn from {maybe_lsn}"))?,
2372 : );
2373 8 : flags_parse_from = 3;
2374 : }
2375 4 : } else {
2376 4 : lsn = None;
2377 4 : flags_parse_from = 2;
2378 4 : }
2379 :
2380 36 : let mut gzip = false;
2381 36 : let mut replica = false;
2382 :
2383 44 : for ¶m in ¶meters[flags_parse_from..] {
2384 44 : match param {
2385 44 : "--gzip" => {
2386 28 : if gzip {
2387 4 : bail!("duplicate parameter for basebackup command: {param}")
2388 24 : }
2389 24 : gzip = true
2390 : }
2391 16 : "--replica" => {
2392 8 : if replica {
2393 0 : bail!("duplicate parameter for basebackup command: {param}")
2394 8 : }
2395 8 : replica = true
2396 : }
2397 8 : _ => bail!("invalid parameter for basebackup command: {param}"),
2398 : }
2399 : }
2400 24 : Ok(Self {
2401 24 : tenant_id,
2402 24 : timeline_id,
2403 24 : lsn,
2404 24 : gzip,
2405 24 : replica,
2406 24 : })
2407 36 : }
2408 : }
2409 :
2410 : impl LeaseLsnCmd {
2411 8 : fn parse(query: &str) -> anyhow::Result<Self> {
2412 8 : let parameters = query.split_whitespace().collect_vec();
2413 8 : if parameters.len() != 3 {
2414 0 : bail!(
2415 0 : "invalid number of parameters for lease lsn command: {}",
2416 0 : query
2417 0 : );
2418 8 : }
2419 8 : let tenant_shard_id = TenantShardId::from_str(parameters[0])
2420 8 : .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
2421 8 : let timeline_id = TimelineId::from_str(parameters[1])
2422 8 : .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
2423 8 : let lsn = Lsn::from_str(parameters[2])
2424 8 : .with_context(|| format!("Failed to parse lsn from {}", parameters[2]))?;
2425 8 : Ok(Self {
2426 8 : tenant_shard_id,
2427 8 : timeline_id,
2428 8 : lsn,
2429 8 : })
2430 8 : }
2431 : }
2432 :
2433 : impl PageServiceCmd {
2434 84 : fn parse(query: &str) -> anyhow::Result<Self> {
2435 84 : let query = query.trim();
2436 84 : let Some((cmd, other)) = query.split_once(' ') else {
2437 8 : bail!("cannot parse query: {query}")
2438 : };
2439 76 : match cmd.to_ascii_lowercase().as_str() {
2440 76 : "pagestream_v2" => Ok(Self::PageStream(PageStreamCmd::parse(
2441 12 : other,
2442 12 : PagestreamProtocolVersion::V2,
2443 12 : )?)),
2444 64 : "pagestream_v3" => Ok(Self::PageStream(PageStreamCmd::parse(
2445 0 : other,
2446 0 : PagestreamProtocolVersion::V3,
2447 0 : )?)),
2448 64 : "basebackup" => Ok(Self::BaseBackup(BaseBackupCmd::parse(other)?)),
2449 28 : "fullbackup" => Ok(Self::FullBackup(FullBackupCmd::parse(other)?)),
2450 20 : "lease" => {
2451 12 : let Some((cmd2, other)) = other.split_once(' ') else {
2452 0 : bail!("invalid lease command: {cmd}");
2453 : };
2454 12 : let cmd2 = cmd2.to_ascii_lowercase();
2455 12 : if cmd2 == "lsn" {
2456 8 : Ok(Self::LeaseLsn(LeaseLsnCmd::parse(other)?))
2457 : } else {
2458 4 : bail!("invalid lease command: {cmd}");
2459 : }
2460 : }
2461 8 : "set" => Ok(Self::Set),
2462 0 : _ => Err(anyhow::anyhow!("unsupported command {cmd} in {query}")),
2463 : }
2464 84 : }
2465 : }
2466 :
2467 : impl<IO> postgres_backend::Handler<IO> for PageServerHandler
2468 : where
2469 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
2470 : {
2471 0 : fn check_auth_jwt(
2472 0 : &mut self,
2473 0 : _pgb: &mut PostgresBackend<IO>,
2474 0 : jwt_response: &[u8],
2475 0 : ) -> Result<(), QueryError> {
2476 : // this unwrap is never triggered, because check_auth_jwt only called when auth_type is NeonJWT
2477 : // which requires auth to be present
2478 0 : let data = self
2479 0 : .auth
2480 0 : .as_ref()
2481 0 : .unwrap()
2482 0 : .decode(str::from_utf8(jwt_response).context("jwt response is not UTF-8")?)
2483 0 : .map_err(|e| QueryError::Unauthorized(e.0))?;
2484 :
2485 0 : if matches!(data.claims.scope, Scope::Tenant) && data.claims.tenant_id.is_none() {
2486 0 : return Err(QueryError::Unauthorized(
2487 0 : "jwt token scope is Tenant, but tenant id is missing".into(),
2488 0 : ));
2489 0 : }
2490 0 :
2491 0 : debug!(
2492 0 : "jwt scope check succeeded for scope: {:#?} by tenant id: {:?}",
2493 : data.claims.scope, data.claims.tenant_id,
2494 : );
2495 :
2496 0 : self.claims = Some(data.claims);
2497 0 : Ok(())
2498 0 : }
2499 :
2500 0 : fn startup(
2501 0 : &mut self,
2502 0 : _pgb: &mut PostgresBackend<IO>,
2503 0 : sm: &FeStartupPacket,
2504 0 : ) -> Result<(), QueryError> {
2505 0 : fail::fail_point!("ps::connection-start::startup-packet");
2506 :
2507 0 : if let FeStartupPacket::StartupMessage { params, .. } = sm {
2508 0 : if let Some(app_name) = params.get("application_name") {
2509 0 : Span::current().record("application_name", field::display(app_name));
2510 0 : }
2511 0 : };
2512 :
2513 0 : Ok(())
2514 0 : }
2515 :
2516 : #[instrument(skip_all, fields(tenant_id, timeline_id))]
2517 : async fn process_query(
2518 : &mut self,
2519 : pgb: &mut PostgresBackend<IO>,
2520 : query_string: &str,
2521 : ) -> Result<(), QueryError> {
2522 0 : fail::fail_point!("simulated-bad-compute-connection", |_| {
2523 0 : info!("Hit failpoint for bad connection");
2524 0 : Err(QueryError::SimulatedConnectionError)
2525 0 : });
2526 :
2527 : fail::fail_point!("ps::connection-start::process-query");
2528 :
2529 : let ctx = self.connection_ctx.attached_child();
2530 : debug!("process query {query_string}");
2531 : let query = PageServiceCmd::parse(query_string)?;
2532 : match query {
2533 : PageServiceCmd::PageStream(PageStreamCmd {
2534 : tenant_id,
2535 : timeline_id,
2536 : protocol_version,
2537 : }) => {
2538 : tracing::Span::current()
2539 : .record("tenant_id", field::display(tenant_id))
2540 : .record("timeline_id", field::display(timeline_id));
2541 :
2542 : self.check_permission(Some(tenant_id))?;
2543 : let command_kind = match protocol_version {
2544 : PagestreamProtocolVersion::V2 => ComputeCommandKind::PageStreamV2,
2545 : PagestreamProtocolVersion::V3 => ComputeCommandKind::PageStreamV3,
2546 : };
2547 : COMPUTE_COMMANDS_COUNTERS.for_command(command_kind).inc();
2548 :
2549 : self.handle_pagerequests(pgb, tenant_id, timeline_id, protocol_version, ctx)
2550 : .await?;
2551 : }
2552 : PageServiceCmd::BaseBackup(BaseBackupCmd {
2553 : tenant_id,
2554 : timeline_id,
2555 : lsn,
2556 : gzip,
2557 : replica,
2558 : }) => {
2559 : tracing::Span::current()
2560 : .record("tenant_id", field::display(tenant_id))
2561 : .record("timeline_id", field::display(timeline_id));
2562 :
2563 : self.check_permission(Some(tenant_id))?;
2564 :
2565 : COMPUTE_COMMANDS_COUNTERS
2566 : .for_command(ComputeCommandKind::Basebackup)
2567 : .inc();
2568 : let metric_recording = metrics::BASEBACKUP_QUERY_TIME.start_recording();
2569 0 : let res = async {
2570 0 : self.handle_basebackup_request(
2571 0 : pgb,
2572 0 : tenant_id,
2573 0 : timeline_id,
2574 0 : lsn,
2575 0 : None,
2576 0 : false,
2577 0 : gzip,
2578 0 : replica,
2579 0 : &ctx,
2580 0 : )
2581 0 : .await?;
2582 0 : pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
2583 0 : Result::<(), QueryError>::Ok(())
2584 0 : }
2585 : .await;
2586 : metric_recording.observe(&res);
2587 : res?;
2588 : }
2589 : // same as basebackup, but result includes relational data as well
2590 : PageServiceCmd::FullBackup(FullBackupCmd {
2591 : tenant_id,
2592 : timeline_id,
2593 : lsn,
2594 : prev_lsn,
2595 : }) => {
2596 : tracing::Span::current()
2597 : .record("tenant_id", field::display(tenant_id))
2598 : .record("timeline_id", field::display(timeline_id));
2599 :
2600 : self.check_permission(Some(tenant_id))?;
2601 :
2602 : COMPUTE_COMMANDS_COUNTERS
2603 : .for_command(ComputeCommandKind::Fullbackup)
2604 : .inc();
2605 :
2606 : // Check that the timeline exists
2607 : self.handle_basebackup_request(
2608 : pgb,
2609 : tenant_id,
2610 : timeline_id,
2611 : lsn,
2612 : prev_lsn,
2613 : true,
2614 : false,
2615 : false,
2616 : &ctx,
2617 : )
2618 : .await?;
2619 : pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
2620 : }
2621 : PageServiceCmd::Set => {
2622 : // important because psycopg2 executes "SET datestyle TO 'ISO'"
2623 : // on connect
2624 : pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
2625 : }
2626 : PageServiceCmd::LeaseLsn(LeaseLsnCmd {
2627 : tenant_shard_id,
2628 : timeline_id,
2629 : lsn,
2630 : }) => {
2631 : tracing::Span::current()
2632 : .record("tenant_id", field::display(tenant_shard_id))
2633 : .record("timeline_id", field::display(timeline_id));
2634 :
2635 : self.check_permission(Some(tenant_shard_id.tenant_id))?;
2636 :
2637 : COMPUTE_COMMANDS_COUNTERS
2638 : .for_command(ComputeCommandKind::LeaseLsn)
2639 : .inc();
2640 :
2641 : match self
2642 : .handle_make_lsn_lease(pgb, tenant_shard_id, timeline_id, lsn, &ctx)
2643 : .await
2644 : {
2645 : Ok(()) => {
2646 : pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?
2647 : }
2648 : Err(e) => {
2649 : error!("error obtaining lsn lease for {lsn}: {e:?}");
2650 : pgb.write_message_noflush(&BeMessage::ErrorResponse(
2651 : &e.to_string(),
2652 : Some(e.pg_error_code()),
2653 : ))?
2654 : }
2655 : };
2656 : }
2657 : }
2658 :
2659 : Ok(())
2660 : }
2661 : }
2662 :
2663 : impl From<GetActiveTenantError> for QueryError {
2664 0 : fn from(e: GetActiveTenantError) -> Self {
2665 0 : match e {
2666 0 : GetActiveTenantError::WaitForActiveTimeout { .. } => QueryError::Disconnected(
2667 0 : ConnectionError::Io(io::Error::new(io::ErrorKind::TimedOut, e.to_string())),
2668 0 : ),
2669 : GetActiveTenantError::Cancelled
2670 : | GetActiveTenantError::WillNotBecomeActive(TenantState::Stopping { .. }) => {
2671 0 : QueryError::Shutdown
2672 : }
2673 0 : e @ GetActiveTenantError::NotFound(_) => QueryError::NotFound(format!("{e}").into()),
2674 0 : e => QueryError::Other(anyhow::anyhow!(e)),
2675 : }
2676 0 : }
2677 : }
2678 :
2679 : #[derive(Debug, thiserror::Error)]
2680 : pub(crate) enum GetActiveTimelineError {
2681 : #[error(transparent)]
2682 : Tenant(GetActiveTenantError),
2683 : #[error(transparent)]
2684 : Timeline(#[from] GetTimelineError),
2685 : }
2686 :
2687 : impl From<GetActiveTimelineError> for QueryError {
2688 0 : fn from(e: GetActiveTimelineError) -> Self {
2689 0 : match e {
2690 0 : GetActiveTimelineError::Tenant(GetActiveTenantError::Cancelled) => QueryError::Shutdown,
2691 0 : GetActiveTimelineError::Tenant(e) => e.into(),
2692 0 : GetActiveTimelineError::Timeline(e) => QueryError::NotFound(format!("{e}").into()),
2693 : }
2694 0 : }
2695 : }
2696 :
2697 : impl From<crate::tenant::timeline::handle::HandleUpgradeError> for QueryError {
2698 0 : fn from(e: crate::tenant::timeline::handle::HandleUpgradeError) -> Self {
2699 0 : match e {
2700 0 : crate::tenant::timeline::handle::HandleUpgradeError::ShutDown => QueryError::Shutdown,
2701 0 : }
2702 0 : }
2703 : }
2704 :
2705 0 : fn set_tracing_field_shard_id(timeline: &Timeline) {
2706 0 : debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
2707 0 : tracing::Span::current().record(
2708 0 : "shard_id",
2709 0 : tracing::field::display(timeline.tenant_shard_id.shard_slug()),
2710 0 : );
2711 0 : debug_assert_current_span_has_tenant_and_timeline_id();
2712 0 : }
2713 :
2714 : struct WaitedForLsn(Lsn);
2715 : impl From<WaitedForLsn> for Lsn {
2716 0 : fn from(WaitedForLsn(lsn): WaitedForLsn) -> Self {
2717 0 : lsn
2718 0 : }
2719 : }
2720 :
2721 : #[cfg(test)]
2722 : mod tests {
2723 : use utils::shard::ShardCount;
2724 :
2725 : use super::*;
2726 :
2727 : #[test]
2728 4 : fn pageservice_cmd_parse() {
2729 4 : let tenant_id = TenantId::generate();
2730 4 : let timeline_id = TimelineId::generate();
2731 4 : let cmd =
2732 4 : PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id} {timeline_id}")).unwrap();
2733 4 : assert_eq!(
2734 4 : cmd,
2735 4 : PageServiceCmd::PageStream(PageStreamCmd {
2736 4 : tenant_id,
2737 4 : timeline_id,
2738 4 : protocol_version: PagestreamProtocolVersion::V2,
2739 4 : })
2740 4 : );
2741 4 : let cmd = PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id}")).unwrap();
2742 4 : assert_eq!(
2743 4 : cmd,
2744 4 : PageServiceCmd::BaseBackup(BaseBackupCmd {
2745 4 : tenant_id,
2746 4 : timeline_id,
2747 4 : lsn: None,
2748 4 : gzip: false,
2749 4 : replica: false
2750 4 : })
2751 4 : );
2752 4 : let cmd =
2753 4 : PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} --gzip")).unwrap();
2754 4 : assert_eq!(
2755 4 : cmd,
2756 4 : PageServiceCmd::BaseBackup(BaseBackupCmd {
2757 4 : tenant_id,
2758 4 : timeline_id,
2759 4 : lsn: None,
2760 4 : gzip: true,
2761 4 : replica: false
2762 4 : })
2763 4 : );
2764 4 : let cmd =
2765 4 : PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} latest")).unwrap();
2766 4 : assert_eq!(
2767 4 : cmd,
2768 4 : PageServiceCmd::BaseBackup(BaseBackupCmd {
2769 4 : tenant_id,
2770 4 : timeline_id,
2771 4 : lsn: None,
2772 4 : gzip: false,
2773 4 : replica: false
2774 4 : })
2775 4 : );
2776 4 : let cmd = PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} 0/16ABCDE"))
2777 4 : .unwrap();
2778 4 : assert_eq!(
2779 4 : cmd,
2780 4 : PageServiceCmd::BaseBackup(BaseBackupCmd {
2781 4 : tenant_id,
2782 4 : timeline_id,
2783 4 : lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
2784 4 : gzip: false,
2785 4 : replica: false
2786 4 : })
2787 4 : );
2788 4 : let cmd = PageServiceCmd::parse(&format!(
2789 4 : "basebackup {tenant_id} {timeline_id} --replica --gzip"
2790 4 : ))
2791 4 : .unwrap();
2792 4 : assert_eq!(
2793 4 : cmd,
2794 4 : PageServiceCmd::BaseBackup(BaseBackupCmd {
2795 4 : tenant_id,
2796 4 : timeline_id,
2797 4 : lsn: None,
2798 4 : gzip: true,
2799 4 : replica: true
2800 4 : })
2801 4 : );
2802 4 : let cmd = PageServiceCmd::parse(&format!(
2803 4 : "basebackup {tenant_id} {timeline_id} 0/16ABCDE --replica --gzip"
2804 4 : ))
2805 4 : .unwrap();
2806 4 : assert_eq!(
2807 4 : cmd,
2808 4 : PageServiceCmd::BaseBackup(BaseBackupCmd {
2809 4 : tenant_id,
2810 4 : timeline_id,
2811 4 : lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
2812 4 : gzip: true,
2813 4 : replica: true
2814 4 : })
2815 4 : );
2816 4 : let cmd = PageServiceCmd::parse(&format!("fullbackup {tenant_id} {timeline_id}")).unwrap();
2817 4 : assert_eq!(
2818 4 : cmd,
2819 4 : PageServiceCmd::FullBackup(FullBackupCmd {
2820 4 : tenant_id,
2821 4 : timeline_id,
2822 4 : lsn: None,
2823 4 : prev_lsn: None
2824 4 : })
2825 4 : );
2826 4 : let cmd = PageServiceCmd::parse(&format!(
2827 4 : "fullbackup {tenant_id} {timeline_id} 0/16ABCDE 0/16ABCDF"
2828 4 : ))
2829 4 : .unwrap();
2830 4 : assert_eq!(
2831 4 : cmd,
2832 4 : PageServiceCmd::FullBackup(FullBackupCmd {
2833 4 : tenant_id,
2834 4 : timeline_id,
2835 4 : lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
2836 4 : prev_lsn: Some(Lsn::from_str("0/16ABCDF").unwrap()),
2837 4 : })
2838 4 : );
2839 4 : let tenant_shard_id = TenantShardId::unsharded(tenant_id);
2840 4 : let cmd = PageServiceCmd::parse(&format!(
2841 4 : "lease lsn {tenant_shard_id} {timeline_id} 0/16ABCDE"
2842 4 : ))
2843 4 : .unwrap();
2844 4 : assert_eq!(
2845 4 : cmd,
2846 4 : PageServiceCmd::LeaseLsn(LeaseLsnCmd {
2847 4 : tenant_shard_id,
2848 4 : timeline_id,
2849 4 : lsn: Lsn::from_str("0/16ABCDE").unwrap(),
2850 4 : })
2851 4 : );
2852 4 : let tenant_shard_id = TenantShardId::split(&tenant_shard_id, ShardCount(8))[1];
2853 4 : let cmd = PageServiceCmd::parse(&format!(
2854 4 : "lease lsn {tenant_shard_id} {timeline_id} 0/16ABCDE"
2855 4 : ))
2856 4 : .unwrap();
2857 4 : assert_eq!(
2858 4 : cmd,
2859 4 : PageServiceCmd::LeaseLsn(LeaseLsnCmd {
2860 4 : tenant_shard_id,
2861 4 : timeline_id,
2862 4 : lsn: Lsn::from_str("0/16ABCDE").unwrap(),
2863 4 : })
2864 4 : );
2865 4 : let cmd = PageServiceCmd::parse("set a = b").unwrap();
2866 4 : assert_eq!(cmd, PageServiceCmd::Set);
2867 4 : let cmd = PageServiceCmd::parse("SET foo").unwrap();
2868 4 : assert_eq!(cmd, PageServiceCmd::Set);
2869 4 : }
2870 :
2871 : #[test]
2872 4 : fn pageservice_cmd_err_handling() {
2873 4 : let tenant_id = TenantId::generate();
2874 4 : let timeline_id = TimelineId::generate();
2875 4 : let cmd = PageServiceCmd::parse("unknown_command");
2876 4 : assert!(cmd.is_err());
2877 4 : let cmd = PageServiceCmd::parse("pagestream_v2");
2878 4 : assert!(cmd.is_err());
2879 4 : let cmd = PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id}xxx"));
2880 4 : assert!(cmd.is_err());
2881 4 : let cmd = PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id}xxx {timeline_id}xxx"));
2882 4 : assert!(cmd.is_err());
2883 4 : let cmd = PageServiceCmd::parse(&format!(
2884 4 : "basebackup {tenant_id} {timeline_id} --gzip --gzip"
2885 4 : ));
2886 4 : assert!(cmd.is_err());
2887 4 : let cmd = PageServiceCmd::parse(&format!(
2888 4 : "basebackup {tenant_id} {timeline_id} --gzip --unknown"
2889 4 : ));
2890 4 : assert!(cmd.is_err());
2891 4 : let cmd = PageServiceCmd::parse(&format!(
2892 4 : "basebackup {tenant_id} {timeline_id} --gzip 0/16ABCDE"
2893 4 : ));
2894 4 : assert!(cmd.is_err());
2895 4 : let cmd = PageServiceCmd::parse(&format!("lease {tenant_id} {timeline_id} gzip 0/16ABCDE"));
2896 4 : assert!(cmd.is_err());
2897 4 : }
2898 : }
|