Line data Source code
1 : //! The Page Service listens for client connections and serves their GetPage@LSN
2 : //! requests.
3 :
4 : use std::any::Any;
5 : use std::borrow::Cow;
6 : use std::num::NonZeroUsize;
7 : use std::os::fd::AsRawFd;
8 : use std::pin::Pin;
9 : use std::str::FromStr;
10 : use std::sync::Arc;
11 : use std::task::{Context, Poll};
12 : use std::time::{Duration, Instant, SystemTime};
13 : use std::{io, str};
14 :
15 : use anyhow::{Context as _, bail};
16 : use bytes::{Buf as _, BufMut as _, BytesMut};
17 : use chrono::Utc;
18 : use futures::future::BoxFuture;
19 : use futures::{FutureExt, Stream};
20 : use itertools::Itertools;
21 : use jsonwebtoken::TokenData;
22 : use once_cell::sync::OnceCell;
23 : use pageserver_api::config::{
24 : GetVectoredConcurrentIo, PageServicePipeliningConfig, PageServicePipeliningConfigPipelined,
25 : PageServiceProtocolPipelinedBatchingStrategy, PageServiceProtocolPipelinedExecutionStrategy,
26 : };
27 : use pageserver_api::key::rel_block_to_key;
28 : use pageserver_api::models::{PageTraceEvent, TenantState};
29 : use pageserver_api::pagestream_api::{
30 : self, PagestreamBeMessage, PagestreamDbSizeRequest, PagestreamDbSizeResponse,
31 : PagestreamErrorResponse, PagestreamExistsRequest, PagestreamExistsResponse,
32 : PagestreamFeMessage, PagestreamGetPageRequest, PagestreamGetSlruSegmentRequest,
33 : PagestreamGetSlruSegmentResponse, PagestreamNblocksRequest, PagestreamNblocksResponse,
34 : PagestreamProtocolVersion, PagestreamRequest,
35 : };
36 : use pageserver_api::reltag::SlruKind;
37 : use pageserver_api::shard::TenantShardId;
38 : use pageserver_page_api as page_api;
39 : use pageserver_page_api::proto;
40 : use postgres_backend::{
41 : AuthType, PostgresBackend, PostgresBackendReader, QueryError, is_expected_io_error,
42 : };
43 : use postgres_ffi::BLCKSZ;
44 : use postgres_ffi_types::constants::DEFAULTTABLESPACE_OID;
45 : use pq_proto::framed::ConnectionError;
46 : use pq_proto::{BeMessage, FeMessage, FeStartupPacket, RowDescriptor};
47 : use smallvec::{SmallVec, smallvec};
48 : use strum_macros::IntoStaticStr;
49 : use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _, BufWriter};
50 : use tokio::task::JoinHandle;
51 : use tokio_util::sync::CancellationToken;
52 : use tonic::service::Interceptor as _;
53 : use tonic::transport::server::TcpConnectInfo;
54 : use tracing::*;
55 : use utils::auth::{Claims, Scope, SwappableJwtAuth};
56 : use utils::id::{TenantId, TenantTimelineId, TimelineId};
57 : use utils::logging::log_slow;
58 : use utils::lsn::Lsn;
59 : use utils::shard::ShardIndex;
60 : use utils::simple_rcu::RcuReadGuard;
61 : use utils::sync::gate::{Gate, GateGuard};
62 : use utils::sync::spsc_fold;
63 : use utils::{failpoint_support, span_record};
64 :
65 : use crate::auth::check_permission;
66 : use crate::basebackup::{self, BasebackupError};
67 : use crate::config::PageServerConf;
68 : use crate::context::{
69 : DownloadBehavior, PerfInstrumentFutureExt, RequestContext, RequestContextBuilder,
70 : };
71 : use crate::metrics::{
72 : self, COMPUTE_COMMANDS_COUNTERS, ComputeCommandKind, GetPageBatchBreakReason, LIVE_CONNECTIONS,
73 : MISROUTED_PAGESTREAM_REQUESTS, PAGESTREAM_HANDLER_RESULTS_TOTAL, SmgrOpTimer, TimelineMetrics,
74 : };
75 : use crate::pgdatadir_mapping::{LsnRange, Version};
76 : use crate::span::{
77 : debug_assert_current_span_has_tenant_and_timeline_id,
78 : debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id,
79 : };
80 : use crate::task_mgr::{self, COMPUTE_REQUEST_RUNTIME, TaskKind};
81 : use crate::tenant::mgr::{
82 : GetActiveTenantError, GetTenantError, ShardResolveResult, ShardSelector, TenantManager,
83 : };
84 : use crate::tenant::storage_layer::IoConcurrency;
85 : use crate::tenant::timeline::handle::{Handle, HandleUpgradeError, WeakHandle};
86 : use crate::tenant::timeline::{self, WaitLsnError, WaitLsnTimeout, WaitLsnWaiter};
87 : use crate::tenant::{GetTimelineError, PageReconstructError, Timeline};
88 : use crate::{CancellableTask, PERF_TRACE_TARGET, timed_after_cancellation};
89 :
90 : /// How long we may wait for a [`crate::tenant::mgr::TenantSlot::InProgress`]` and/or a [`crate::tenant::TenantShard`] which
91 : /// is not yet in state [`TenantState::Active`].
92 : ///
93 : /// NB: this is a different value than [`crate::http::routes::ACTIVE_TENANT_TIMEOUT`].
94 : /// HADRON: reduced timeout and we will retry in Cache::get().
95 : const ACTIVE_TENANT_TIMEOUT: Duration = Duration::from_millis(5000);
96 :
97 : /// Threshold at which to log slow GetPage requests.
98 : const LOG_SLOW_GETPAGE_THRESHOLD: Duration = Duration::from_secs(30);
99 :
100 : /// The idle time before sending TCP keepalive probes for gRPC connections. The
101 : /// interval and timeout between each probe is configured via sysctl. This
102 : /// allows detecting dead connections sooner.
103 : const GRPC_TCP_KEEPALIVE_TIME: Duration = Duration::from_secs(60);
104 :
105 : /// Whether to enable TCP nodelay for gRPC connections. This disables Nagle's
106 : /// algorithm, which can cause latency spikes for small messages.
107 : const GRPC_TCP_NODELAY: bool = true;
108 :
109 : /// The interval between HTTP2 keepalive pings. This allows shutting down server
110 : /// tasks when clients are unresponsive.
111 : const GRPC_HTTP2_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(30);
112 :
113 : /// The timeout for HTTP2 keepalive pings. Should be <= GRPC_KEEPALIVE_INTERVAL.
114 : const GRPC_HTTP2_KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(20);
115 :
116 : /// Number of concurrent gRPC streams per TCP connection. We expect something
117 : /// like 8 GetPage streams per connections, plus any unary requests.
118 : const GRPC_MAX_CONCURRENT_STREAMS: u32 = 256;
119 :
120 : ///////////////////////////////////////////////////////////////////////////////
121 :
122 : pub struct Listener {
123 : cancel: CancellationToken,
124 : /// Cancel the listener task through `listen_cancel` to shut down the listener
125 : /// and get a handle on the existing connections.
126 : task: JoinHandle<Connections>,
127 : }
128 :
129 : pub struct Connections {
130 : cancel: CancellationToken,
131 : tasks: tokio::task::JoinSet<ConnectionHandlerResult>,
132 : gate: Gate,
133 : }
134 :
135 0 : pub fn spawn(
136 0 : conf: &'static PageServerConf,
137 0 : tenant_manager: Arc<TenantManager>,
138 0 : pg_auth: Option<Arc<SwappableJwtAuth>>,
139 0 : perf_trace_dispatch: Option<Dispatch>,
140 0 : tcp_listener: tokio::net::TcpListener,
141 0 : tls_config: Option<Arc<rustls::ServerConfig>>,
142 0 : ) -> Listener {
143 0 : let cancel = CancellationToken::new();
144 0 : let libpq_ctx = RequestContext::todo_child(
145 0 : TaskKind::LibpqEndpointListener,
146 : // listener task shouldn't need to download anything. (We will
147 : // create a separate sub-contexts for each connection, with their
148 : // own download behavior. This context is used only to listen and
149 : // accept connections.)
150 0 : DownloadBehavior::Error,
151 : );
152 0 : let task = COMPUTE_REQUEST_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
153 0 : "libpq listener",
154 0 : libpq_listener_main(
155 0 : conf,
156 0 : tenant_manager,
157 0 : pg_auth,
158 0 : perf_trace_dispatch,
159 0 : tcp_listener,
160 0 : conf.pg_auth_type,
161 0 : tls_config,
162 0 : conf.page_service_pipelining.clone(),
163 0 : libpq_ctx,
164 0 : cancel.clone(),
165 0 : )
166 0 : .map(anyhow::Ok),
167 0 : ));
168 :
169 0 : Listener { cancel, task }
170 0 : }
171 :
172 : impl Listener {
173 0 : pub async fn stop_accepting(self) -> Connections {
174 0 : self.cancel.cancel();
175 0 : self.task
176 0 : .await
177 0 : .expect("unreachable: we wrap the listener task in task_mgr::exit_on_panic_or_error")
178 0 : }
179 : }
180 : impl Connections {
181 0 : pub(crate) async fn shutdown(self) {
182 : let Self {
183 0 : cancel,
184 0 : mut tasks,
185 0 : gate,
186 0 : } = self;
187 0 : cancel.cancel();
188 0 : while let Some(res) = tasks.join_next().await {
189 0 : Self::handle_connection_completion(res);
190 0 : }
191 0 : gate.close().await;
192 0 : }
193 :
194 0 : fn handle_connection_completion(res: Result<anyhow::Result<()>, tokio::task::JoinError>) {
195 0 : match res {
196 0 : Ok(Ok(())) => {}
197 0 : Ok(Err(e)) => error!("error in page_service connection task: {:?}", e),
198 0 : Err(e) => error!("page_service connection task panicked: {:?}", e),
199 : }
200 0 : }
201 : }
202 :
203 : ///
204 : /// Main loop of the page service.
205 : ///
206 : /// Listens for connections, and launches a new handler task for each.
207 : ///
208 : /// Returns Ok(()) upon cancellation via `cancel`, returning the set of
209 : /// open connections.
210 : ///
211 : #[allow(clippy::too_many_arguments)]
212 0 : pub async fn libpq_listener_main(
213 0 : conf: &'static PageServerConf,
214 0 : tenant_manager: Arc<TenantManager>,
215 0 : auth: Option<Arc<SwappableJwtAuth>>,
216 0 : perf_trace_dispatch: Option<Dispatch>,
217 0 : listener: tokio::net::TcpListener,
218 0 : auth_type: AuthType,
219 0 : tls_config: Option<Arc<rustls::ServerConfig>>,
220 0 : pipelining_config: PageServicePipeliningConfig,
221 0 : listener_ctx: RequestContext,
222 0 : listener_cancel: CancellationToken,
223 0 : ) -> Connections {
224 0 : let connections_cancel = CancellationToken::new();
225 0 : let connections_gate = Gate::default();
226 0 : let mut connection_handler_tasks = tokio::task::JoinSet::default();
227 :
228 : loop {
229 0 : let gate_guard = match connections_gate.enter() {
230 0 : Ok(guard) => guard,
231 0 : Err(_) => break,
232 : };
233 :
234 0 : let accepted = tokio::select! {
235 : biased;
236 0 : _ = listener_cancel.cancelled() => break,
237 0 : next = connection_handler_tasks.join_next(), if !connection_handler_tasks.is_empty() => {
238 0 : let res = next.expect("we dont poll while empty");
239 0 : Connections::handle_connection_completion(res);
240 0 : continue;
241 : }
242 0 : accepted = listener.accept() => accepted,
243 : };
244 :
245 0 : match accepted {
246 0 : Ok((socket, peer_addr)) => {
247 : // Connection established. Spawn a new task to handle it.
248 0 : debug!("accepted connection from {}", peer_addr);
249 0 : let local_auth = auth.clone();
250 0 : let connection_ctx = RequestContextBuilder::from(&listener_ctx)
251 0 : .task_kind(TaskKind::PageRequestHandler)
252 0 : .download_behavior(DownloadBehavior::Download)
253 0 : .perf_span_dispatch(perf_trace_dispatch.clone())
254 0 : .detached_child();
255 :
256 0 : connection_handler_tasks.spawn(page_service_conn_main(
257 0 : conf,
258 0 : tenant_manager.clone(),
259 0 : local_auth,
260 0 : socket,
261 0 : auth_type,
262 0 : tls_config.clone(),
263 0 : pipelining_config.clone(),
264 0 : connection_ctx,
265 0 : connections_cancel.child_token(),
266 0 : gate_guard,
267 : ));
268 : }
269 0 : Err(err) => {
270 : // accept() failed. Log the error, and loop back to retry on next connection.
271 0 : error!("accept() failed: {:?}", err);
272 : }
273 : }
274 : }
275 :
276 0 : debug!("page_service listener loop terminated");
277 :
278 0 : Connections {
279 0 : cancel: connections_cancel,
280 0 : tasks: connection_handler_tasks,
281 0 : gate: connections_gate,
282 0 : }
283 0 : }
284 :
285 : type ConnectionHandlerResult = anyhow::Result<()>;
286 :
287 : /// Perf root spans start at the per-request level, after shard routing.
288 : /// This struct carries connection-level information to the root perf span definition.
289 : #[derive(Clone, Default)]
290 : struct ConnectionPerfSpanFields {
291 : peer_addr: String,
292 : application_name: Option<String>,
293 : compute_mode: Option<String>,
294 : }
295 :
296 : #[instrument(skip_all, fields(peer_addr, application_name, compute_mode))]
297 : #[allow(clippy::too_many_arguments)]
298 : async fn page_service_conn_main(
299 : conf: &'static PageServerConf,
300 : tenant_manager: Arc<TenantManager>,
301 : auth: Option<Arc<SwappableJwtAuth>>,
302 : socket: tokio::net::TcpStream,
303 : auth_type: AuthType,
304 : tls_config: Option<Arc<rustls::ServerConfig>>,
305 : pipelining_config: PageServicePipeliningConfig,
306 : connection_ctx: RequestContext,
307 : cancel: CancellationToken,
308 : gate_guard: GateGuard,
309 : ) -> ConnectionHandlerResult {
310 : let _guard = LIVE_CONNECTIONS
311 : .with_label_values(&["page_service"])
312 : .guard();
313 :
314 : socket
315 : .set_nodelay(true)
316 : .context("could not set TCP_NODELAY")?;
317 :
318 : let socket_fd = socket.as_raw_fd();
319 :
320 : let peer_addr = socket.peer_addr().context("get peer address")?;
321 :
322 : let perf_span_fields = ConnectionPerfSpanFields {
323 : peer_addr: peer_addr.to_string(),
324 : application_name: None, // filled in later
325 : compute_mode: None, // filled in later
326 : };
327 : tracing::Span::current().record("peer_addr", field::display(peer_addr));
328 :
329 : // setup read timeout of 10 minutes. the timeout is rather arbitrary for requirements:
330 : // - long enough for most valid compute connections
331 : // - less than infinite to stop us from "leaking" connections to long-gone computes
332 : //
333 : // no write timeout is used, because the kernel is assumed to error writes after some time.
334 : let mut socket = tokio_io_timeout::TimeoutReader::new(socket);
335 :
336 : let default_timeout_ms = 10 * 60 * 1000; // 10 minutes by default
337 0 : let socket_timeout_ms = (|| {
338 0 : fail::fail_point!("simulated-bad-compute-connection", |avg_timeout_ms| {
339 : // Exponential distribution for simulating
340 : // poor network conditions, expect about avg_timeout_ms to be around 15
341 : // in tests
342 0 : if let Some(avg_timeout_ms) = avg_timeout_ms {
343 0 : let avg = avg_timeout_ms.parse::<i64>().unwrap() as f32;
344 0 : let u = rand::random::<f32>();
345 0 : ((1.0 - u).ln() / (-avg)) as u64
346 : } else {
347 0 : default_timeout_ms
348 : }
349 0 : });
350 0 : default_timeout_ms
351 : })();
352 :
353 : // A timeout here does not mean the client died, it can happen if it's just idle for
354 : // a while: we will tear down this PageServerHandler and instantiate a new one if/when
355 : // they reconnect.
356 : socket.set_timeout(Some(std::time::Duration::from_millis(socket_timeout_ms)));
357 : let socket = Box::pin(socket);
358 :
359 : fail::fail_point!("ps::connection-start::pre-login");
360 :
361 : // XXX: pgbackend.run() should take the connection_ctx,
362 : // and create a child per-query context when it invokes process_query.
363 : // But it's in a shared crate, so, we store connection_ctx inside PageServerHandler
364 : // and create the per-query context in process_query ourselves.
365 : let mut conn_handler = PageServerHandler::new(
366 : tenant_manager,
367 : auth,
368 : pipelining_config,
369 : conf.get_vectored_concurrent_io,
370 : perf_span_fields,
371 : connection_ctx,
372 : cancel.clone(),
373 : gate_guard,
374 : );
375 : let pgbackend =
376 : PostgresBackend::new_from_io(socket_fd, socket, peer_addr, auth_type, tls_config)?;
377 :
378 : match pgbackend.run(&mut conn_handler, &cancel).await {
379 : Ok(()) => {
380 : // we've been requested to shut down
381 : Ok(())
382 : }
383 : Err(QueryError::Disconnected(ConnectionError::Io(io_error))) => {
384 : if is_expected_io_error(&io_error) {
385 : info!("Postgres client disconnected ({io_error})");
386 : Ok(())
387 : } else {
388 : let tenant_id = conn_handler.timeline_handles.as_ref().unwrap().tenant_id();
389 : Err(io_error).context(format!(
390 : "Postgres connection error for tenant_id={tenant_id:?} client at peer_addr={peer_addr}"
391 : ))
392 : }
393 : }
394 : other => {
395 : let tenant_id = conn_handler.timeline_handles.as_ref().unwrap().tenant_id();
396 : other.context(format!(
397 : "Postgres query error for tenant_id={tenant_id:?} client peer_addr={peer_addr}"
398 : ))
399 : }
400 : }
401 : }
402 :
403 : /// Page service connection handler.
404 : struct PageServerHandler {
405 : auth: Option<Arc<SwappableJwtAuth>>,
406 : claims: Option<Claims>,
407 :
408 : /// The context created for the lifetime of the connection
409 : /// services by this PageServerHandler.
410 : /// For each query received over the connection,
411 : /// `process_query` creates a child context from this one.
412 : connection_ctx: RequestContext,
413 :
414 : perf_span_fields: ConnectionPerfSpanFields,
415 :
416 : cancel: CancellationToken,
417 :
418 : /// None only while pagestream protocol is being processed.
419 : timeline_handles: Option<TimelineHandles>,
420 :
421 : pipelining_config: PageServicePipeliningConfig,
422 : get_vectored_concurrent_io: GetVectoredConcurrentIo,
423 :
424 : gate_guard: GateGuard,
425 : }
426 :
427 : struct TimelineHandles {
428 : wrapper: TenantManagerWrapper,
429 : /// Note on size: the typical size of this map is 1. The largest size we expect
430 : /// to see is the number of shards divided by the number of pageservers (typically < 2),
431 : /// or the ratio used when splitting shards (i.e. how many children created from one)
432 : /// parent shard, where a "large" number might be ~8.
433 : handles: timeline::handle::Cache<TenantManagerTypes>,
434 : }
435 :
436 : impl TimelineHandles {
437 0 : fn new(tenant_manager: Arc<TenantManager>) -> Self {
438 0 : Self {
439 0 : wrapper: TenantManagerWrapper {
440 0 : tenant_manager,
441 0 : tenant_id: OnceCell::new(),
442 0 : },
443 0 : handles: Default::default(),
444 0 : }
445 0 : }
446 0 : async fn get(
447 0 : &mut self,
448 0 : tenant_id: TenantId,
449 0 : timeline_id: TimelineId,
450 0 : shard_selector: ShardSelector,
451 0 : ) -> Result<Handle<TenantManagerTypes>, GetActiveTimelineError> {
452 0 : if *self.wrapper.tenant_id.get_or_init(|| tenant_id) != tenant_id {
453 0 : return Err(GetActiveTimelineError::Tenant(
454 0 : GetActiveTenantError::SwitchedTenant,
455 0 : ));
456 0 : }
457 0 : self.handles
458 0 : .get(timeline_id, shard_selector, &self.wrapper)
459 0 : .await
460 0 : .map_err(|e| match e {
461 0 : timeline::handle::GetError::TenantManager(e) => e,
462 : timeline::handle::GetError::PerTimelineStateShutDown => {
463 0 : trace!("per-timeline state shut down");
464 0 : GetActiveTimelineError::Timeline(GetTimelineError::ShuttingDown)
465 : }
466 0 : })
467 0 : }
468 :
469 0 : fn tenant_id(&self) -> Option<TenantId> {
470 0 : self.wrapper.tenant_id.get().copied()
471 0 : }
472 : }
473 :
474 : pub(crate) struct TenantManagerWrapper {
475 : tenant_manager: Arc<TenantManager>,
476 : // We do not support switching tenant_id on a connection at this point.
477 : // We can can add support for this later if needed without changing
478 : // the protocol.
479 : tenant_id: once_cell::sync::OnceCell<TenantId>,
480 : }
481 :
482 : #[derive(Debug)]
483 : pub(crate) struct TenantManagerTypes;
484 :
485 : impl timeline::handle::Types for TenantManagerTypes {
486 : type TenantManagerError = GetActiveTimelineError;
487 : type TenantManager = TenantManagerWrapper;
488 : type Timeline = TenantManagerCacheItem;
489 : }
490 :
491 : pub(crate) struct TenantManagerCacheItem {
492 : pub(crate) timeline: Arc<Timeline>,
493 : // allow() for cheap propagation through RequestContext inside a task
494 : #[allow(clippy::redundant_allocation)]
495 : pub(crate) metrics: Arc<Arc<TimelineMetrics>>,
496 : #[allow(dead_code)] // we store it to keep the gate open
497 : pub(crate) gate_guard: GateGuard,
498 : }
499 :
500 : impl std::ops::Deref for TenantManagerCacheItem {
501 : type Target = Arc<Timeline>;
502 0 : fn deref(&self) -> &Self::Target {
503 0 : &self.timeline
504 0 : }
505 : }
506 :
507 : impl timeline::handle::Timeline<TenantManagerTypes> for TenantManagerCacheItem {
508 0 : fn shard_timeline_id(&self) -> timeline::handle::ShardTimelineId {
509 0 : Timeline::shard_timeline_id(&self.timeline)
510 0 : }
511 :
512 0 : fn per_timeline_state(&self) -> &timeline::handle::PerTimelineState<TenantManagerTypes> {
513 0 : &self.timeline.handles
514 0 : }
515 :
516 0 : fn get_shard_identity(&self) -> &pageserver_api::shard::ShardIdentity {
517 0 : Timeline::get_shard_identity(&self.timeline)
518 0 : }
519 : }
520 :
521 : impl timeline::handle::TenantManager<TenantManagerTypes> for TenantManagerWrapper {
522 0 : async fn resolve(
523 0 : &self,
524 0 : timeline_id: TimelineId,
525 0 : shard_selector: ShardSelector,
526 0 : ) -> Result<TenantManagerCacheItem, GetActiveTimelineError> {
527 0 : let tenant_id = self.tenant_id.get().expect("we set this in get()");
528 0 : let timeout = ACTIVE_TENANT_TIMEOUT;
529 0 : let wait_start = Instant::now();
530 0 : let deadline = wait_start + timeout;
531 0 : let tenant_shard = loop {
532 0 : let resolved = self
533 0 : .tenant_manager
534 0 : .resolve_attached_shard(tenant_id, shard_selector);
535 0 : match resolved {
536 0 : ShardResolveResult::Found(tenant_shard) => break tenant_shard,
537 : ShardResolveResult::NotFound => {
538 0 : return Err(GetActiveTimelineError::Tenant(
539 0 : GetActiveTenantError::NotFound(GetTenantError::NotFound(*tenant_id)),
540 0 : ));
541 : }
542 0 : ShardResolveResult::InProgress(barrier) => {
543 : // We can't authoritatively answer right now: wait for InProgress state
544 : // to end, then try again
545 0 : tokio::select! {
546 0 : _ = barrier.wait() => {
547 0 : // The barrier completed: proceed around the loop to try looking up again
548 0 : },
549 0 : _ = tokio::time::sleep(deadline.duration_since(Instant::now())) => {
550 0 : return Err(GetActiveTimelineError::Tenant(GetActiveTenantError::WaitForActiveTimeout {
551 0 : latest_state: None,
552 0 : wait_time: timeout,
553 0 : }));
554 : }
555 : }
556 : }
557 : };
558 : };
559 :
560 0 : tracing::debug!("Waiting for tenant to enter active state...");
561 0 : tenant_shard
562 0 : .wait_to_become_active(deadline.duration_since(Instant::now()))
563 0 : .await
564 0 : .map_err(GetActiveTimelineError::Tenant)?;
565 :
566 0 : let timeline = tenant_shard
567 0 : .get_timeline(timeline_id, true)
568 0 : .map_err(GetActiveTimelineError::Timeline)?;
569 :
570 0 : let gate_guard = match timeline.gate.enter() {
571 0 : Ok(guard) => guard,
572 : Err(_) => {
573 0 : return Err(GetActiveTimelineError::Timeline(
574 0 : GetTimelineError::ShuttingDown,
575 0 : ));
576 : }
577 : };
578 :
579 0 : let metrics = Arc::new(Arc::clone(&timeline.metrics));
580 :
581 0 : Ok(TenantManagerCacheItem {
582 0 : timeline,
583 0 : metrics,
584 0 : gate_guard,
585 0 : })
586 0 : }
587 : }
588 :
589 : #[derive(thiserror::Error, Debug)]
590 : enum PageStreamError {
591 : /// We encountered an error that should prompt the client to reconnect:
592 : /// in practice this means we drop the connection without sending a response.
593 : #[error("Reconnect required: {0}")]
594 : Reconnect(Cow<'static, str>),
595 :
596 : /// We were instructed to shutdown while processing the query
597 : #[error("Shutting down")]
598 : Shutdown,
599 :
600 : /// Something went wrong reading a page: this likely indicates a pageserver bug
601 : #[error("Read error")]
602 : Read(#[source] PageReconstructError),
603 :
604 : /// Ran out of time waiting for an LSN
605 : #[error("LSN timeout: {0}")]
606 : LsnTimeout(WaitLsnError),
607 :
608 : /// The entity required to serve the request (tenant or timeline) is not found,
609 : /// or is not found in a suitable state to serve a request.
610 : #[error("Not found: {0}")]
611 : NotFound(Cow<'static, str>),
612 :
613 : /// Request asked for something that doesn't make sense, like an invalid LSN
614 : #[error("Bad request: {0}")]
615 : BadRequest(Cow<'static, str>),
616 : }
617 :
618 : impl From<PageStreamError> for tonic::Status {
619 0 : fn from(err: PageStreamError) -> Self {
620 : use tonic::Code;
621 0 : let message = err.to_string();
622 0 : let code = match err {
623 0 : PageStreamError::Reconnect(_) => Code::Unavailable,
624 0 : PageStreamError::Shutdown => Code::Unavailable,
625 0 : PageStreamError::Read(err) => match err {
626 0 : PageReconstructError::Cancelled => Code::Unavailable,
627 0 : PageReconstructError::MissingKey(_) => Code::NotFound,
628 0 : PageReconstructError::AncestorLsnTimeout(err) => tonic::Status::from(err).code(),
629 0 : PageReconstructError::Other(_) => Code::Internal,
630 0 : PageReconstructError::WalRedo(_) => Code::Internal,
631 : },
632 0 : PageStreamError::LsnTimeout(err) => tonic::Status::from(err).code(),
633 0 : PageStreamError::NotFound(_) => Code::NotFound,
634 0 : PageStreamError::BadRequest(_) => Code::InvalidArgument,
635 : };
636 0 : tonic::Status::new(code, message)
637 0 : }
638 : }
639 :
640 : impl From<PageReconstructError> for PageStreamError {
641 0 : fn from(value: PageReconstructError) -> Self {
642 0 : match value {
643 0 : PageReconstructError::Cancelled => Self::Shutdown,
644 0 : e => Self::Read(e),
645 : }
646 0 : }
647 : }
648 :
649 : impl From<GetActiveTimelineError> for PageStreamError {
650 0 : fn from(value: GetActiveTimelineError) -> Self {
651 0 : match value {
652 : GetActiveTimelineError::Tenant(GetActiveTenantError::Cancelled)
653 : | GetActiveTimelineError::Tenant(GetActiveTenantError::WillNotBecomeActive(
654 : TenantState::Stopping { .. },
655 : ))
656 0 : | GetActiveTimelineError::Timeline(GetTimelineError::ShuttingDown) => Self::Shutdown,
657 0 : GetActiveTimelineError::Tenant(e) => Self::NotFound(format!("{e}").into()),
658 0 : GetActiveTimelineError::Timeline(e) => Self::NotFound(format!("{e}").into()),
659 : }
660 0 : }
661 : }
662 :
663 : impl From<WaitLsnError> for PageStreamError {
664 0 : fn from(value: WaitLsnError) -> Self {
665 0 : match value {
666 0 : e @ WaitLsnError::Timeout(_) => Self::LsnTimeout(e),
667 0 : WaitLsnError::Shutdown => Self::Shutdown,
668 0 : e @ WaitLsnError::BadState { .. } => Self::Reconnect(format!("{e}").into()),
669 : }
670 0 : }
671 : }
672 :
673 : impl From<WaitLsnError> for QueryError {
674 0 : fn from(value: WaitLsnError) -> Self {
675 0 : match value {
676 0 : e @ WaitLsnError::Timeout(_) => Self::Other(anyhow::Error::new(e)),
677 0 : WaitLsnError::Shutdown => Self::Shutdown,
678 0 : WaitLsnError::BadState { .. } => Self::Reconnect,
679 : }
680 0 : }
681 : }
682 :
683 : #[derive(thiserror::Error, Debug)]
684 : struct BatchedPageStreamError {
685 : req: PagestreamRequest,
686 : err: PageStreamError,
687 : }
688 :
689 : impl std::fmt::Display for BatchedPageStreamError {
690 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
691 0 : self.err.fmt(f)
692 0 : }
693 : }
694 :
695 : struct BatchedGetPageRequest {
696 : req: PagestreamGetPageRequest,
697 : timer: SmgrOpTimer,
698 : lsn_range: LsnRange,
699 : ctx: RequestContext,
700 : // If the request is perf enabled, this contains a context
701 : // with a perf span tracking the time spent waiting for the executor.
702 : batch_wait_ctx: Option<RequestContext>,
703 : }
704 :
705 : #[cfg(feature = "testing")]
706 : struct BatchedTestRequest {
707 : req: pagestream_api::PagestreamTestRequest,
708 : timer: SmgrOpTimer,
709 : }
710 :
711 : /// NB: we only hold [`timeline::handle::WeakHandle`] inside this enum,
712 : /// so that we don't keep the [`Timeline::gate`] open while the batch
713 : /// is being built up inside the [`spsc_fold`] (pagestream pipelining).
714 : #[derive(IntoStaticStr)]
715 : #[allow(clippy::large_enum_variant)]
716 : enum BatchedFeMessage {
717 : Exists {
718 : span: Span,
719 : timer: SmgrOpTimer,
720 : shard: WeakHandle<TenantManagerTypes>,
721 : req: PagestreamExistsRequest,
722 : },
723 : Nblocks {
724 : span: Span,
725 : timer: SmgrOpTimer,
726 : shard: WeakHandle<TenantManagerTypes>,
727 : req: PagestreamNblocksRequest,
728 : },
729 : GetPage {
730 : span: Span,
731 : shard: WeakHandle<TenantManagerTypes>,
732 : pages: SmallVec<[BatchedGetPageRequest; 1]>,
733 : batch_break_reason: GetPageBatchBreakReason,
734 : },
735 : DbSize {
736 : span: Span,
737 : timer: SmgrOpTimer,
738 : shard: WeakHandle<TenantManagerTypes>,
739 : req: PagestreamDbSizeRequest,
740 : },
741 : GetSlruSegment {
742 : span: Span,
743 : timer: SmgrOpTimer,
744 : shard: WeakHandle<TenantManagerTypes>,
745 : req: PagestreamGetSlruSegmentRequest,
746 : },
747 : #[cfg(feature = "testing")]
748 : Test {
749 : span: Span,
750 : shard: WeakHandle<TenantManagerTypes>,
751 : requests: Vec<BatchedTestRequest>,
752 : },
753 : RespondError {
754 : span: Span,
755 : error: BatchedPageStreamError,
756 : },
757 : }
758 :
759 : impl BatchedFeMessage {
760 0 : fn as_static_str(&self) -> &'static str {
761 0 : self.into()
762 0 : }
763 :
764 0 : fn observe_execution_start(&mut self, at: Instant) {
765 0 : match self {
766 0 : BatchedFeMessage::Exists { timer, .. }
767 0 : | BatchedFeMessage::Nblocks { timer, .. }
768 0 : | BatchedFeMessage::DbSize { timer, .. }
769 0 : | BatchedFeMessage::GetSlruSegment { timer, .. } => {
770 0 : timer.observe_execution_start(at);
771 0 : }
772 0 : BatchedFeMessage::GetPage { pages, .. } => {
773 0 : for page in pages {
774 0 : page.timer.observe_execution_start(at);
775 0 : }
776 : }
777 : #[cfg(feature = "testing")]
778 0 : BatchedFeMessage::Test { requests, .. } => {
779 0 : for req in requests {
780 0 : req.timer.observe_execution_start(at);
781 0 : }
782 : }
783 0 : BatchedFeMessage::RespondError { .. } => {}
784 : }
785 0 : }
786 :
787 0 : fn should_break_batch(
788 0 : &self,
789 0 : other: &BatchedFeMessage,
790 0 : max_batch_size: NonZeroUsize,
791 0 : batching_strategy: PageServiceProtocolPipelinedBatchingStrategy,
792 0 : ) -> Option<GetPageBatchBreakReason> {
793 0 : match (self, other) {
794 : (
795 : BatchedFeMessage::GetPage {
796 0 : shard: accum_shard,
797 0 : pages: accum_pages,
798 : ..
799 : },
800 : BatchedFeMessage::GetPage {
801 0 : shard: this_shard,
802 0 : pages: this_pages,
803 : ..
804 : },
805 : ) => {
806 0 : assert_eq!(this_pages.len(), 1);
807 0 : if accum_pages.len() >= max_batch_size.get() {
808 0 : trace!(%max_batch_size, "stopping batching because of batch size");
809 0 : assert_eq!(accum_pages.len(), max_batch_size.get());
810 :
811 0 : return Some(GetPageBatchBreakReason::BatchFull);
812 0 : }
813 0 : if !accum_shard.is_same_handle_as(this_shard) {
814 0 : trace!("stopping batching because timeline object mismatch");
815 : // TODO: we _could_ batch & execute each shard seperately (and in parallel).
816 : // But the current logic for keeping responses in order does not support that.
817 :
818 0 : return Some(GetPageBatchBreakReason::NonUniformTimeline);
819 0 : }
820 :
821 0 : match batching_strategy {
822 : PageServiceProtocolPipelinedBatchingStrategy::UniformLsn => {
823 0 : if let Some(last_in_batch) = accum_pages.last() {
824 0 : if last_in_batch.lsn_range.effective_lsn
825 0 : != this_pages[0].lsn_range.effective_lsn
826 : {
827 0 : trace!(
828 : accum_lsn = %last_in_batch.lsn_range.effective_lsn,
829 0 : this_lsn = %this_pages[0].lsn_range.effective_lsn,
830 0 : "stopping batching because LSN changed"
831 : );
832 :
833 0 : return Some(GetPageBatchBreakReason::NonUniformLsn);
834 0 : }
835 0 : }
836 : }
837 : PageServiceProtocolPipelinedBatchingStrategy::ScatteredLsn => {
838 : // The read path doesn't curently support serving the same page at different LSNs.
839 : // While technically possible, it's uncertain if the complexity is worth it.
840 : // Break the batch if such a case is encountered.
841 0 : let same_page_different_lsn = accum_pages.iter().any(|batched| {
842 0 : batched.req.rel == this_pages[0].req.rel
843 0 : && batched.req.blkno == this_pages[0].req.blkno
844 0 : && batched.lsn_range.effective_lsn
845 0 : != this_pages[0].lsn_range.effective_lsn
846 0 : });
847 :
848 0 : if same_page_different_lsn {
849 0 : trace!(
850 0 : rel=%this_pages[0].req.rel,
851 0 : blkno=%this_pages[0].req.blkno,
852 0 : lsn=%this_pages[0].lsn_range.effective_lsn,
853 0 : "stopping batching because same page was requested at different LSNs"
854 : );
855 :
856 0 : return Some(GetPageBatchBreakReason::SamePageAtDifferentLsn);
857 0 : }
858 : }
859 : }
860 :
861 0 : None
862 : }
863 : #[cfg(feature = "testing")]
864 : (
865 : BatchedFeMessage::Test {
866 0 : shard: accum_shard,
867 0 : requests: accum_requests,
868 : ..
869 : },
870 : BatchedFeMessage::Test {
871 0 : shard: this_shard,
872 0 : requests: this_requests,
873 : ..
874 : },
875 : ) => {
876 0 : assert!(this_requests.len() == 1);
877 0 : if accum_requests.len() >= max_batch_size.get() {
878 0 : trace!(%max_batch_size, "stopping batching because of batch size");
879 0 : assert_eq!(accum_requests.len(), max_batch_size.get());
880 0 : return Some(GetPageBatchBreakReason::BatchFull);
881 0 : }
882 0 : if !accum_shard.is_same_handle_as(this_shard) {
883 0 : trace!("stopping batching because timeline object mismatch");
884 : // TODO: we _could_ batch & execute each shard seperately (and in parallel).
885 : // But the current logic for keeping responses in order does not support that.
886 0 : return Some(GetPageBatchBreakReason::NonUniformTimeline);
887 0 : }
888 0 : let this_batch_key = this_requests[0].req.batch_key;
889 0 : let accum_batch_key = accum_requests[0].req.batch_key;
890 0 : if this_requests[0].req.batch_key != accum_requests[0].req.batch_key {
891 0 : trace!(%accum_batch_key, %this_batch_key, "stopping batching because batch key changed");
892 0 : return Some(GetPageBatchBreakReason::NonUniformKey);
893 0 : }
894 0 : None
895 : }
896 0 : (_, _) => Some(GetPageBatchBreakReason::NonBatchableRequest),
897 : }
898 0 : }
899 : }
900 :
901 : impl PageServerHandler {
902 : #[allow(clippy::too_many_arguments)]
903 0 : pub fn new(
904 0 : tenant_manager: Arc<TenantManager>,
905 0 : auth: Option<Arc<SwappableJwtAuth>>,
906 0 : pipelining_config: PageServicePipeliningConfig,
907 0 : get_vectored_concurrent_io: GetVectoredConcurrentIo,
908 0 : perf_span_fields: ConnectionPerfSpanFields,
909 0 : connection_ctx: RequestContext,
910 0 : cancel: CancellationToken,
911 0 : gate_guard: GateGuard,
912 0 : ) -> Self {
913 0 : PageServerHandler {
914 0 : auth,
915 0 : claims: None,
916 0 : connection_ctx,
917 0 : perf_span_fields,
918 0 : timeline_handles: Some(TimelineHandles::new(tenant_manager)),
919 0 : cancel,
920 0 : pipelining_config,
921 0 : get_vectored_concurrent_io,
922 0 : gate_guard,
923 0 : }
924 0 : }
925 :
926 : /// This function always respects cancellation of any timeline in `[Self::shard_timelines]`. Pass in
927 : /// a cancellation token at the next scope up (such as a tenant cancellation token) to ensure we respect
928 : /// cancellation if there aren't any timelines in the cache.
929 : ///
930 : /// If calling from a function that doesn't use the `[Self::shard_timelines]` cache, then pass in the
931 : /// timeline cancellation token.
932 0 : async fn flush_cancellable<IO>(
933 0 : &self,
934 0 : pgb: &mut PostgresBackend<IO>,
935 0 : cancel: &CancellationToken,
936 0 : ) -> Result<(), QueryError>
937 0 : where
938 0 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
939 0 : {
940 0 : tokio::select!(
941 0 : flush_r = pgb.flush() => {
942 0 : Ok(flush_r?)
943 : },
944 0 : _ = cancel.cancelled() => {
945 0 : Err(QueryError::Shutdown)
946 : }
947 : )
948 0 : }
949 :
950 : #[allow(clippy::too_many_arguments)]
951 0 : async fn pagestream_read_message<IO>(
952 0 : pgb: &mut PostgresBackendReader<IO>,
953 0 : tenant_id: TenantId,
954 0 : timeline_id: TimelineId,
955 0 : timeline_handles: &mut TimelineHandles,
956 0 : conn_perf_span_fields: &ConnectionPerfSpanFields,
957 0 : cancel: &CancellationToken,
958 0 : ctx: &RequestContext,
959 0 : protocol_version: PagestreamProtocolVersion,
960 0 : parent_span: Span,
961 0 : ) -> Result<Option<BatchedFeMessage>, QueryError>
962 0 : where
963 0 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
964 0 : {
965 0 : let msg = tokio::select! {
966 : biased;
967 0 : _ = cancel.cancelled() => {
968 0 : return Err(QueryError::Shutdown)
969 : }
970 0 : msg = pgb.read_message() => { msg }
971 : };
972 :
973 0 : let received_at = Instant::now();
974 :
975 0 : let copy_data_bytes = match msg? {
976 0 : Some(FeMessage::CopyData(bytes)) => bytes,
977 : Some(FeMessage::Terminate) => {
978 0 : return Ok(None);
979 : }
980 0 : Some(m) => {
981 0 : return Err(QueryError::Other(anyhow::anyhow!(
982 0 : "unexpected message: {m:?} during COPY"
983 0 : )));
984 : }
985 : None => {
986 0 : return Ok(None);
987 : } // client disconnected
988 : };
989 0 : trace!("query: {copy_data_bytes:?}");
990 :
991 0 : fail::fail_point!("ps::handle-pagerequest-message");
992 :
993 : // parse request
994 0 : let neon_fe_msg =
995 0 : PagestreamFeMessage::parse(&mut copy_data_bytes.reader(), protocol_version)?;
996 :
997 0 : let batched_msg = match neon_fe_msg {
998 0 : PagestreamFeMessage::Exists(req) => {
999 0 : let shard = timeline_handles
1000 0 : .get(tenant_id, timeline_id, ShardSelector::Zero)
1001 0 : .await?;
1002 0 : debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
1003 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());
1004 0 : let timer = Self::record_op_start_and_throttle(
1005 0 : &shard,
1006 0 : metrics::SmgrQueryType::GetRelExists,
1007 0 : received_at,
1008 0 : )
1009 0 : .await?;
1010 0 : BatchedFeMessage::Exists {
1011 0 : span,
1012 0 : timer,
1013 0 : shard: shard.downgrade(),
1014 0 : req,
1015 0 : }
1016 : }
1017 0 : PagestreamFeMessage::Nblocks(req) => {
1018 0 : let shard = timeline_handles
1019 0 : .get(tenant_id, timeline_id, ShardSelector::Zero)
1020 0 : .await?;
1021 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());
1022 0 : let timer = Self::record_op_start_and_throttle(
1023 0 : &shard,
1024 0 : metrics::SmgrQueryType::GetRelSize,
1025 0 : received_at,
1026 0 : )
1027 0 : .await?;
1028 0 : BatchedFeMessage::Nblocks {
1029 0 : span,
1030 0 : timer,
1031 0 : shard: shard.downgrade(),
1032 0 : req,
1033 0 : }
1034 : }
1035 0 : PagestreamFeMessage::DbSize(req) => {
1036 0 : let shard = timeline_handles
1037 0 : .get(tenant_id, timeline_id, ShardSelector::Zero)
1038 0 : .await?;
1039 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());
1040 0 : let timer = Self::record_op_start_and_throttle(
1041 0 : &shard,
1042 0 : metrics::SmgrQueryType::GetDbSize,
1043 0 : received_at,
1044 0 : )
1045 0 : .await?;
1046 0 : BatchedFeMessage::DbSize {
1047 0 : span,
1048 0 : timer,
1049 0 : shard: shard.downgrade(),
1050 0 : req,
1051 0 : }
1052 : }
1053 0 : PagestreamFeMessage::GetSlruSegment(req) => {
1054 0 : let shard = timeline_handles
1055 0 : .get(tenant_id, timeline_id, ShardSelector::Zero)
1056 0 : .await?;
1057 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());
1058 0 : let timer = Self::record_op_start_and_throttle(
1059 0 : &shard,
1060 0 : metrics::SmgrQueryType::GetSlruSegment,
1061 0 : received_at,
1062 0 : )
1063 0 : .await?;
1064 0 : BatchedFeMessage::GetSlruSegment {
1065 0 : span,
1066 0 : timer,
1067 0 : shard: shard.downgrade(),
1068 0 : req,
1069 0 : }
1070 : }
1071 0 : PagestreamFeMessage::GetPage(req) => {
1072 : // avoid a somewhat costly Span::record() by constructing the entire span in one go.
1073 : macro_rules! mkspan {
1074 : (before shard routing) => {{
1075 : tracing::info_span!(
1076 : parent: &parent_span,
1077 : "handle_get_page_request",
1078 : request_id = %req.hdr.reqid,
1079 : rel = %req.rel,
1080 : blkno = %req.blkno,
1081 : req_lsn = %req.hdr.request_lsn,
1082 : not_modified_since_lsn = %req.hdr.not_modified_since,
1083 : )
1084 : }};
1085 : ($shard_id:expr) => {{
1086 : tracing::info_span!(
1087 : parent: &parent_span,
1088 : "handle_get_page_request",
1089 : request_id = %req.hdr.reqid,
1090 : rel = %req.rel,
1091 : blkno = %req.blkno,
1092 : req_lsn = %req.hdr.request_lsn,
1093 : not_modified_since_lsn = %req.hdr.not_modified_since,
1094 : shard_id = %$shard_id,
1095 : )
1096 : }};
1097 : }
1098 :
1099 : macro_rules! respond_error {
1100 : ($span:expr, $error:expr) => {{
1101 : let error = BatchedFeMessage::RespondError {
1102 : span: $span,
1103 : error: BatchedPageStreamError {
1104 : req: req.hdr,
1105 : err: $error,
1106 : },
1107 : };
1108 : Ok(Some(error))
1109 : }};
1110 : }
1111 :
1112 0 : let key = rel_block_to_key(req.rel, req.blkno);
1113 :
1114 0 : let res = timeline_handles
1115 0 : .get(tenant_id, timeline_id, ShardSelector::Page(key))
1116 0 : .await;
1117 :
1118 0 : let shard = match res {
1119 0 : Ok(tl) => tl,
1120 0 : Err(e) => {
1121 0 : let span = mkspan!(before shard routing);
1122 0 : match e {
1123 : GetActiveTimelineError::Tenant(GetActiveTenantError::NotFound(_)) => {
1124 : // We already know this tenant exists in general, because we resolved it at
1125 : // start of connection. Getting a NotFound here indicates that the shard containing
1126 : // the requested page is not present on this node: the client's knowledge of shard->pageserver
1127 : // mapping is out of date.
1128 : //
1129 : // Closing the connection by returning ``::Reconnect` has the side effect of rate-limiting above message, via
1130 : // client's reconnect backoff, as well as hopefully prompting the client to load its updated configuration
1131 : // and talk to a different pageserver.
1132 0 : MISROUTED_PAGESTREAM_REQUESTS.inc();
1133 0 : return respond_error!(
1134 0 : span,
1135 0 : PageStreamError::Reconnect(
1136 0 : "getpage@lsn request routed to wrong shard".into()
1137 0 : )
1138 : );
1139 : }
1140 0 : e => {
1141 0 : return respond_error!(span, e.into());
1142 : }
1143 : }
1144 : }
1145 : };
1146 :
1147 0 : let ctx = if shard.is_get_page_request_sampled() {
1148 0 : RequestContextBuilder::from(ctx)
1149 0 : .root_perf_span(|| {
1150 0 : info_span!(
1151 : target: PERF_TRACE_TARGET,
1152 : "GET_PAGE",
1153 : peer_addr = conn_perf_span_fields.peer_addr,
1154 : application_name = conn_perf_span_fields.application_name,
1155 : compute_mode = conn_perf_span_fields.compute_mode,
1156 : tenant_id = %tenant_id,
1157 0 : shard_id = %shard.get_shard_identity().shard_slug(),
1158 : timeline_id = %timeline_id,
1159 : lsn = %req.hdr.request_lsn,
1160 : not_modified_since_lsn = %req.hdr.not_modified_since,
1161 : request_id = %req.hdr.reqid,
1162 : key = %key,
1163 : )
1164 0 : })
1165 0 : .attached_child()
1166 : } else {
1167 0 : ctx.attached_child()
1168 : };
1169 :
1170 : // This ctx travels as part of the BatchedFeMessage through
1171 : // batching into the request handler.
1172 : // The request handler needs to do some per-request work
1173 : // (relsize check) before dispatching the batch as a single
1174 : // get_vectored call to the Timeline.
1175 : // This ctx will be used for the reslize check, whereas the
1176 : // get_vectored call will be a different ctx with separate
1177 : // perf span.
1178 0 : let ctx = ctx.with_scope_page_service_pagestream(&shard);
1179 :
1180 : // Similar game for this `span`: we funnel it through so that
1181 : // request handler log messages contain the request-specific fields.
1182 0 : let span = mkspan!(shard.tenant_shard_id.shard_slug());
1183 :
1184 0 : let timer = Self::record_op_start_and_throttle(
1185 0 : &shard,
1186 0 : metrics::SmgrQueryType::GetPageAtLsn,
1187 0 : received_at,
1188 : )
1189 0 : .maybe_perf_instrument(&ctx, |current_perf_span| {
1190 0 : info_span!(
1191 : target: PERF_TRACE_TARGET,
1192 0 : parent: current_perf_span,
1193 : "THROTTLE",
1194 : )
1195 0 : })
1196 0 : .await?;
1197 :
1198 : // We're holding the Handle
1199 0 : let effective_lsn = match Self::effective_request_lsn(
1200 0 : &shard,
1201 0 : shard.get_last_record_lsn(),
1202 0 : req.hdr.request_lsn,
1203 0 : req.hdr.not_modified_since,
1204 0 : &shard.get_applied_gc_cutoff_lsn(),
1205 0 : ) {
1206 0 : Ok(lsn) => lsn,
1207 0 : Err(e) => {
1208 0 : return respond_error!(span, e);
1209 : }
1210 : };
1211 :
1212 0 : let batch_wait_ctx = if ctx.has_perf_span() {
1213 : Some(
1214 0 : RequestContextBuilder::from(&ctx)
1215 0 : .perf_span(|crnt_perf_span| {
1216 0 : info_span!(
1217 : target: PERF_TRACE_TARGET,
1218 0 : parent: crnt_perf_span,
1219 : "WAIT_EXECUTOR",
1220 : )
1221 0 : })
1222 0 : .attached_child(),
1223 : )
1224 : } else {
1225 0 : None
1226 : };
1227 :
1228 : BatchedFeMessage::GetPage {
1229 0 : span,
1230 0 : shard: shard.downgrade(),
1231 0 : pages: smallvec![BatchedGetPageRequest {
1232 0 : req,
1233 0 : timer,
1234 0 : lsn_range: LsnRange {
1235 0 : effective_lsn,
1236 0 : request_lsn: req.hdr.request_lsn
1237 0 : },
1238 0 : ctx,
1239 0 : batch_wait_ctx,
1240 0 : }],
1241 : // The executor grabs the batch when it becomes idle.
1242 : // Hence, [`GetPageBatchBreakReason::ExecutorSteal`] is the
1243 : // default reason for breaking the batch.
1244 0 : batch_break_reason: GetPageBatchBreakReason::ExecutorSteal,
1245 : }
1246 : }
1247 : #[cfg(feature = "testing")]
1248 0 : PagestreamFeMessage::Test(req) => {
1249 0 : let shard = timeline_handles
1250 0 : .get(tenant_id, timeline_id, ShardSelector::Zero)
1251 0 : .await?;
1252 0 : let span = tracing::info_span!(parent: &parent_span, "handle_test_request", shard_id = %shard.tenant_shard_id.shard_slug());
1253 0 : let timer = Self::record_op_start_and_throttle(
1254 0 : &shard,
1255 0 : metrics::SmgrQueryType::Test,
1256 0 : received_at,
1257 0 : )
1258 0 : .await?;
1259 0 : BatchedFeMessage::Test {
1260 0 : span,
1261 0 : shard: shard.downgrade(),
1262 0 : requests: vec![BatchedTestRequest { req, timer }],
1263 0 : }
1264 : }
1265 : };
1266 0 : Ok(Some(batched_msg))
1267 0 : }
1268 :
1269 : /// Starts a SmgrOpTimer at received_at and throttles the request.
1270 0 : async fn record_op_start_and_throttle(
1271 0 : shard: &Handle<TenantManagerTypes>,
1272 0 : op: metrics::SmgrQueryType,
1273 0 : received_at: Instant,
1274 0 : ) -> Result<SmgrOpTimer, QueryError> {
1275 : // It's important to start the smgr op metric recorder as early as possible
1276 : // so that the _started counters are incremented before we do
1277 : // any serious waiting, e.g., for throttle, batching, or actual request handling.
1278 0 : let mut timer = shard.query_metrics.start_smgr_op(op, received_at);
1279 0 : let now = Instant::now();
1280 0 : timer.observe_throttle_start(now);
1281 0 : let throttled = tokio::select! {
1282 0 : res = shard.pagestream_throttle.throttle(1, now) => res,
1283 0 : _ = shard.cancel.cancelled() => return Err(QueryError::Shutdown),
1284 : };
1285 0 : timer.observe_throttle_done(throttled);
1286 0 : Ok(timer)
1287 0 : }
1288 :
1289 : /// Post-condition: `batch` is Some()
1290 : #[instrument(skip_all, level = tracing::Level::TRACE)]
1291 : #[allow(clippy::boxed_local)]
1292 : fn pagestream_do_batch(
1293 : batching_strategy: PageServiceProtocolPipelinedBatchingStrategy,
1294 : max_batch_size: NonZeroUsize,
1295 : batch: &mut Result<BatchedFeMessage, QueryError>,
1296 : this_msg: Result<BatchedFeMessage, QueryError>,
1297 : ) -> Result<(), Result<BatchedFeMessage, QueryError>> {
1298 : debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
1299 :
1300 : let this_msg = match this_msg {
1301 : Ok(this_msg) => this_msg,
1302 : Err(e) => return Err(Err(e)),
1303 : };
1304 :
1305 : let eligible_batch = match batch {
1306 : Ok(b) => b,
1307 : Err(_) => {
1308 : return Err(Ok(this_msg));
1309 : }
1310 : };
1311 :
1312 : let batch_break =
1313 : eligible_batch.should_break_batch(&this_msg, max_batch_size, batching_strategy);
1314 :
1315 : match batch_break {
1316 : Some(reason) => {
1317 : if let BatchedFeMessage::GetPage {
1318 : batch_break_reason, ..
1319 : } = eligible_batch
1320 : {
1321 : *batch_break_reason = reason;
1322 : }
1323 :
1324 : Err(Ok(this_msg))
1325 : }
1326 : None => {
1327 : // ok to batch
1328 : match (eligible_batch, this_msg) {
1329 : (
1330 : BatchedFeMessage::GetPage {
1331 : pages: accum_pages, ..
1332 : },
1333 : BatchedFeMessage::GetPage {
1334 : pages: this_pages, ..
1335 : },
1336 : ) => {
1337 : accum_pages.extend(this_pages);
1338 : Ok(())
1339 : }
1340 : #[cfg(feature = "testing")]
1341 : (
1342 : BatchedFeMessage::Test {
1343 : requests: accum_requests,
1344 : ..
1345 : },
1346 : BatchedFeMessage::Test {
1347 : requests: this_requests,
1348 : ..
1349 : },
1350 : ) => {
1351 : accum_requests.extend(this_requests);
1352 : Ok(())
1353 : }
1354 : // Shape guaranteed by [`BatchedFeMessage::should_break_batch`]
1355 : _ => unreachable!(),
1356 : }
1357 : }
1358 : }
1359 : }
1360 :
1361 0 : #[instrument(level = tracing::Level::DEBUG, skip_all)]
1362 : async fn pagestream_handle_batched_message<IO>(
1363 : &mut self,
1364 : pgb_writer: &mut PostgresBackend<IO>,
1365 : batch: BatchedFeMessage,
1366 : io_concurrency: IoConcurrency,
1367 : cancel: &CancellationToken,
1368 : protocol_version: PagestreamProtocolVersion,
1369 : ctx: &RequestContext,
1370 : ) -> Result<(), QueryError>
1371 : where
1372 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
1373 : {
1374 : let started_at = Instant::now();
1375 : let batch = {
1376 : let mut batch = batch;
1377 : batch.observe_execution_start(started_at);
1378 : batch
1379 : };
1380 :
1381 : // Dispatch the batch to the appropriate request handler.
1382 : let log_slow_name = batch.as_static_str();
1383 : let (mut handler_results, span) = {
1384 : // TODO: we unfortunately have to pin the future on the heap, since GetPage futures are huge and
1385 : // won't fit on the stack.
1386 : let mut boxpinned = Box::pin(Self::pagestream_dispatch_batched_message(
1387 : batch,
1388 : io_concurrency,
1389 : ctx,
1390 : ));
1391 : log_slow(
1392 : log_slow_name,
1393 : LOG_SLOW_GETPAGE_THRESHOLD,
1394 : boxpinned.as_mut(),
1395 : )
1396 : .await?
1397 : };
1398 :
1399 : // We purposefully don't count flush time into the smgr operation timer.
1400 : //
1401 : // The reason is that current compute client will not perform protocol processing
1402 : // if the postgres backend process is doing things other than `->smgr_read()`.
1403 : // This is especially the case for prefetch.
1404 : //
1405 : // If the compute doesn't read from the connection, eventually TCP will backpressure
1406 : // all the way into our flush call below.
1407 : //
1408 : // The timer's underlying metric is used for a storage-internal latency SLO and
1409 : // we don't want to include latency in it that we can't control.
1410 : // And as pointed out above, in this case, we don't control the time that flush will take.
1411 : //
1412 : // We put each response in the batch onto the wire in a separate pgb_writer.flush()
1413 : // call, which (all unmeasured) adds syscall overhead but reduces time to first byte
1414 : // and avoids building up a "giant" contiguous userspace buffer to hold the entire response.
1415 : // TODO: vectored socket IO would be great, but pgb_writer doesn't support that.
1416 : let flush_timers = {
1417 : let flushing_start_time = Instant::now();
1418 : let mut flush_timers = Vec::with_capacity(handler_results.len());
1419 : for handler_result in &mut handler_results {
1420 : let flush_timer = match handler_result {
1421 : Ok((_response, timer, _ctx)) => Some(
1422 : timer
1423 : .observe_execution_end(flushing_start_time)
1424 : .expect("we are the first caller"),
1425 : ),
1426 : Err(_) => {
1427 : // TODO: measure errors
1428 : None
1429 : }
1430 : };
1431 : flush_timers.push(flush_timer);
1432 : }
1433 : assert_eq!(flush_timers.len(), handler_results.len());
1434 : flush_timers
1435 : };
1436 :
1437 : // Map handler result to protocol behavior.
1438 : // Some handler errors cause exit from pagestream protocol.
1439 : // Other handler errors are sent back as an error message and we stay in pagestream protocol.
1440 : for (handler_result, flushing_timer) in handler_results.into_iter().zip(flush_timers) {
1441 : let (response_msg, ctx) = match handler_result {
1442 : Err(e) => match &e.err {
1443 : PageStreamError::Shutdown => {
1444 : // BEGIN HADRON
1445 : PAGESTREAM_HANDLER_RESULTS_TOTAL
1446 : .with_label_values(&[metrics::PAGESTREAM_HANDLER_OUTCOME_OTHER_ERROR])
1447 : .inc();
1448 : // END HADRON
1449 :
1450 : // If we fail to fulfil a request during shutdown, which may be _because_ of
1451 : // shutdown, then do not send the error to the client. Instead just drop the
1452 : // connection.
1453 0 : span.in_scope(|| info!("dropping connection due to shutdown"));
1454 : return Err(QueryError::Shutdown);
1455 : }
1456 : PageStreamError::Reconnect(_reason) => {
1457 0 : span.in_scope(|| {
1458 : // BEGIN HADRON
1459 : // We can get here because the compute node is pointing at the wrong PS. We
1460 : // already have a metric to keep track of this so suppressing this log to
1461 : // reduce log spam. The information in this log message is not going to be that
1462 : // helpful given the volume of logs that can be generated.
1463 : // info!("handler requested reconnect: {reason}")
1464 : // END HADRON
1465 0 : });
1466 : // BEGIN HADRON
1467 : PAGESTREAM_HANDLER_RESULTS_TOTAL
1468 : .with_label_values(&[
1469 : metrics::PAGESTREAM_HANDLER_OUTCOME_INTERNAL_ERROR,
1470 : ])
1471 : .inc();
1472 : // END HADRON
1473 : return Err(QueryError::Reconnect);
1474 : }
1475 : PageStreamError::Read(_)
1476 : | PageStreamError::LsnTimeout(_)
1477 : | PageStreamError::NotFound(_)
1478 : | PageStreamError::BadRequest(_) => {
1479 : // BEGIN HADRON
1480 : if let PageStreamError::Read(_) | PageStreamError::LsnTimeout(_) = &e.err {
1481 : PAGESTREAM_HANDLER_RESULTS_TOTAL
1482 : .with_label_values(&[
1483 : metrics::PAGESTREAM_HANDLER_OUTCOME_INTERNAL_ERROR,
1484 : ])
1485 : .inc();
1486 : } else {
1487 : PAGESTREAM_HANDLER_RESULTS_TOTAL
1488 : .with_label_values(&[
1489 : metrics::PAGESTREAM_HANDLER_OUTCOME_OTHER_ERROR,
1490 : ])
1491 : .inc();
1492 : }
1493 : // END HADRON
1494 :
1495 : // print the all details to the log with {:#}, but for the client the
1496 : // error message is enough. Do not log if shutting down, as the anyhow::Error
1497 : // here includes cancellation which is not an error.
1498 : let full = utils::error::report_compact_sources(&e.err);
1499 0 : span.in_scope(|| {
1500 0 : error!("error reading relation or page version: {full:#}")
1501 0 : });
1502 :
1503 : (
1504 : PagestreamBeMessage::Error(PagestreamErrorResponse {
1505 : req: e.req,
1506 : message: e.err.to_string(),
1507 : }),
1508 : None,
1509 : )
1510 : }
1511 : },
1512 : Ok((response_msg, _op_timer_already_observed, ctx)) => {
1513 : // BEGIN HADRON
1514 : PAGESTREAM_HANDLER_RESULTS_TOTAL
1515 : .with_label_values(&[metrics::PAGESTREAM_HANDLER_OUTCOME_SUCCESS])
1516 : .inc();
1517 : // END HADRON
1518 :
1519 : (response_msg, Some(ctx))
1520 : }
1521 : };
1522 :
1523 0 : let ctx = ctx.map(|req_ctx| {
1524 0 : RequestContextBuilder::from(&req_ctx)
1525 0 : .perf_span(|crnt_perf_span| {
1526 0 : info_span!(
1527 : target: PERF_TRACE_TARGET,
1528 0 : parent: crnt_perf_span,
1529 : "FLUSH_RESPONSE",
1530 : )
1531 0 : })
1532 0 : .attached_child()
1533 0 : });
1534 :
1535 : //
1536 : // marshal & transmit response message
1537 : //
1538 :
1539 : pgb_writer.write_message_noflush(&BeMessage::CopyData(
1540 : &response_msg.serialize(protocol_version),
1541 : ))?;
1542 :
1543 : failpoint_support::sleep_millis_async!("before-pagestream-msg-flush", cancel);
1544 :
1545 : // what we want to do
1546 : let socket_fd = pgb_writer.socket_fd;
1547 : let flush_fut = pgb_writer.flush();
1548 : // metric for how long flushing takes
1549 : let flush_fut = match flushing_timer {
1550 : Some(flushing_timer) => futures::future::Either::Left(flushing_timer.measure(
1551 : Instant::now(),
1552 : flush_fut,
1553 : socket_fd,
1554 : )),
1555 : None => futures::future::Either::Right(flush_fut),
1556 : };
1557 :
1558 : let flush_fut = if let Some(req_ctx) = ctx.as_ref() {
1559 : futures::future::Either::Left(
1560 0 : flush_fut.maybe_perf_instrument(req_ctx, |current_perf_span| {
1561 0 : current_perf_span.clone()
1562 0 : }),
1563 : )
1564 : } else {
1565 : futures::future::Either::Right(flush_fut)
1566 : };
1567 :
1568 : // do it while respecting cancellation
1569 0 : let _: () = async move {
1570 0 : tokio::select! {
1571 : biased;
1572 0 : _ = cancel.cancelled() => {
1573 : // We were requested to shut down.
1574 0 : info!("shutdown request received in page handler");
1575 0 : return Err(QueryError::Shutdown)
1576 : }
1577 0 : res = flush_fut => {
1578 0 : res?;
1579 : }
1580 : }
1581 0 : Ok(())
1582 0 : }
1583 : .await?;
1584 : }
1585 : Ok(())
1586 : }
1587 :
1588 : /// Helper which dispatches a batched message to the appropriate handler.
1589 : /// Returns a vec of results, along with the extracted trace span.
1590 0 : async fn pagestream_dispatch_batched_message(
1591 0 : batch: BatchedFeMessage,
1592 0 : io_concurrency: IoConcurrency,
1593 0 : ctx: &RequestContext,
1594 0 : ) -> Result<
1595 0 : (
1596 0 : Vec<Result<(PagestreamBeMessage, SmgrOpTimer, RequestContext), BatchedPageStreamError>>,
1597 0 : Span,
1598 0 : ),
1599 0 : QueryError,
1600 0 : > {
1601 : macro_rules! upgrade_handle_and_set_context {
1602 : ($shard:ident) => {{
1603 : let weak_handle = &$shard;
1604 : let handle = weak_handle.upgrade()?;
1605 : let ctx = ctx.with_scope_page_service_pagestream(&handle);
1606 : (handle, ctx)
1607 : }};
1608 : }
1609 0 : Ok(match batch {
1610 : BatchedFeMessage::Exists {
1611 0 : span,
1612 0 : timer,
1613 0 : shard,
1614 0 : req,
1615 : } => {
1616 0 : fail::fail_point!("ps::handle-pagerequest-message::exists");
1617 0 : let (shard, ctx) = upgrade_handle_and_set_context!(shard);
1618 : (
1619 0 : vec![
1620 0 : Self::handle_get_rel_exists_request(&shard, &req, &ctx)
1621 0 : .instrument(span.clone())
1622 0 : .await
1623 0 : .map(|msg| (PagestreamBeMessage::Exists(msg), timer, ctx))
1624 0 : .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
1625 : ],
1626 0 : span,
1627 : )
1628 : }
1629 : BatchedFeMessage::Nblocks {
1630 0 : span,
1631 0 : timer,
1632 0 : shard,
1633 0 : req,
1634 : } => {
1635 0 : fail::fail_point!("ps::handle-pagerequest-message::nblocks");
1636 0 : let (shard, ctx) = upgrade_handle_and_set_context!(shard);
1637 : (
1638 0 : vec![
1639 0 : Self::handle_get_nblocks_request(&shard, &req, false, &ctx)
1640 0 : .instrument(span.clone())
1641 0 : .await
1642 0 : .map(|msg| msg.expect("allow_missing=false"))
1643 0 : .map(|msg| (PagestreamBeMessage::Nblocks(msg), timer, ctx))
1644 0 : .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
1645 : ],
1646 0 : span,
1647 : )
1648 : }
1649 : BatchedFeMessage::GetPage {
1650 0 : span,
1651 0 : shard,
1652 0 : pages,
1653 0 : batch_break_reason,
1654 : } => {
1655 0 : fail::fail_point!("ps::handle-pagerequest-message::getpage");
1656 0 : let (shard, ctx) = upgrade_handle_and_set_context!(shard);
1657 : (
1658 : {
1659 0 : let npages = pages.len();
1660 0 : trace!(npages, "handling getpage request");
1661 0 : let res = Self::handle_get_page_at_lsn_request_batched(
1662 0 : &shard,
1663 0 : pages,
1664 0 : io_concurrency,
1665 0 : batch_break_reason,
1666 0 : &ctx,
1667 0 : )
1668 0 : .instrument(span.clone())
1669 0 : .await;
1670 0 : assert_eq!(res.len(), npages);
1671 0 : res
1672 : },
1673 0 : span,
1674 : )
1675 : }
1676 : BatchedFeMessage::DbSize {
1677 0 : span,
1678 0 : timer,
1679 0 : shard,
1680 0 : req,
1681 : } => {
1682 0 : fail::fail_point!("ps::handle-pagerequest-message::dbsize");
1683 0 : let (shard, ctx) = upgrade_handle_and_set_context!(shard);
1684 : (
1685 0 : vec![
1686 0 : Self::handle_db_size_request(&shard, &req, &ctx)
1687 0 : .instrument(span.clone())
1688 0 : .await
1689 0 : .map(|msg| (PagestreamBeMessage::DbSize(msg), timer, ctx))
1690 0 : .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
1691 : ],
1692 0 : span,
1693 : )
1694 : }
1695 : BatchedFeMessage::GetSlruSegment {
1696 0 : span,
1697 0 : timer,
1698 0 : shard,
1699 0 : req,
1700 : } => {
1701 0 : fail::fail_point!("ps::handle-pagerequest-message::slrusegment");
1702 0 : let (shard, ctx) = upgrade_handle_and_set_context!(shard);
1703 : (
1704 0 : vec![
1705 0 : Self::handle_get_slru_segment_request(&shard, &req, &ctx)
1706 0 : .instrument(span.clone())
1707 0 : .await
1708 0 : .map(|msg| (PagestreamBeMessage::GetSlruSegment(msg), timer, ctx))
1709 0 : .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
1710 : ],
1711 0 : span,
1712 : )
1713 : }
1714 : #[cfg(feature = "testing")]
1715 : BatchedFeMessage::Test {
1716 0 : span,
1717 0 : shard,
1718 0 : requests,
1719 : } => {
1720 0 : fail::fail_point!("ps::handle-pagerequest-message::test");
1721 0 : let (shard, ctx) = upgrade_handle_and_set_context!(shard);
1722 : (
1723 : {
1724 0 : let npages = requests.len();
1725 0 : trace!(npages, "handling getpage request");
1726 0 : let res = Self::handle_test_request_batch(&shard, requests, &ctx)
1727 0 : .instrument(span.clone())
1728 0 : .await;
1729 0 : assert_eq!(res.len(), npages);
1730 0 : res
1731 : },
1732 0 : span,
1733 : )
1734 : }
1735 0 : BatchedFeMessage::RespondError { span, error } => {
1736 : // We've already decided to respond with an error, so we don't need to
1737 : // call the handler.
1738 0 : (vec![Err(error)], span)
1739 : }
1740 : })
1741 0 : }
1742 :
1743 : /// Pagestream sub-protocol handler.
1744 : ///
1745 : /// It is a simple request-response protocol inside a COPYBOTH session.
1746 : ///
1747 : /// # Coding Discipline
1748 : ///
1749 : /// Coding discipline within this function: all interaction with the `pgb` connection
1750 : /// needs to be sensitive to connection shutdown, currently signalled via [`Self::cancel`].
1751 : /// This is so that we can shutdown page_service quickly.
1752 : #[instrument(skip_all)]
1753 : async fn handle_pagerequests<IO>(
1754 : &mut self,
1755 : pgb: &mut PostgresBackend<IO>,
1756 : tenant_id: TenantId,
1757 : timeline_id: TimelineId,
1758 : protocol_version: PagestreamProtocolVersion,
1759 : ctx: RequestContext,
1760 : ) -> Result<(), QueryError>
1761 : where
1762 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
1763 : {
1764 : debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
1765 :
1766 : // switch client to COPYBOTH
1767 : pgb.write_message_noflush(&BeMessage::CopyBothResponse)?;
1768 : tokio::select! {
1769 : biased;
1770 : _ = self.cancel.cancelled() => {
1771 : return Err(QueryError::Shutdown)
1772 : }
1773 : res = pgb.flush() => {
1774 : res?;
1775 : }
1776 : }
1777 :
1778 : let io_concurrency = IoConcurrency::spawn_from_conf(
1779 : self.get_vectored_concurrent_io,
1780 : match self.gate_guard.try_clone() {
1781 : Ok(guard) => guard,
1782 : Err(_) => {
1783 : info!("shutdown request received in page handler");
1784 : return Err(QueryError::Shutdown);
1785 : }
1786 : },
1787 : );
1788 :
1789 : let pgb_reader = pgb
1790 : .split()
1791 : .context("implementation error: split pgb into reader and writer")?;
1792 :
1793 : let timeline_handles = self
1794 : .timeline_handles
1795 : .take()
1796 : .expect("implementation error: timeline_handles should not be locked");
1797 :
1798 : let request_span = info_span!("request");
1799 : let ((pgb_reader, timeline_handles), result) = match self.pipelining_config.clone() {
1800 : PageServicePipeliningConfig::Pipelined(pipelining_config) => {
1801 : self.handle_pagerequests_pipelined(
1802 : pgb,
1803 : pgb_reader,
1804 : tenant_id,
1805 : timeline_id,
1806 : timeline_handles,
1807 : request_span,
1808 : pipelining_config,
1809 : protocol_version,
1810 : io_concurrency,
1811 : &ctx,
1812 : )
1813 : .await
1814 : }
1815 : PageServicePipeliningConfig::Serial => {
1816 : self.handle_pagerequests_serial(
1817 : pgb,
1818 : pgb_reader,
1819 : tenant_id,
1820 : timeline_id,
1821 : timeline_handles,
1822 : request_span,
1823 : protocol_version,
1824 : io_concurrency,
1825 : &ctx,
1826 : )
1827 : .await
1828 : }
1829 : };
1830 :
1831 : debug!("pagestream subprotocol shut down cleanly");
1832 :
1833 : pgb.unsplit(pgb_reader)
1834 : .context("implementation error: unsplit pgb")?;
1835 :
1836 : let replaced = self.timeline_handles.replace(timeline_handles);
1837 : assert!(replaced.is_none());
1838 :
1839 : result
1840 : }
1841 :
1842 : #[allow(clippy::too_many_arguments)]
1843 0 : async fn handle_pagerequests_serial<IO>(
1844 0 : &mut self,
1845 0 : pgb_writer: &mut PostgresBackend<IO>,
1846 0 : mut pgb_reader: PostgresBackendReader<IO>,
1847 0 : tenant_id: TenantId,
1848 0 : timeline_id: TimelineId,
1849 0 : mut timeline_handles: TimelineHandles,
1850 0 : request_span: Span,
1851 0 : protocol_version: PagestreamProtocolVersion,
1852 0 : io_concurrency: IoConcurrency,
1853 0 : ctx: &RequestContext,
1854 0 : ) -> (
1855 0 : (PostgresBackendReader<IO>, TimelineHandles),
1856 0 : Result<(), QueryError>,
1857 0 : )
1858 0 : where
1859 0 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
1860 0 : {
1861 0 : let cancel = self.cancel.clone();
1862 :
1863 0 : let err = loop {
1864 0 : let msg = Self::pagestream_read_message(
1865 0 : &mut pgb_reader,
1866 0 : tenant_id,
1867 0 : timeline_id,
1868 0 : &mut timeline_handles,
1869 0 : &self.perf_span_fields,
1870 0 : &cancel,
1871 0 : ctx,
1872 0 : protocol_version,
1873 0 : request_span.clone(),
1874 0 : )
1875 0 : .await;
1876 0 : let msg = match msg {
1877 0 : Ok(msg) => msg,
1878 0 : Err(e) => break e,
1879 : };
1880 0 : let msg = match msg {
1881 0 : Some(msg) => msg,
1882 : None => {
1883 0 : debug!("pagestream subprotocol end observed");
1884 0 : return ((pgb_reader, timeline_handles), Ok(()));
1885 : }
1886 : };
1887 :
1888 0 : let result = self
1889 0 : .pagestream_handle_batched_message(
1890 0 : pgb_writer,
1891 0 : msg,
1892 0 : io_concurrency.clone(),
1893 0 : &cancel,
1894 0 : protocol_version,
1895 0 : ctx,
1896 0 : )
1897 0 : .await;
1898 0 : match result {
1899 0 : Ok(()) => {}
1900 0 : Err(e) => break e,
1901 : }
1902 : };
1903 0 : ((pgb_reader, timeline_handles), Err(err))
1904 0 : }
1905 :
1906 : /// # Cancel-Safety
1907 : ///
1908 : /// May leak tokio tasks if not polled to completion.
1909 : #[allow(clippy::too_many_arguments)]
1910 0 : async fn handle_pagerequests_pipelined<IO>(
1911 0 : &mut self,
1912 0 : pgb_writer: &mut PostgresBackend<IO>,
1913 0 : pgb_reader: PostgresBackendReader<IO>,
1914 0 : tenant_id: TenantId,
1915 0 : timeline_id: TimelineId,
1916 0 : mut timeline_handles: TimelineHandles,
1917 0 : request_span: Span,
1918 0 : pipelining_config: PageServicePipeliningConfigPipelined,
1919 0 : protocol_version: PagestreamProtocolVersion,
1920 0 : io_concurrency: IoConcurrency,
1921 0 : ctx: &RequestContext,
1922 0 : ) -> (
1923 0 : (PostgresBackendReader<IO>, TimelineHandles),
1924 0 : Result<(), QueryError>,
1925 0 : )
1926 0 : where
1927 0 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
1928 0 : {
1929 : //
1930 : // Pipelined pagestream handling consists of
1931 : // - a Batcher that reads requests off the wire and
1932 : // and batches them if possible,
1933 : // - an Executor that processes the batched requests.
1934 : //
1935 : // The batch is built up inside an `spsc_fold` channel,
1936 : // shared betwen Batcher (Sender) and Executor (Receiver).
1937 : //
1938 : // The Batcher continously folds client requests into the batch,
1939 : // while the Executor can at any time take out what's in the batch
1940 : // in order to process it.
1941 : // This means the next batch builds up while the Executor
1942 : // executes the last batch.
1943 : //
1944 : // CANCELLATION
1945 : //
1946 : // We run both Batcher and Executor futures to completion before
1947 : // returning from this function.
1948 : //
1949 : // If Executor exits first, it signals cancellation to the Batcher
1950 : // via a CancellationToken that is child of `self.cancel`.
1951 : // If Batcher exits first, it signals cancellation to the Executor
1952 : // by dropping the spsc_fold channel Sender.
1953 : //
1954 : // CLEAN SHUTDOWN
1955 : //
1956 : // Clean shutdown means that the client ends the COPYBOTH session.
1957 : // In response to such a client message, the Batcher exits.
1958 : // The Executor continues to run, draining the spsc_fold channel.
1959 : // Once drained, the spsc_fold recv will fail with a distinct error
1960 : // indicating that the sender disconnected.
1961 : // The Executor exits with Ok(()) in response to that error.
1962 : //
1963 : // Server initiated shutdown is not clean shutdown, but instead
1964 : // is an error Err(QueryError::Shutdown) that is propagated through
1965 : // error propagation.
1966 : //
1967 : // ERROR PROPAGATION
1968 : //
1969 : // When the Batcher encounter an error, it sends it as a value
1970 : // through the spsc_fold channel and exits afterwards.
1971 : // When the Executor observes such an error in the channel,
1972 : // it exits returning that error value.
1973 : //
1974 : // This design ensures that the Executor stage will still process
1975 : // the batch that was in flight when the Batcher encountered an error,
1976 : // thereby beahving identical to a serial implementation.
1977 :
1978 : let PageServicePipeliningConfigPipelined {
1979 0 : max_batch_size,
1980 0 : execution,
1981 0 : batching: batching_strategy,
1982 0 : } = pipelining_config;
1983 :
1984 : // Macro to _define_ a pipeline stage.
1985 : macro_rules! pipeline_stage {
1986 : ($name:literal, $cancel:expr, $make_fut:expr) => {{
1987 : let cancel: CancellationToken = $cancel;
1988 : let stage_fut = $make_fut(cancel.clone());
1989 0 : async move {
1990 0 : scopeguard::defer! {
1991 : debug!("exiting");
1992 : }
1993 0 : timed_after_cancellation(stage_fut, $name, Duration::from_millis(100), &cancel)
1994 0 : .await
1995 0 : }
1996 : .instrument(tracing::info_span!($name))
1997 : }};
1998 : }
1999 :
2000 : //
2001 : // Batcher
2002 : //
2003 :
2004 0 : let perf_span_fields = self.perf_span_fields.clone();
2005 :
2006 0 : let cancel_batcher = self.cancel.child_token();
2007 0 : let (mut batch_tx, mut batch_rx) = spsc_fold::channel();
2008 0 : let batcher = pipeline_stage!("batcher", cancel_batcher.clone(), move |cancel_batcher| {
2009 0 : let ctx = ctx.attached_child();
2010 0 : async move {
2011 0 : let mut pgb_reader = pgb_reader;
2012 0 : let mut exit = false;
2013 0 : while !exit {
2014 0 : let read_res = Self::pagestream_read_message(
2015 0 : &mut pgb_reader,
2016 0 : tenant_id,
2017 0 : timeline_id,
2018 0 : &mut timeline_handles,
2019 0 : &perf_span_fields,
2020 0 : &cancel_batcher,
2021 0 : &ctx,
2022 0 : protocol_version,
2023 0 : request_span.clone(),
2024 0 : )
2025 0 : .await;
2026 0 : let Some(read_res) = read_res.transpose() else {
2027 0 : debug!("client-initiated shutdown");
2028 0 : break;
2029 : };
2030 0 : exit |= read_res.is_err();
2031 0 : let could_send = batch_tx
2032 0 : .send(read_res, |batch, res| {
2033 0 : Self::pagestream_do_batch(batching_strategy, max_batch_size, batch, res)
2034 0 : })
2035 0 : .await;
2036 0 : exit |= could_send.is_err();
2037 : }
2038 0 : (pgb_reader, timeline_handles)
2039 0 : }
2040 0 : });
2041 :
2042 : //
2043 : // Executor
2044 : //
2045 :
2046 0 : let executor = pipeline_stage!("executor", self.cancel.clone(), move |cancel| {
2047 0 : let ctx = ctx.attached_child();
2048 0 : async move {
2049 0 : let _cancel_batcher = cancel_batcher.drop_guard();
2050 : loop {
2051 0 : let maybe_batch = batch_rx.recv().await;
2052 0 : let batch = match maybe_batch {
2053 0 : Ok(batch) => batch,
2054 : Err(spsc_fold::RecvError::SenderGone) => {
2055 0 : debug!("upstream gone");
2056 0 : return Ok(());
2057 : }
2058 : };
2059 0 : let mut batch = match batch {
2060 0 : Ok(batch) => batch,
2061 0 : Err(e) => {
2062 0 : return Err(e);
2063 : }
2064 : };
2065 :
2066 : if let BatchedFeMessage::GetPage {
2067 0 : pages,
2068 : span: _,
2069 : shard: _,
2070 : batch_break_reason: _,
2071 0 : } = &mut batch
2072 : {
2073 0 : for req in pages {
2074 0 : req.batch_wait_ctx.take();
2075 0 : }
2076 0 : }
2077 :
2078 0 : self.pagestream_handle_batched_message(
2079 0 : pgb_writer,
2080 0 : batch,
2081 0 : io_concurrency.clone(),
2082 0 : &cancel,
2083 0 : protocol_version,
2084 0 : &ctx,
2085 0 : )
2086 0 : .await?;
2087 : }
2088 0 : }
2089 0 : });
2090 :
2091 : //
2092 : // Execute the stages.
2093 : //
2094 :
2095 0 : match execution {
2096 : PageServiceProtocolPipelinedExecutionStrategy::ConcurrentFutures => {
2097 0 : tokio::join!(batcher, executor)
2098 : }
2099 : PageServiceProtocolPipelinedExecutionStrategy::Tasks => {
2100 : // These tasks are not tracked anywhere.
2101 0 : let read_messages_task = tokio::spawn(batcher);
2102 0 : let (read_messages_task_res, executor_res_) =
2103 0 : tokio::join!(read_messages_task, executor,);
2104 0 : (
2105 0 : read_messages_task_res.expect("propagated panic from read_messages"),
2106 0 : executor_res_,
2107 0 : )
2108 : }
2109 : }
2110 0 : }
2111 :
2112 : /// Helper function to handle the LSN from client request.
2113 : ///
2114 : /// Each GetPage (and Exists and Nblocks) request includes information about
2115 : /// which version of the page is being requested. The primary compute node
2116 : /// will always request the latest page version, by setting 'request_lsn' to
2117 : /// the last inserted or flushed WAL position, while a standby will request
2118 : /// a version at the LSN that it's currently caught up to.
2119 : ///
2120 : /// In either case, if the page server hasn't received the WAL up to the
2121 : /// requested LSN yet, we will wait for it to arrive. The return value is
2122 : /// the LSN that should be used to look up the page versions.
2123 : ///
2124 : /// In addition to the request LSN, each request carries another LSN,
2125 : /// 'not_modified_since', which is a hint to the pageserver that the client
2126 : /// knows that the page has not been modified between 'not_modified_since'
2127 : /// and the request LSN. This allows skipping the wait, as long as the WAL
2128 : /// up to 'not_modified_since' has arrived. If the client doesn't have any
2129 : /// information about when the page was modified, it will use
2130 : /// not_modified_since == lsn. If the client lies and sends a too low
2131 : /// not_modified_hint such that there are in fact later page versions, the
2132 : /// behavior is undefined: the pageserver may return any of the page versions
2133 : /// or an error.
2134 0 : async fn wait_or_get_last_lsn(
2135 0 : timeline: &Timeline,
2136 0 : request_lsn: Lsn,
2137 0 : not_modified_since: Lsn,
2138 0 : latest_gc_cutoff_lsn: &RcuReadGuard<Lsn>,
2139 0 : ctx: &RequestContext,
2140 0 : ) -> Result<Lsn, PageStreamError> {
2141 0 : let last_record_lsn = timeline.get_last_record_lsn();
2142 0 : let effective_request_lsn = Self::effective_request_lsn(
2143 0 : timeline,
2144 0 : last_record_lsn,
2145 0 : request_lsn,
2146 0 : not_modified_since,
2147 0 : latest_gc_cutoff_lsn,
2148 0 : )?;
2149 :
2150 0 : if effective_request_lsn > last_record_lsn {
2151 0 : timeline
2152 0 : .wait_lsn(
2153 0 : not_modified_since,
2154 0 : crate::tenant::timeline::WaitLsnWaiter::PageService,
2155 0 : timeline::WaitLsnTimeout::Default,
2156 0 : ctx,
2157 0 : )
2158 0 : .await?;
2159 :
2160 : // Since we waited for 'effective_request_lsn' to arrive, that is now the last
2161 : // record LSN. (Or close enough for our purposes; the last-record LSN can
2162 : // advance immediately after we return anyway)
2163 0 : }
2164 :
2165 0 : Ok(effective_request_lsn)
2166 0 : }
2167 :
2168 0 : fn effective_request_lsn(
2169 0 : timeline: &Timeline,
2170 0 : last_record_lsn: Lsn,
2171 0 : request_lsn: Lsn,
2172 0 : not_modified_since: Lsn,
2173 0 : latest_gc_cutoff_lsn: &RcuReadGuard<Lsn>,
2174 0 : ) -> Result<Lsn, PageStreamError> {
2175 : // Sanity check the request
2176 0 : if request_lsn < not_modified_since {
2177 0 : return Err(PageStreamError::BadRequest(
2178 0 : format!(
2179 0 : "invalid request with request LSN {request_lsn} and not_modified_since {not_modified_since}",
2180 0 : )
2181 0 : .into(),
2182 0 : ));
2183 0 : }
2184 :
2185 : // Check explicitly for INVALID just to get a less scary error message if the request is obviously bogus
2186 0 : if request_lsn == Lsn::INVALID {
2187 0 : return Err(PageStreamError::BadRequest(
2188 0 : "invalid LSN(0) in request".into(),
2189 0 : ));
2190 0 : }
2191 :
2192 : // Clients should only read from recent LSNs on their timeline, or from locations holding an LSN lease.
2193 : //
2194 : // We may have older data available, but we make a best effort to detect this case and return an error,
2195 : // to distinguish a misbehaving client (asking for old LSN) from a storage issue (data missing at a legitimate LSN).
2196 0 : if request_lsn < **latest_gc_cutoff_lsn && !timeline.is_gc_blocked_by_lsn_lease_deadline() {
2197 0 : let gc_info = &timeline.gc_info.read().unwrap();
2198 0 : if !gc_info.lsn_covered_by_lease(request_lsn) {
2199 0 : return Err(
2200 0 : PageStreamError::BadRequest(format!(
2201 0 : "tried to request a page version that was garbage collected. requested at {} gc cutoff {}",
2202 0 : request_lsn, **latest_gc_cutoff_lsn
2203 0 : ).into())
2204 0 : );
2205 0 : }
2206 0 : }
2207 :
2208 0 : if not_modified_since > last_record_lsn {
2209 0 : Ok(not_modified_since)
2210 : } else {
2211 : // It might be better to use max(not_modified_since, latest_gc_cutoff_lsn)
2212 : // here instead. That would give the same result, since we know that there
2213 : // haven't been any modifications since 'not_modified_since'. Using an older
2214 : // LSN might be faster, because that could allow skipping recent layers when
2215 : // finding the page. However, we have historically used 'last_record_lsn', so
2216 : // stick to that for now.
2217 0 : Ok(std::cmp::min(last_record_lsn, request_lsn))
2218 : }
2219 0 : }
2220 :
2221 : /// Handles the lsn lease request.
2222 : /// If a lease cannot be obtained, the client will receive NULL.
2223 : #[instrument(skip_all, fields(shard_id, %lsn))]
2224 : async fn handle_make_lsn_lease<IO>(
2225 : &mut self,
2226 : pgb: &mut PostgresBackend<IO>,
2227 : tenant_shard_id: TenantShardId,
2228 : timeline_id: TimelineId,
2229 : lsn: Lsn,
2230 : ctx: &RequestContext,
2231 : ) -> Result<(), QueryError>
2232 : where
2233 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
2234 : {
2235 : let timeline = self
2236 : .timeline_handles
2237 : .as_mut()
2238 : .unwrap()
2239 : .get(
2240 : tenant_shard_id.tenant_id,
2241 : timeline_id,
2242 : ShardSelector::Known(tenant_shard_id.to_index()),
2243 : )
2244 : .await?;
2245 : set_tracing_field_shard_id(&timeline);
2246 :
2247 : let lease = timeline
2248 : .renew_lsn_lease(lsn, timeline.get_lsn_lease_length(), ctx)
2249 0 : .inspect_err(|e| {
2250 0 : warn!("{e}");
2251 0 : })
2252 : .ok();
2253 0 : let valid_until_str = lease.map(|l| {
2254 0 : l.valid_until
2255 0 : .duration_since(SystemTime::UNIX_EPOCH)
2256 0 : .expect("valid_until is earlier than UNIX_EPOCH")
2257 0 : .as_millis()
2258 0 : .to_string()
2259 0 : });
2260 :
2261 : info!(
2262 : "acquired lease for {} until {}",
2263 : lsn,
2264 : valid_until_str.as_deref().unwrap_or("<unknown>")
2265 : );
2266 :
2267 0 : let bytes = valid_until_str.as_ref().map(|x| x.as_bytes());
2268 :
2269 : pgb.write_message_noflush(&BeMessage::RowDescription(&[RowDescriptor::text_col(
2270 : b"valid_until",
2271 : )]))?
2272 : .write_message_noflush(&BeMessage::DataRow(&[bytes]))?;
2273 :
2274 : Ok(())
2275 : }
2276 :
2277 : #[instrument(skip_all, fields(shard_id))]
2278 : async fn handle_get_rel_exists_request(
2279 : timeline: &Timeline,
2280 : req: &PagestreamExistsRequest,
2281 : ctx: &RequestContext,
2282 : ) -> Result<PagestreamExistsResponse, PageStreamError> {
2283 : let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
2284 : let lsn = Self::wait_or_get_last_lsn(
2285 : timeline,
2286 : req.hdr.request_lsn,
2287 : req.hdr.not_modified_since,
2288 : &latest_gc_cutoff_lsn,
2289 : ctx,
2290 : )
2291 : .await?;
2292 :
2293 : let exists = timeline
2294 : .get_rel_exists(
2295 : req.rel,
2296 : Version::LsnRange(LsnRange {
2297 : effective_lsn: lsn,
2298 : request_lsn: req.hdr.request_lsn,
2299 : }),
2300 : ctx,
2301 : )
2302 : .await?;
2303 :
2304 : Ok(PagestreamExistsResponse { req: *req, exists })
2305 : }
2306 :
2307 : /// If `allow_missing` is true, returns None instead of Err on missing relations. Otherwise,
2308 : /// never returns None. It is only supported by the gRPC protocol, so we pass it separately to
2309 : /// avoid changing the libpq protocol types.
2310 : #[instrument(skip_all, fields(shard_id))]
2311 : async fn handle_get_nblocks_request(
2312 : timeline: &Timeline,
2313 : req: &PagestreamNblocksRequest,
2314 : allow_missing: bool,
2315 : ctx: &RequestContext,
2316 : ) -> Result<Option<PagestreamNblocksResponse>, PageStreamError> {
2317 : let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
2318 : let lsn = Self::wait_or_get_last_lsn(
2319 : timeline,
2320 : req.hdr.request_lsn,
2321 : req.hdr.not_modified_since,
2322 : &latest_gc_cutoff_lsn,
2323 : ctx,
2324 : )
2325 : .await?;
2326 :
2327 : let n_blocks = timeline
2328 : .get_rel_size_in_reldir(
2329 : req.rel,
2330 : Version::LsnRange(LsnRange {
2331 : effective_lsn: lsn,
2332 : request_lsn: req.hdr.request_lsn,
2333 : }),
2334 : None,
2335 : allow_missing,
2336 : ctx,
2337 : )
2338 : .await?;
2339 : let Some(n_blocks) = n_blocks else {
2340 : return Ok(None);
2341 : };
2342 :
2343 : Ok(Some(PagestreamNblocksResponse {
2344 : req: *req,
2345 : n_blocks,
2346 : }))
2347 : }
2348 :
2349 : #[instrument(skip_all, fields(shard_id))]
2350 : async fn handle_db_size_request(
2351 : timeline: &Timeline,
2352 : req: &PagestreamDbSizeRequest,
2353 : ctx: &RequestContext,
2354 : ) -> Result<PagestreamDbSizeResponse, PageStreamError> {
2355 : let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
2356 : let lsn = Self::wait_or_get_last_lsn(
2357 : timeline,
2358 : req.hdr.request_lsn,
2359 : req.hdr.not_modified_since,
2360 : &latest_gc_cutoff_lsn,
2361 : ctx,
2362 : )
2363 : .await?;
2364 :
2365 : let total_blocks = timeline
2366 : .get_db_size(
2367 : DEFAULTTABLESPACE_OID,
2368 : req.dbnode,
2369 : Version::LsnRange(LsnRange {
2370 : effective_lsn: lsn,
2371 : request_lsn: req.hdr.request_lsn,
2372 : }),
2373 : ctx,
2374 : )
2375 : .await?;
2376 : let db_size = total_blocks as i64 * BLCKSZ as i64;
2377 :
2378 : Ok(PagestreamDbSizeResponse { req: *req, db_size })
2379 : }
2380 :
2381 : #[instrument(skip_all)]
2382 : async fn handle_get_page_at_lsn_request_batched(
2383 : timeline: &Timeline,
2384 : requests: SmallVec<[BatchedGetPageRequest; 1]>,
2385 : io_concurrency: IoConcurrency,
2386 : batch_break_reason: GetPageBatchBreakReason,
2387 : ctx: &RequestContext,
2388 : ) -> Vec<Result<(PagestreamBeMessage, SmgrOpTimer, RequestContext), BatchedPageStreamError>>
2389 : {
2390 : debug_assert_current_span_has_tenant_and_timeline_id();
2391 :
2392 : timeline
2393 : .query_metrics
2394 : .observe_getpage_batch_start(requests.len(), batch_break_reason);
2395 :
2396 : // If a page trace is running, submit an event for this request.
2397 : if let Some(page_trace) = timeline.page_trace.load().as_ref() {
2398 : let time = SystemTime::now();
2399 : for batch in &requests {
2400 : let key = rel_block_to_key(batch.req.rel, batch.req.blkno).to_compact();
2401 : // Ignore error (trace buffer may be full or tracer may have disconnected).
2402 : _ = page_trace.try_send(PageTraceEvent {
2403 : key,
2404 : effective_lsn: batch.lsn_range.effective_lsn,
2405 : time,
2406 : });
2407 : }
2408 : }
2409 :
2410 : // If any request in the batch needs to wait for LSN, then do so now.
2411 : let mut perf_instrument = false;
2412 : let max_effective_lsn = requests
2413 : .iter()
2414 0 : .map(|req| {
2415 0 : if req.ctx.has_perf_span() {
2416 0 : perf_instrument = true;
2417 0 : }
2418 :
2419 0 : req.lsn_range.effective_lsn
2420 0 : })
2421 : .max()
2422 : .expect("batch is never empty");
2423 :
2424 : let ctx = match perf_instrument {
2425 : true => RequestContextBuilder::from(ctx)
2426 0 : .root_perf_span(|| {
2427 0 : info_span!(
2428 : target: PERF_TRACE_TARGET,
2429 : "GET_VECTORED",
2430 : tenant_id = %timeline.tenant_shard_id.tenant_id,
2431 : timeline_id = %timeline.timeline_id,
2432 0 : shard = %timeline.tenant_shard_id.shard_slug(),
2433 : %max_effective_lsn
2434 : )
2435 0 : })
2436 : .attached_child(),
2437 : false => ctx.attached_child(),
2438 : };
2439 :
2440 : let last_record_lsn = timeline.get_last_record_lsn();
2441 : if max_effective_lsn > last_record_lsn {
2442 : if let Err(e) = timeline
2443 : .wait_lsn(
2444 : max_effective_lsn,
2445 : crate::tenant::timeline::WaitLsnWaiter::PageService,
2446 : timeline::WaitLsnTimeout::Default,
2447 : &ctx,
2448 : )
2449 0 : .maybe_perf_instrument(&ctx, |current_perf_span| {
2450 0 : info_span!(
2451 : target: PERF_TRACE_TARGET,
2452 0 : parent: current_perf_span,
2453 : "WAIT_LSN",
2454 : )
2455 0 : })
2456 : .await
2457 : {
2458 0 : return Vec::from_iter(requests.into_iter().map(|req| {
2459 0 : Err(BatchedPageStreamError {
2460 0 : err: PageStreamError::from(e.clone()),
2461 0 : req: req.req.hdr,
2462 0 : })
2463 0 : }));
2464 : }
2465 : }
2466 :
2467 : let results = timeline
2468 : .get_rel_page_at_lsn_batched(
2469 0 : requests.iter().map(|p| {
2470 0 : (
2471 0 : &p.req.rel,
2472 0 : &p.req.blkno,
2473 0 : p.lsn_range,
2474 0 : p.ctx.attached_child(),
2475 0 : )
2476 0 : }),
2477 : io_concurrency,
2478 : &ctx,
2479 : )
2480 : .await;
2481 : assert_eq!(results.len(), requests.len());
2482 :
2483 : // TODO: avoid creating the new Vec here
2484 : Vec::from_iter(
2485 : requests
2486 : .into_iter()
2487 : .zip(results.into_iter())
2488 0 : .map(|(req, res)| {
2489 0 : res.map(|page| {
2490 0 : (
2491 0 : PagestreamBeMessage::GetPage(
2492 0 : pagestream_api::PagestreamGetPageResponse { req: req.req, page },
2493 0 : ),
2494 0 : req.timer,
2495 0 : req.ctx,
2496 0 : )
2497 0 : })
2498 0 : .map_err(|e| BatchedPageStreamError {
2499 0 : err: PageStreamError::from(e),
2500 0 : req: req.req.hdr,
2501 0 : })
2502 0 : }),
2503 : )
2504 : }
2505 :
2506 : #[instrument(skip_all, fields(shard_id))]
2507 : async fn handle_get_slru_segment_request(
2508 : timeline: &Timeline,
2509 : req: &PagestreamGetSlruSegmentRequest,
2510 : ctx: &RequestContext,
2511 : ) -> Result<PagestreamGetSlruSegmentResponse, PageStreamError> {
2512 : let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
2513 : let lsn = Self::wait_or_get_last_lsn(
2514 : timeline,
2515 : req.hdr.request_lsn,
2516 : req.hdr.not_modified_since,
2517 : &latest_gc_cutoff_lsn,
2518 : ctx,
2519 : )
2520 : .await?;
2521 :
2522 : let kind = SlruKind::from_repr(req.kind)
2523 : .ok_or(PageStreamError::BadRequest("invalid SLRU kind".into()))?;
2524 : let segment = timeline.get_slru_segment(kind, req.segno, lsn, ctx).await?;
2525 :
2526 : Ok(PagestreamGetSlruSegmentResponse { req: *req, segment })
2527 : }
2528 :
2529 : // NB: this impl mimics what we do for batched getpage requests.
2530 : #[cfg(feature = "testing")]
2531 : #[instrument(skip_all, fields(shard_id))]
2532 : async fn handle_test_request_batch(
2533 : timeline: &Timeline,
2534 : requests: Vec<BatchedTestRequest>,
2535 : _ctx: &RequestContext,
2536 : ) -> Vec<Result<(PagestreamBeMessage, SmgrOpTimer, RequestContext), BatchedPageStreamError>>
2537 : {
2538 : // real requests would do something with the timeline
2539 : let mut results = Vec::with_capacity(requests.len());
2540 : for _req in requests.iter() {
2541 : tokio::task::yield_now().await;
2542 :
2543 : results.push({
2544 : if timeline.cancel.is_cancelled() {
2545 : Err(PageReconstructError::Cancelled)
2546 : } else {
2547 : Ok(())
2548 : }
2549 : });
2550 : }
2551 :
2552 : // TODO: avoid creating the new Vec here
2553 : Vec::from_iter(
2554 : requests
2555 : .into_iter()
2556 : .zip(results.into_iter())
2557 0 : .map(|(req, res)| {
2558 0 : res.map(|()| {
2559 0 : (
2560 0 : PagestreamBeMessage::Test(pagestream_api::PagestreamTestResponse {
2561 0 : req: req.req.clone(),
2562 0 : }),
2563 0 : req.timer,
2564 0 : RequestContext::new(
2565 0 : TaskKind::PageRequestHandler,
2566 0 : DownloadBehavior::Warn,
2567 0 : ),
2568 0 : )
2569 0 : })
2570 0 : .map_err(|e| BatchedPageStreamError {
2571 0 : err: PageStreamError::from(e),
2572 0 : req: req.req.hdr,
2573 0 : })
2574 0 : }),
2575 : )
2576 : }
2577 :
2578 : /// Note on "fullbackup":
2579 : /// Full basebackups should only be used for debugging purposes.
2580 : /// Originally, it was introduced to enable breaking storage format changes,
2581 : /// but that is not applicable anymore.
2582 : ///
2583 : /// # Coding Discipline
2584 : ///
2585 : /// Coding discipline within this function: all interaction with the `pgb` connection
2586 : /// needs to be sensitive to connection shutdown, currently signalled via [`Self::cancel`].
2587 : /// This is so that we can shutdown page_service quickly.
2588 : ///
2589 : /// TODO: wrap the pgb that we pass to the basebackup handler so that it's sensitive
2590 : /// to connection cancellation.
2591 : #[allow(clippy::too_many_arguments)]
2592 : #[instrument(skip_all, fields(shard_id, ?lsn, ?prev_lsn, %full_backup))]
2593 : async fn handle_basebackup_request<IO>(
2594 : &mut self,
2595 : pgb: &mut PostgresBackend<IO>,
2596 : tenant_id: TenantId,
2597 : timeline_id: TimelineId,
2598 : lsn: Option<Lsn>,
2599 : prev_lsn: Option<Lsn>,
2600 : full_backup: bool,
2601 : gzip: bool,
2602 : replica: bool,
2603 : ctx: &RequestContext,
2604 : ) -> Result<(), QueryError>
2605 : where
2606 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
2607 : {
2608 : let started = std::time::Instant::now();
2609 :
2610 : let timeline = self
2611 : .timeline_handles
2612 : .as_mut()
2613 : .unwrap()
2614 : .get(tenant_id, timeline_id, ShardSelector::Zero)
2615 : .await?;
2616 : set_tracing_field_shard_id(&timeline);
2617 : let ctx = ctx.with_scope_timeline(&timeline);
2618 :
2619 : if timeline.is_archived() == Some(true) {
2620 : tracing::info!(
2621 : "timeline {tenant_id}/{timeline_id} is archived, but got basebackup request for it."
2622 : );
2623 : return Err(QueryError::NotFound("timeline is archived".into()));
2624 : }
2625 :
2626 : let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
2627 : if let Some(lsn) = lsn {
2628 : // Backup was requested at a particular LSN. Wait for it to arrive.
2629 : info!("waiting for {}", lsn);
2630 : timeline
2631 : .wait_lsn(
2632 : lsn,
2633 : crate::tenant::timeline::WaitLsnWaiter::PageService,
2634 : crate::tenant::timeline::WaitLsnTimeout::Default,
2635 : &ctx,
2636 : )
2637 : .await?;
2638 : timeline
2639 : .check_lsn_is_in_scope(lsn, &latest_gc_cutoff_lsn)
2640 : .context("invalid basebackup lsn")?;
2641 : }
2642 :
2643 : let lsn_awaited_after = started.elapsed();
2644 :
2645 : // switch client to COPYOUT
2646 : pgb.write_message_noflush(&BeMessage::CopyOutResponse)
2647 : .map_err(QueryError::Disconnected)?;
2648 : self.flush_cancellable(pgb, &self.cancel).await?;
2649 :
2650 : let mut from_cache = false;
2651 :
2652 : // Send a tarball of the latest layer on the timeline. Compress if not
2653 : // fullbackup. TODO Compress in that case too (tests need to be updated)
2654 : if full_backup {
2655 : let mut writer = pgb.copyout_writer();
2656 : basebackup::send_basebackup_tarball(
2657 : &mut writer,
2658 : &timeline,
2659 : lsn,
2660 : prev_lsn,
2661 : full_backup,
2662 : replica,
2663 : None,
2664 : &ctx,
2665 : )
2666 : .await?;
2667 : } else {
2668 : let mut writer = BufWriter::new(pgb.copyout_writer());
2669 :
2670 : let cached = timeline
2671 : .get_cached_basebackup_if_enabled(lsn, prev_lsn, full_backup, replica, gzip)
2672 : .await;
2673 :
2674 : if let Some(mut cached) = cached {
2675 : from_cache = true;
2676 : tokio::io::copy(&mut cached, &mut writer)
2677 : .await
2678 0 : .map_err(|err| {
2679 0 : BasebackupError::Client(err, "handle_basebackup_request,cached,copy")
2680 0 : })?;
2681 : } else {
2682 : basebackup::send_basebackup_tarball(
2683 : &mut writer,
2684 : &timeline,
2685 : lsn,
2686 : prev_lsn,
2687 : full_backup,
2688 : replica,
2689 : // NB: using fast compression because it's on the critical path for compute
2690 : // startup. For an empty database, we get <100KB with this method. The
2691 : // Level::Best compression method gives us <20KB, but maybe we should add
2692 : // basebackup caching on compute shutdown first.
2693 : gzip.then_some(async_compression::Level::Fastest),
2694 : &ctx,
2695 : )
2696 : .await?;
2697 : }
2698 : writer
2699 : .flush()
2700 : .await
2701 0 : .map_err(|err| BasebackupError::Client(err, "handle_basebackup_request,flush"))?;
2702 : }
2703 :
2704 : pgb.write_message_noflush(&BeMessage::CopyDone)
2705 : .map_err(QueryError::Disconnected)?;
2706 : self.flush_cancellable(pgb, &timeline.cancel).await?;
2707 :
2708 : let basebackup_after = started
2709 : .elapsed()
2710 : .checked_sub(lsn_awaited_after)
2711 : .unwrap_or(Duration::ZERO);
2712 :
2713 : info!(
2714 : lsn_await_millis = lsn_awaited_after.as_millis(),
2715 : basebackup_millis = basebackup_after.as_millis(),
2716 : %from_cache,
2717 : "basebackup complete"
2718 : );
2719 :
2720 : Ok(())
2721 : }
2722 :
2723 : // when accessing management api supply None as an argument
2724 : // when using to authorize tenant pass corresponding tenant id
2725 0 : fn check_permission(&self, tenant_id: Option<TenantId>) -> Result<(), QueryError> {
2726 0 : if self.auth.is_none() {
2727 : // auth is set to Trust, nothing to check so just return ok
2728 0 : return Ok(());
2729 0 : }
2730 : // auth is some, just checked above, when auth is some
2731 : // then claims are always present because of checks during connection init
2732 : // so this expect won't trigger
2733 0 : let claims = self
2734 0 : .claims
2735 0 : .as_ref()
2736 0 : .expect("claims presence already checked");
2737 0 : check_permission(claims, tenant_id).map_err(|e| QueryError::Unauthorized(e.0))
2738 0 : }
2739 : }
2740 :
2741 : /// `basebackup tenant timeline [lsn] [--gzip] [--replica]`
2742 : #[derive(Debug, Clone, Eq, PartialEq)]
2743 : struct BaseBackupCmd {
2744 : tenant_id: TenantId,
2745 : timeline_id: TimelineId,
2746 : lsn: Option<Lsn>,
2747 : gzip: bool,
2748 : replica: bool,
2749 : }
2750 :
2751 : /// `fullbackup tenant timeline [lsn] [prev_lsn]`
2752 : #[derive(Debug, Clone, Eq, PartialEq)]
2753 : struct FullBackupCmd {
2754 : tenant_id: TenantId,
2755 : timeline_id: TimelineId,
2756 : lsn: Option<Lsn>,
2757 : prev_lsn: Option<Lsn>,
2758 : }
2759 :
2760 : /// `pagestream_v2 tenant timeline`
2761 : #[derive(Debug, Clone, Eq, PartialEq)]
2762 : struct PageStreamCmd {
2763 : tenant_id: TenantId,
2764 : timeline_id: TimelineId,
2765 : protocol_version: PagestreamProtocolVersion,
2766 : }
2767 :
2768 : /// `lease lsn tenant timeline lsn`
2769 : #[derive(Debug, Clone, Eq, PartialEq)]
2770 : struct LeaseLsnCmd {
2771 : tenant_shard_id: TenantShardId,
2772 : timeline_id: TimelineId,
2773 : lsn: Lsn,
2774 : }
2775 :
2776 : #[derive(Debug, Clone, Eq, PartialEq)]
2777 : enum PageServiceCmd {
2778 : Set,
2779 : PageStream(PageStreamCmd),
2780 : BaseBackup(BaseBackupCmd),
2781 : FullBackup(FullBackupCmd),
2782 : LeaseLsn(LeaseLsnCmd),
2783 : }
2784 :
2785 : impl PageStreamCmd {
2786 3 : fn parse(query: &str, protocol_version: PagestreamProtocolVersion) -> anyhow::Result<Self> {
2787 3 : let parameters = query.split_whitespace().collect_vec();
2788 3 : if parameters.len() != 2 {
2789 1 : bail!(
2790 1 : "invalid number of parameters for pagestream command: {}",
2791 : query
2792 : );
2793 2 : }
2794 2 : let tenant_id = TenantId::from_str(parameters[0])
2795 2 : .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
2796 1 : let timeline_id = TimelineId::from_str(parameters[1])
2797 1 : .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
2798 1 : Ok(Self {
2799 1 : tenant_id,
2800 1 : timeline_id,
2801 1 : protocol_version,
2802 1 : })
2803 3 : }
2804 : }
2805 :
2806 : impl FullBackupCmd {
2807 2 : fn parse(query: &str) -> anyhow::Result<Self> {
2808 2 : let parameters = query.split_whitespace().collect_vec();
2809 2 : if parameters.len() < 2 || parameters.len() > 4 {
2810 0 : bail!(
2811 0 : "invalid number of parameters for basebackup command: {}",
2812 : query
2813 : );
2814 2 : }
2815 2 : let tenant_id = TenantId::from_str(parameters[0])
2816 2 : .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
2817 2 : let timeline_id = TimelineId::from_str(parameters[1])
2818 2 : .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
2819 : // The caller is responsible for providing correct lsn and prev_lsn.
2820 2 : let lsn = if let Some(lsn_str) = parameters.get(2) {
2821 : Some(
2822 1 : Lsn::from_str(lsn_str)
2823 1 : .with_context(|| format!("Failed to parse Lsn from {lsn_str}"))?,
2824 : )
2825 : } else {
2826 1 : None
2827 : };
2828 2 : let prev_lsn = if let Some(prev_lsn_str) = parameters.get(3) {
2829 : Some(
2830 1 : Lsn::from_str(prev_lsn_str)
2831 1 : .with_context(|| format!("Failed to parse Lsn from {prev_lsn_str}"))?,
2832 : )
2833 : } else {
2834 1 : None
2835 : };
2836 2 : Ok(Self {
2837 2 : tenant_id,
2838 2 : timeline_id,
2839 2 : lsn,
2840 2 : prev_lsn,
2841 2 : })
2842 2 : }
2843 : }
2844 :
2845 : impl BaseBackupCmd {
2846 9 : fn parse(query: &str) -> anyhow::Result<Self> {
2847 9 : let parameters = query.split_whitespace().collect_vec();
2848 9 : if parameters.len() < 2 {
2849 0 : bail!(
2850 0 : "invalid number of parameters for basebackup command: {}",
2851 : query
2852 : );
2853 9 : }
2854 9 : let tenant_id = TenantId::from_str(parameters[0])
2855 9 : .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
2856 9 : let timeline_id = TimelineId::from_str(parameters[1])
2857 9 : .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
2858 : let lsn;
2859 : let flags_parse_from;
2860 9 : if let Some(maybe_lsn) = parameters.get(2) {
2861 8 : if *maybe_lsn == "latest" {
2862 1 : lsn = None;
2863 1 : flags_parse_from = 3;
2864 7 : } else if maybe_lsn.starts_with("--") {
2865 5 : lsn = None;
2866 5 : flags_parse_from = 2;
2867 5 : } else {
2868 : lsn = Some(
2869 2 : Lsn::from_str(maybe_lsn)
2870 2 : .with_context(|| format!("Failed to parse lsn from {maybe_lsn}"))?,
2871 : );
2872 2 : flags_parse_from = 3;
2873 : }
2874 1 : } else {
2875 1 : lsn = None;
2876 1 : flags_parse_from = 2;
2877 1 : }
2878 :
2879 9 : let mut gzip = false;
2880 9 : let mut replica = false;
2881 :
2882 11 : for ¶m in ¶meters[flags_parse_from..] {
2883 11 : match param {
2884 11 : "--gzip" => {
2885 7 : if gzip {
2886 1 : bail!("duplicate parameter for basebackup command: {param}")
2887 6 : }
2888 6 : gzip = true
2889 : }
2890 4 : "--replica" => {
2891 2 : if replica {
2892 0 : bail!("duplicate parameter for basebackup command: {param}")
2893 2 : }
2894 2 : replica = true
2895 : }
2896 2 : _ => bail!("invalid parameter for basebackup command: {param}"),
2897 : }
2898 : }
2899 6 : Ok(Self {
2900 6 : tenant_id,
2901 6 : timeline_id,
2902 6 : lsn,
2903 6 : gzip,
2904 6 : replica,
2905 6 : })
2906 9 : }
2907 : }
2908 :
2909 : impl LeaseLsnCmd {
2910 2 : fn parse(query: &str) -> anyhow::Result<Self> {
2911 2 : let parameters = query.split_whitespace().collect_vec();
2912 2 : if parameters.len() != 3 {
2913 0 : bail!(
2914 0 : "invalid number of parameters for lease lsn command: {}",
2915 : query
2916 : );
2917 2 : }
2918 2 : let tenant_shard_id = TenantShardId::from_str(parameters[0])
2919 2 : .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
2920 2 : let timeline_id = TimelineId::from_str(parameters[1])
2921 2 : .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
2922 2 : let lsn = Lsn::from_str(parameters[2])
2923 2 : .with_context(|| format!("Failed to parse lsn from {}", parameters[2]))?;
2924 2 : Ok(Self {
2925 2 : tenant_shard_id,
2926 2 : timeline_id,
2927 2 : lsn,
2928 2 : })
2929 2 : }
2930 : }
2931 :
2932 : impl PageServiceCmd {
2933 21 : fn parse(query: &str) -> anyhow::Result<Self> {
2934 21 : let query = query.trim();
2935 21 : let Some((cmd, other)) = query.split_once(' ') else {
2936 2 : bail!("cannot parse query: {query}")
2937 : };
2938 19 : match cmd.to_ascii_lowercase().as_str() {
2939 19 : "pagestream_v2" => Ok(Self::PageStream(PageStreamCmd::parse(
2940 3 : other,
2941 3 : PagestreamProtocolVersion::V2,
2942 2 : )?)),
2943 16 : "pagestream_v3" => Ok(Self::PageStream(PageStreamCmd::parse(
2944 0 : other,
2945 0 : PagestreamProtocolVersion::V3,
2946 0 : )?)),
2947 16 : "basebackup" => Ok(Self::BaseBackup(BaseBackupCmd::parse(other)?)),
2948 7 : "fullbackup" => Ok(Self::FullBackup(FullBackupCmd::parse(other)?)),
2949 5 : "lease" => {
2950 3 : let Some((cmd2, other)) = other.split_once(' ') else {
2951 0 : bail!("invalid lease command: {cmd}");
2952 : };
2953 3 : let cmd2 = cmd2.to_ascii_lowercase();
2954 3 : if cmd2 == "lsn" {
2955 2 : Ok(Self::LeaseLsn(LeaseLsnCmd::parse(other)?))
2956 : } else {
2957 1 : bail!("invalid lease command: {cmd}");
2958 : }
2959 : }
2960 2 : "set" => Ok(Self::Set),
2961 0 : _ => Err(anyhow::anyhow!("unsupported command {cmd} in {query}")),
2962 : }
2963 21 : }
2964 : }
2965 :
2966 : /// Parse the startup options from the postgres wire protocol startup packet.
2967 : ///
2968 : /// It takes a sequence of `-c option=X` or `-coption=X`. It parses the options string
2969 : /// by best effort and returns all the options parsed (key-value pairs) and a bool indicating
2970 : /// whether all options are successfully parsed. There could be duplicates in the options
2971 : /// if the caller passed such parameters.
2972 7 : fn parse_options(options: &str) -> (Vec<(String, String)>, bool) {
2973 7 : let mut parsing_config = false;
2974 7 : let mut has_error = false;
2975 7 : let mut config = Vec::new();
2976 16 : for item in options.split_whitespace() {
2977 16 : if item == "-c" {
2978 9 : if !parsing_config {
2979 8 : parsing_config = true;
2980 8 : } else {
2981 : // "-c" followed with another "-c"
2982 1 : tracing::warn!("failed to parse the startup options: {options}");
2983 1 : has_error = true;
2984 1 : break;
2985 : }
2986 7 : } else if item.starts_with("-c") || parsing_config {
2987 7 : let Some((mut key, value)) = item.split_once('=') else {
2988 : // "-c" followed with an invalid option
2989 1 : tracing::warn!("failed to parse the startup options: {options}");
2990 1 : has_error = true;
2991 1 : break;
2992 : };
2993 6 : if !parsing_config {
2994 : // Parse "-coptions=X"
2995 1 : let Some(stripped_key) = key.strip_prefix("-c") else {
2996 0 : tracing::warn!("failed to parse the startup options: {options}");
2997 0 : has_error = true;
2998 0 : break;
2999 : };
3000 1 : key = stripped_key;
3001 5 : }
3002 6 : config.push((key.to_string(), value.to_string()));
3003 6 : parsing_config = false;
3004 : } else {
3005 0 : tracing::warn!("failed to parse the startup options: {options}");
3006 0 : has_error = true;
3007 0 : break;
3008 : }
3009 : }
3010 7 : if parsing_config {
3011 : // "-c" without the option
3012 3 : tracing::warn!("failed to parse the startup options: {options}");
3013 3 : has_error = true;
3014 4 : }
3015 7 : (config, has_error)
3016 7 : }
3017 :
3018 : impl<IO> postgres_backend::Handler<IO> for PageServerHandler
3019 : where
3020 : IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
3021 : {
3022 0 : fn check_auth_jwt(
3023 0 : &mut self,
3024 0 : _pgb: &mut PostgresBackend<IO>,
3025 0 : jwt_response: &[u8],
3026 0 : ) -> Result<(), QueryError> {
3027 : // this unwrap is never triggered, because check_auth_jwt only called when auth_type is NeonJWT
3028 : // which requires auth to be present
3029 0 : let data: TokenData<Claims> = self
3030 0 : .auth
3031 0 : .as_ref()
3032 0 : .unwrap()
3033 0 : .decode(str::from_utf8(jwt_response).context("jwt response is not UTF-8")?)
3034 0 : .map_err(|e| QueryError::Unauthorized(e.0))?;
3035 :
3036 0 : if matches!(data.claims.scope, Scope::Tenant) && data.claims.tenant_id.is_none() {
3037 0 : return Err(QueryError::Unauthorized(
3038 0 : "jwt token scope is Tenant, but tenant id is missing".into(),
3039 0 : ));
3040 0 : }
3041 :
3042 0 : debug!(
3043 0 : "jwt scope check succeeded for scope: {:#?} by tenant id: {:?}",
3044 : data.claims.scope, data.claims.tenant_id,
3045 : );
3046 :
3047 0 : self.claims = Some(data.claims);
3048 0 : Ok(())
3049 0 : }
3050 :
3051 0 : fn startup(
3052 0 : &mut self,
3053 0 : _pgb: &mut PostgresBackend<IO>,
3054 0 : sm: &FeStartupPacket,
3055 0 : ) -> Result<(), QueryError> {
3056 0 : fail::fail_point!("ps::connection-start::startup-packet");
3057 :
3058 0 : if let FeStartupPacket::StartupMessage { params, .. } = sm {
3059 0 : if let Some(app_name) = params.get("application_name") {
3060 0 : self.perf_span_fields.application_name = Some(app_name.to_string());
3061 0 : Span::current().record("application_name", field::display(app_name));
3062 0 : }
3063 0 : if let Some(options) = params.get("options") {
3064 0 : let (config, _) = parse_options(options);
3065 0 : for (key, value) in config {
3066 0 : if key == "neon.compute_mode" {
3067 0 : self.perf_span_fields.compute_mode = Some(value.clone());
3068 0 : Span::current().record("compute_mode", field::display(value));
3069 0 : }
3070 : }
3071 0 : }
3072 0 : };
3073 :
3074 0 : Ok(())
3075 0 : }
3076 :
3077 : #[instrument(skip_all, fields(tenant_id, timeline_id))]
3078 : async fn process_query(
3079 : &mut self,
3080 : pgb: &mut PostgresBackend<IO>,
3081 : query_string: &str,
3082 : ) -> Result<(), QueryError> {
3083 0 : fail::fail_point!("simulated-bad-compute-connection", |_| {
3084 0 : info!("Hit failpoint for bad connection");
3085 0 : Err(QueryError::SimulatedConnectionError)
3086 0 : });
3087 :
3088 : fail::fail_point!("ps::connection-start::process-query");
3089 :
3090 : let ctx = self.connection_ctx.attached_child();
3091 : debug!("process query {query_string}");
3092 : let query = PageServiceCmd::parse(query_string)?;
3093 : match query {
3094 : PageServiceCmd::PageStream(PageStreamCmd {
3095 : tenant_id,
3096 : timeline_id,
3097 : protocol_version,
3098 : }) => {
3099 : tracing::Span::current()
3100 : .record("tenant_id", field::display(tenant_id))
3101 : .record("timeline_id", field::display(timeline_id));
3102 :
3103 : self.check_permission(Some(tenant_id))?;
3104 : let command_kind = match protocol_version {
3105 : PagestreamProtocolVersion::V2 => ComputeCommandKind::PageStreamV2,
3106 : PagestreamProtocolVersion::V3 => ComputeCommandKind::PageStreamV3,
3107 : };
3108 : COMPUTE_COMMANDS_COUNTERS.for_command(command_kind).inc();
3109 :
3110 : self.handle_pagerequests(pgb, tenant_id, timeline_id, protocol_version, ctx)
3111 : .await?;
3112 : }
3113 : PageServiceCmd::BaseBackup(BaseBackupCmd {
3114 : tenant_id,
3115 : timeline_id,
3116 : lsn,
3117 : gzip,
3118 : replica,
3119 : }) => {
3120 : tracing::Span::current()
3121 : .record("tenant_id", field::display(tenant_id))
3122 : .record("timeline_id", field::display(timeline_id));
3123 :
3124 : self.check_permission(Some(tenant_id))?;
3125 :
3126 : COMPUTE_COMMANDS_COUNTERS
3127 : .for_command(ComputeCommandKind::Basebackup)
3128 : .inc();
3129 : let metric_recording = metrics::BASEBACKUP_QUERY_TIME.start_recording();
3130 0 : let res = async {
3131 0 : self.handle_basebackup_request(
3132 0 : pgb,
3133 0 : tenant_id,
3134 0 : timeline_id,
3135 0 : lsn,
3136 0 : None,
3137 0 : false,
3138 0 : gzip,
3139 0 : replica,
3140 0 : &ctx,
3141 0 : )
3142 0 : .await?;
3143 0 : pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
3144 0 : Result::<(), QueryError>::Ok(())
3145 0 : }
3146 : .await;
3147 : metric_recording.observe(&res);
3148 : res?;
3149 : }
3150 : // same as basebackup, but result includes relational data as well
3151 : PageServiceCmd::FullBackup(FullBackupCmd {
3152 : tenant_id,
3153 : timeline_id,
3154 : lsn,
3155 : prev_lsn,
3156 : }) => {
3157 : tracing::Span::current()
3158 : .record("tenant_id", field::display(tenant_id))
3159 : .record("timeline_id", field::display(timeline_id));
3160 :
3161 : self.check_permission(Some(tenant_id))?;
3162 :
3163 : COMPUTE_COMMANDS_COUNTERS
3164 : .for_command(ComputeCommandKind::Fullbackup)
3165 : .inc();
3166 :
3167 : // Check that the timeline exists
3168 : self.handle_basebackup_request(
3169 : pgb,
3170 : tenant_id,
3171 : timeline_id,
3172 : lsn,
3173 : prev_lsn,
3174 : true,
3175 : false,
3176 : false,
3177 : &ctx,
3178 : )
3179 : .await?;
3180 : pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
3181 : }
3182 : PageServiceCmd::Set => {
3183 : // important because psycopg2 executes "SET datestyle TO 'ISO'"
3184 : // on connect
3185 : // TODO: allow setting options, i.e., application_name/compute_mode via SET commands
3186 : pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
3187 : }
3188 : PageServiceCmd::LeaseLsn(LeaseLsnCmd {
3189 : tenant_shard_id,
3190 : timeline_id,
3191 : lsn,
3192 : }) => {
3193 : tracing::Span::current()
3194 : .record("tenant_id", field::display(tenant_shard_id))
3195 : .record("timeline_id", field::display(timeline_id));
3196 :
3197 : self.check_permission(Some(tenant_shard_id.tenant_id))?;
3198 :
3199 : COMPUTE_COMMANDS_COUNTERS
3200 : .for_command(ComputeCommandKind::LeaseLsn)
3201 : .inc();
3202 :
3203 : match self
3204 : .handle_make_lsn_lease(pgb, tenant_shard_id, timeline_id, lsn, &ctx)
3205 : .await
3206 : {
3207 : Ok(()) => {
3208 : pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?
3209 : }
3210 : Err(e) => {
3211 : error!("error obtaining lsn lease for {lsn}: {e:?}");
3212 : pgb.write_message_noflush(&BeMessage::ErrorResponse(
3213 : &e.to_string(),
3214 : Some(e.pg_error_code()),
3215 : ))?
3216 : }
3217 : };
3218 : }
3219 : }
3220 :
3221 : Ok(())
3222 : }
3223 : }
3224 :
3225 : /// Serves the page service over gRPC. Dispatches to PageServerHandler for request processing.
3226 : ///
3227 : /// TODO: rename to PageServiceHandler when libpq impl is removed.
3228 : pub struct GrpcPageServiceHandler {
3229 : tenant_manager: Arc<TenantManager>,
3230 : ctx: RequestContext,
3231 :
3232 : /// Cancelled to shut down the server. Tonic will shut down in response to this, but wait for
3233 : /// in-flight requests to complete. Any tasks we spawn ourselves must respect this token.
3234 : cancel: CancellationToken,
3235 :
3236 : /// Any tasks we spawn ourselves should clone this gate guard, so that we can wait for them to
3237 : /// complete during shutdown. Request handlers implicitly hold this guard already.
3238 : gate_guard: GateGuard,
3239 :
3240 : /// `get_vectored` concurrency setting.
3241 : get_vectored_concurrent_io: GetVectoredConcurrentIo,
3242 : }
3243 :
3244 : impl GrpcPageServiceHandler {
3245 : /// Spawns a gRPC server for the page service.
3246 : ///
3247 : /// Returns a `CancellableTask` handle that can be used to shut down the server. It waits for
3248 : /// any in-flight requests and tasks to complete first.
3249 : ///
3250 : /// TODO: this doesn't support TLS. We need TLS reloading via ReloadingCertificateResolver, so we
3251 : /// need to reimplement the TCP+TLS accept loop ourselves.
3252 0 : pub fn spawn(
3253 0 : tenant_manager: Arc<TenantManager>,
3254 0 : auth: Option<Arc<SwappableJwtAuth>>,
3255 0 : perf_trace_dispatch: Option<Dispatch>,
3256 0 : get_vectored_concurrent_io: GetVectoredConcurrentIo,
3257 0 : listener: std::net::TcpListener,
3258 0 : ) -> anyhow::Result<CancellableTask> {
3259 : // Set up a cancellation token for shutting down the server, and a gate to wait for all
3260 : // requests and spawned tasks to complete.
3261 0 : let cancel = CancellationToken::new();
3262 0 : let gate = Gate::default();
3263 :
3264 0 : let ctx = RequestContextBuilder::new(TaskKind::PageRequestHandler)
3265 0 : .download_behavior(DownloadBehavior::Download)
3266 0 : .perf_span_dispatch(perf_trace_dispatch)
3267 0 : .detached_child();
3268 :
3269 : // Set up the TCP socket. We take a preconfigured TcpListener to bind the
3270 : // port early during startup.
3271 0 : let incoming = {
3272 0 : let _runtime = COMPUTE_REQUEST_RUNTIME.enter(); // required by TcpListener::from_std
3273 0 : listener.set_nonblocking(true)?;
3274 0 : tonic::transport::server::TcpIncoming::from(tokio::net::TcpListener::from_std(
3275 0 : listener,
3276 0 : )?)
3277 0 : .with_nodelay(Some(GRPC_TCP_NODELAY))
3278 0 : .with_keepalive(Some(GRPC_TCP_KEEPALIVE_TIME))
3279 : };
3280 :
3281 : // Set up the gRPC server.
3282 : //
3283 : // TODO: consider tuning window sizes.
3284 0 : let mut server = tonic::transport::Server::builder()
3285 0 : .http2_keepalive_interval(Some(GRPC_HTTP2_KEEPALIVE_INTERVAL))
3286 0 : .http2_keepalive_timeout(Some(GRPC_HTTP2_KEEPALIVE_TIMEOUT))
3287 0 : .max_concurrent_streams(Some(GRPC_MAX_CONCURRENT_STREAMS));
3288 :
3289 : // Main page service stack. Uses a mix of Tonic interceptors and Tower layers:
3290 : //
3291 : // * Interceptors: can inspect and modify the gRPC request. Sync code only, runs before service.
3292 : //
3293 : // * Layers: allow async code, can run code after the service response. However, only has access
3294 : // to the raw HTTP request/response, not the gRPC types.
3295 0 : let page_service_handler = GrpcPageServiceHandler {
3296 0 : tenant_manager,
3297 0 : ctx,
3298 0 : cancel: cancel.clone(),
3299 0 : gate_guard: gate.enter().expect("gate was just created"),
3300 0 : get_vectored_concurrent_io,
3301 0 : };
3302 :
3303 0 : let observability_layer = ObservabilityLayer;
3304 0 : let mut tenant_interceptor = TenantMetadataInterceptor;
3305 0 : let mut auth_interceptor = TenantAuthInterceptor::new(auth);
3306 :
3307 0 : let page_service = tower::ServiceBuilder::new()
3308 : // Create tracing span and record request start time.
3309 0 : .layer(observability_layer)
3310 : // Intercept gRPC requests.
3311 0 : .layer(tonic::service::InterceptorLayer::new(move |mut req| {
3312 : // Extract tenant metadata.
3313 0 : req = tenant_interceptor.call(req)?;
3314 : // Authenticate tenant JWT token.
3315 0 : req = auth_interceptor.call(req)?;
3316 0 : Ok(req)
3317 0 : }))
3318 : // Run the page service.
3319 0 : .service(
3320 0 : proto::PageServiceServer::new(page_service_handler)
3321 : // Support both gzip and zstd compression. The client decides what to use.
3322 0 : .accept_compressed(tonic::codec::CompressionEncoding::Gzip)
3323 0 : .accept_compressed(tonic::codec::CompressionEncoding::Zstd)
3324 0 : .send_compressed(tonic::codec::CompressionEncoding::Gzip)
3325 0 : .send_compressed(tonic::codec::CompressionEncoding::Zstd),
3326 : );
3327 0 : let server = server.add_service(page_service);
3328 :
3329 : // Reflection service for use with e.g. grpcurl.
3330 0 : let reflection_service = tonic_reflection::server::Builder::configure()
3331 0 : .register_encoded_file_descriptor_set(proto::FILE_DESCRIPTOR_SET)
3332 0 : .build_v1()?;
3333 0 : let server = server.add_service(reflection_service);
3334 :
3335 : // Spawn server task. It runs until the cancellation token fires and in-flight requests and
3336 : // tasks complete. The `CancellableTask` will wait for the task's join handle, which
3337 : // implicitly waits for the gate to close.
3338 0 : let task_cancel = cancel.clone();
3339 0 : let task = COMPUTE_REQUEST_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
3340 : "grpc pageservice listener",
3341 0 : async move {
3342 0 : server
3343 0 : .serve_with_incoming_shutdown(incoming, task_cancel.cancelled())
3344 0 : .await?;
3345 : // Server exited cleanly. All requests should have completed by now. Wait for any
3346 : // spawned tasks to complete as well (e.g. IoConcurrency sidecars) via the gate.
3347 0 : gate.close().await;
3348 0 : anyhow::Ok(())
3349 0 : },
3350 : ));
3351 :
3352 0 : Ok(CancellableTask { task, cancel })
3353 0 : }
3354 :
3355 : /// Errors if the request is executed on a non-zero shard. Only shard 0 has a complete view of
3356 : /// relations and their sizes, as well as SLRU segments and similar data.
3357 : #[allow(clippy::result_large_err)]
3358 0 : fn ensure_shard_zero(timeline: &Handle<TenantManagerTypes>) -> Result<(), tonic::Status> {
3359 0 : match timeline.get_shard_index().shard_number.0 {
3360 0 : 0 => Ok(()),
3361 0 : shard => Err(tonic::Status::invalid_argument(format!(
3362 0 : "request must execute on shard zero (is shard {shard})",
3363 0 : ))),
3364 : }
3365 0 : }
3366 :
3367 : /// Generates a PagestreamRequest header from a ReadLsn and request ID.
3368 0 : fn make_hdr(
3369 0 : read_lsn: page_api::ReadLsn,
3370 0 : req_id: Option<page_api::RequestID>,
3371 0 : ) -> PagestreamRequest {
3372 : PagestreamRequest {
3373 0 : reqid: req_id.map(|r| r.id).unwrap_or_default(),
3374 0 : request_lsn: read_lsn.request_lsn,
3375 0 : not_modified_since: read_lsn
3376 0 : .not_modified_since_lsn
3377 0 : .unwrap_or(read_lsn.request_lsn),
3378 : }
3379 0 : }
3380 :
3381 : /// Acquires a timeline handle for the given request.
3382 : ///
3383 : /// TODO: during shard splits, the compute may still be sending requests to the parent shard
3384 : /// until the entire split is committed and the compute is notified. Consider installing a
3385 : /// temporary shard router from the parent to the children while the split is in progress.
3386 : ///
3387 : /// TODO: consider moving this to a middleware layer; all requests need it. Needs to manage
3388 : /// the TimelineHandles lifecycle.
3389 : ///
3390 : /// TODO: untangle acquisition from TenantManagerWrapper::resolve() and Cache::get(), to avoid
3391 : /// the unnecessary overhead.
3392 0 : async fn get_request_timeline(
3393 0 : &self,
3394 0 : req: &tonic::Request<impl Any>,
3395 0 : ) -> Result<Handle<TenantManagerTypes>, GetActiveTimelineError> {
3396 0 : let ttid = *extract::<TenantTimelineId>(req);
3397 0 : let shard_index = *extract::<ShardIndex>(req);
3398 0 : let shard_selector = ShardSelector::Known(shard_index);
3399 :
3400 0 : TimelineHandles::new(self.tenant_manager.clone())
3401 0 : .get(ttid.tenant_id, ttid.timeline_id, shard_selector)
3402 0 : .await
3403 0 : }
3404 :
3405 : /// Starts a SmgrOpTimer at received_at, throttles the request, and records execution start.
3406 : /// Only errors if the timeline is shutting down.
3407 : ///
3408 : /// TODO: move timer construction to ObservabilityLayer (see TODO there).
3409 : /// TODO: decouple rate limiting (middleware?), and return SlowDown errors instead.
3410 0 : async fn record_op_start_and_throttle(
3411 0 : timeline: &Handle<TenantManagerTypes>,
3412 0 : op: metrics::SmgrQueryType,
3413 0 : received_at: Instant,
3414 0 : ) -> Result<SmgrOpTimer, tonic::Status> {
3415 0 : let mut timer = PageServerHandler::record_op_start_and_throttle(timeline, op, received_at)
3416 0 : .await
3417 0 : .map_err(|err| match err {
3418 : // record_op_start_and_throttle() only returns Shutdown.
3419 0 : QueryError::Shutdown => tonic::Status::unavailable(format!("{err}")),
3420 0 : err => tonic::Status::internal(format!("unexpected error: {err}")),
3421 0 : })?;
3422 0 : timer.observe_execution_start(Instant::now());
3423 0 : Ok(timer)
3424 0 : }
3425 :
3426 : /// Processes a GetPage batch request, via the GetPages bidirectional streaming RPC.
3427 : ///
3428 : /// NB: errors returned from here are intercepted in get_pages(), and may be converted to a
3429 : /// GetPageResponse with an appropriate status code to avoid terminating the stream.
3430 : ///
3431 : /// TODO: verify that the requested pages belong to this shard.
3432 : ///
3433 : /// TODO: get_vectored() currently enforces a batch limit of 32. Postgres will typically send
3434 : /// batches up to effective_io_concurrency = 100. Either we have to accept large batches, or
3435 : /// split them up in the client or server.
3436 : #[instrument(skip_all, fields(req_id, rel, blkno, blks, req_lsn, mod_lsn))]
3437 : async fn get_page(
3438 : ctx: &RequestContext,
3439 : timeline: &WeakHandle<TenantManagerTypes>,
3440 : req: proto::GetPageRequest,
3441 : io_concurrency: IoConcurrency,
3442 : ) -> Result<proto::GetPageResponse, tonic::Status> {
3443 : let received_at = Instant::now();
3444 : let timeline = timeline.upgrade()?;
3445 : let ctx = ctx.with_scope_page_service_pagestream(&timeline);
3446 :
3447 : // Validate the request, decorate the span, and convert it to a Pagestream request.
3448 : let req = page_api::GetPageRequest::try_from(req)?;
3449 :
3450 : span_record!(
3451 : req_id = %req.request_id,
3452 : rel = %req.rel,
3453 : blkno = %req.block_numbers[0],
3454 : blks = %req.block_numbers.len(),
3455 : lsn = %req.read_lsn,
3456 : );
3457 :
3458 : let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn(); // hold guard
3459 : let effective_lsn = PageServerHandler::effective_request_lsn(
3460 : &timeline,
3461 : timeline.get_last_record_lsn(),
3462 : req.read_lsn.request_lsn,
3463 : req.read_lsn
3464 : .not_modified_since_lsn
3465 : .unwrap_or(req.read_lsn.request_lsn),
3466 : &latest_gc_cutoff_lsn,
3467 : )?;
3468 :
3469 : let mut batch = SmallVec::with_capacity(req.block_numbers.len());
3470 : for blkno in req.block_numbers {
3471 : // TODO: this creates one timer per page and throttles it. We should have a timer for
3472 : // the entire batch, and throttle only the batch, but this is equivalent to what
3473 : // PageServerHandler does already so we keep it for now.
3474 : let timer = Self::record_op_start_and_throttle(
3475 : &timeline,
3476 : metrics::SmgrQueryType::GetPageAtLsn,
3477 : received_at,
3478 : )
3479 : .await?;
3480 :
3481 : batch.push(BatchedGetPageRequest {
3482 : req: PagestreamGetPageRequest {
3483 : hdr: Self::make_hdr(req.read_lsn, Some(req.request_id)),
3484 : rel: req.rel,
3485 : blkno,
3486 : },
3487 : lsn_range: LsnRange {
3488 : effective_lsn,
3489 : request_lsn: req.read_lsn.request_lsn,
3490 : },
3491 : timer,
3492 : ctx: ctx.attached_child(),
3493 : batch_wait_ctx: None, // TODO: add tracing
3494 : });
3495 : }
3496 :
3497 : // TODO: this does a relation size query for every page in the batch. Since this batch is
3498 : // all for one relation, we could do this only once. However, this is not the case for the
3499 : // libpq implementation.
3500 : let results = PageServerHandler::handle_get_page_at_lsn_request_batched(
3501 : &timeline,
3502 : batch,
3503 : io_concurrency,
3504 : GetPageBatchBreakReason::BatchFull, // TODO: not relevant for gRPC batches
3505 : &ctx,
3506 : )
3507 : .await;
3508 :
3509 : let mut resp = page_api::GetPageResponse {
3510 : request_id: req.request_id,
3511 : status_code: page_api::GetPageStatusCode::Ok,
3512 : reason: None,
3513 : rel: req.rel,
3514 : pages: Vec::with_capacity(results.len()),
3515 : };
3516 :
3517 : for result in results {
3518 : match result {
3519 : Ok((PagestreamBeMessage::GetPage(r), _, _)) => resp.pages.push(page_api::Page {
3520 : block_number: r.req.blkno,
3521 : image: r.page,
3522 : }),
3523 : Ok((resp, _, _)) => {
3524 : return Err(tonic::Status::internal(format!(
3525 : "unexpected response: {resp:?}"
3526 : )));
3527 : }
3528 : Err(err) => return Err(err.err.into()),
3529 : };
3530 : }
3531 :
3532 : Ok(resp.into())
3533 : }
3534 : }
3535 :
3536 : /// Implements the gRPC page service.
3537 : ///
3538 : /// On client disconnect (e.g. timeout or client shutdown), Tonic will drop the request handler
3539 : /// futures, so the read path must be cancellation-safe. On server shutdown, Tonic will wait for
3540 : /// in-flight requests to complete.
3541 : ///
3542 : /// TODO: when the libpq impl is removed, remove the Pagestream types and inline the handler code.
3543 : #[tonic::async_trait]
3544 : impl proto::PageService for GrpcPageServiceHandler {
3545 : type GetBaseBackupStream = Pin<
3546 : Box<dyn Stream<Item = Result<proto::GetBaseBackupResponseChunk, tonic::Status>> + Send>,
3547 : >;
3548 :
3549 : type GetPagesStream =
3550 : Pin<Box<dyn Stream<Item = Result<proto::GetPageResponse, tonic::Status>> + Send>>;
3551 :
3552 : #[instrument(skip_all, fields(lsn))]
3553 : async fn get_base_backup(
3554 : &self,
3555 : req: tonic::Request<proto::GetBaseBackupRequest>,
3556 0 : ) -> Result<tonic::Response<Self::GetBaseBackupStream>, tonic::Status> {
3557 : // Send chunks of 256 KB to avoid large memory allocations. pagebench basebackup shows this
3558 : // to be the sweet spot where throughput is saturated.
3559 : const CHUNK_SIZE: usize = 256 * 1024;
3560 :
3561 0 : let timeline = self.get_request_timeline(&req).await?;
3562 0 : let ctx = self.ctx.with_scope_timeline(&timeline);
3563 :
3564 : // Validate the request and decorate the span.
3565 0 : Self::ensure_shard_zero(&timeline)?;
3566 0 : if timeline.is_archived() == Some(true) {
3567 0 : return Err(tonic::Status::failed_precondition("timeline is archived"));
3568 0 : }
3569 0 : let req: page_api::GetBaseBackupRequest = req.into_inner().try_into()?;
3570 :
3571 0 : span_record!(lsn=?req.lsn);
3572 :
3573 : // Wait for the LSN to arrive, if given.
3574 0 : if let Some(lsn) = req.lsn {
3575 0 : let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
3576 0 : timeline
3577 0 : .wait_lsn(
3578 0 : lsn,
3579 0 : WaitLsnWaiter::PageService,
3580 0 : WaitLsnTimeout::Default,
3581 0 : &ctx,
3582 0 : )
3583 0 : .await?;
3584 0 : timeline
3585 0 : .check_lsn_is_in_scope(lsn, &latest_gc_cutoff_lsn)
3586 0 : .map_err(|err| {
3587 0 : tonic::Status::invalid_argument(format!("invalid basebackup LSN: {err}"))
3588 0 : })?;
3589 0 : }
3590 :
3591 : // Spawn a task to run the basebackup.
3592 0 : let span = Span::current();
3593 0 : let gate_guard = self
3594 0 : .gate_guard
3595 0 : .try_clone()
3596 0 : .map_err(|_| tonic::Status::unavailable("shutting down"))?;
3597 0 : let (mut simplex_read, mut simplex_write) = tokio::io::simplex(CHUNK_SIZE);
3598 0 : let jh = tokio::spawn(async move {
3599 0 : let _gate_guard = gate_guard; // keep gate open until task completes
3600 :
3601 0 : let gzip_level = match req.compression {
3602 0 : page_api::BaseBackupCompression::None => None,
3603 : // NB: using fast compression because it's on the critical path for compute
3604 : // startup. For an empty database, we get <100KB with this method. The
3605 : // Level::Best compression method gives us <20KB, but maybe we should add
3606 : // basebackup caching on compute shutdown first.
3607 0 : page_api::BaseBackupCompression::Gzip => Some(async_compression::Level::Fastest),
3608 : };
3609 :
3610 : // Check for a cached basebackup.
3611 0 : let cached = timeline
3612 0 : .get_cached_basebackup_if_enabled(
3613 0 : req.lsn,
3614 0 : None,
3615 0 : req.full,
3616 0 : req.replica,
3617 0 : gzip_level.is_some(),
3618 0 : )
3619 0 : .await;
3620 :
3621 0 : let result = if let Some(mut cached) = cached {
3622 : // If we have a cached basebackup, send it.
3623 0 : tokio::io::copy(&mut cached, &mut simplex_write)
3624 0 : .await
3625 0 : .map(|_| ())
3626 0 : .map_err(|err| BasebackupError::Client(err, "cached,copy"))
3627 : } else {
3628 0 : basebackup::send_basebackup_tarball(
3629 0 : &mut simplex_write,
3630 0 : &timeline,
3631 0 : req.lsn,
3632 0 : None,
3633 0 : req.full,
3634 0 : req.replica,
3635 0 : gzip_level,
3636 0 : &ctx,
3637 0 : )
3638 0 : .instrument(span) // propagate request span
3639 0 : .await
3640 : };
3641 0 : simplex_write
3642 0 : .shutdown()
3643 0 : .await
3644 0 : .map_err(|err| BasebackupError::Client(err, "simplex_write"))?;
3645 0 : result
3646 0 : });
3647 :
3648 : // Emit chunks of size CHUNK_SIZE.
3649 0 : let chunks = async_stream::try_stream! {
3650 : loop {
3651 : let mut chunk = BytesMut::with_capacity(CHUNK_SIZE).limit(CHUNK_SIZE);
3652 : loop {
3653 0 : let n = simplex_read.read_buf(&mut chunk).await.map_err(|err| {
3654 0 : tonic::Status::internal(format!("failed to read basebackup chunk: {err}"))
3655 0 : })?;
3656 : if n == 0 {
3657 : break; // full chunk or closed stream
3658 : }
3659 : }
3660 : let chunk = chunk.into_inner().freeze();
3661 : if chunk.is_empty() {
3662 : break;
3663 : }
3664 : yield proto::GetBaseBackupResponseChunk::from(chunk);
3665 : }
3666 : // Wait for the basebackup task to exit and check for errors.
3667 0 : jh.await.map_err(|err| {
3668 0 : tonic::Status::internal(format!("basebackup failed: {err}"))
3669 0 : })??;
3670 : };
3671 :
3672 0 : Ok(tonic::Response::new(Box::pin(chunks)))
3673 0 : }
3674 :
3675 : #[instrument(skip_all, fields(db_oid, lsn))]
3676 : async fn get_db_size(
3677 : &self,
3678 : req: tonic::Request<proto::GetDbSizeRequest>,
3679 0 : ) -> Result<tonic::Response<proto::GetDbSizeResponse>, tonic::Status> {
3680 0 : let received_at = extract::<ReceivedAt>(&req).0;
3681 0 : let timeline = self.get_request_timeline(&req).await?;
3682 0 : let ctx = self.ctx.with_scope_page_service_pagestream(&timeline);
3683 :
3684 : // Validate the request, decorate the span, and convert it to a Pagestream request.
3685 0 : Self::ensure_shard_zero(&timeline)?;
3686 0 : let req: page_api::GetDbSizeRequest = req.into_inner().try_into()?;
3687 :
3688 0 : span_record!(db_oid=%req.db_oid, lsn=%req.read_lsn);
3689 :
3690 0 : let req = PagestreamDbSizeRequest {
3691 0 : hdr: Self::make_hdr(req.read_lsn, None),
3692 0 : dbnode: req.db_oid,
3693 0 : };
3694 :
3695 : // Execute the request and convert the response.
3696 0 : let _timer = Self::record_op_start_and_throttle(
3697 0 : &timeline,
3698 0 : metrics::SmgrQueryType::GetDbSize,
3699 0 : received_at,
3700 0 : )
3701 0 : .await?;
3702 :
3703 0 : let resp = PageServerHandler::handle_db_size_request(&timeline, &req, &ctx).await?;
3704 0 : let resp = resp.db_size as page_api::GetDbSizeResponse;
3705 0 : Ok(tonic::Response::new(resp.into()))
3706 0 : }
3707 :
3708 : // NB: don't instrument this, instrument each streamed request.
3709 0 : async fn get_pages(
3710 : &self,
3711 : req: tonic::Request<tonic::Streaming<proto::GetPageRequest>>,
3712 0 : ) -> Result<tonic::Response<Self::GetPagesStream>, tonic::Status> {
3713 : // Extract the timeline from the request and check that it exists.
3714 0 : let ttid = *extract::<TenantTimelineId>(&req);
3715 0 : let shard_index = *extract::<ShardIndex>(&req);
3716 0 : let shard_selector = ShardSelector::Known(shard_index);
3717 :
3718 0 : let mut handles = TimelineHandles::new(self.tenant_manager.clone());
3719 0 : handles
3720 0 : .get(ttid.tenant_id, ttid.timeline_id, shard_selector)
3721 0 : .await?;
3722 :
3723 : // Spawn an IoConcurrency sidecar, if enabled.
3724 0 : let gate_guard = self
3725 0 : .gate_guard
3726 0 : .try_clone()
3727 0 : .map_err(|_| tonic::Status::unavailable("shutting down"))?;
3728 0 : let io_concurrency =
3729 0 : IoConcurrency::spawn_from_conf(self.get_vectored_concurrent_io, gate_guard);
3730 :
3731 : // Construct the GetPageRequest stream handler.
3732 0 : let span = Span::current();
3733 0 : let ctx = self.ctx.attached_child();
3734 0 : let cancel = self.cancel.clone();
3735 0 : let mut reqs = req.into_inner();
3736 :
3737 0 : let resps = async_stream::try_stream! {
3738 : let timeline = handles
3739 : .get(ttid.tenant_id, ttid.timeline_id, shard_selector)
3740 : .await?
3741 : .downgrade();
3742 : loop {
3743 : // NB: Tonic considers the entire stream to be an in-flight request and will wait
3744 : // for it to complete before shutting down. React to cancellation between requests.
3745 : let req = tokio::select! {
3746 : biased;
3747 : _ = cancel.cancelled() => Err(tonic::Status::unavailable("shutting down")),
3748 :
3749 : result = reqs.message() => match result {
3750 : Ok(Some(req)) => Ok(req),
3751 : Ok(None) => break, // client closed the stream
3752 : Err(err) => Err(err),
3753 : },
3754 : }?;
3755 : let req_id = req.request_id.map(page_api::RequestID::from).unwrap_or_default();
3756 : let result = Self::get_page(&ctx, &timeline, req, io_concurrency.clone())
3757 : .instrument(span.clone()) // propagate request span
3758 : .await;
3759 : yield match result {
3760 : Ok(resp) => resp,
3761 : // Convert per-request errors to GetPageResponses as appropriate, or terminate
3762 : // the stream with a tonic::Status. Log the error regardless, since
3763 : // ObservabilityLayer can't automatically log stream errors.
3764 : Err(status) => {
3765 : // TODO: it would be nice if we could propagate the get_page() fields here.
3766 0 : span.in_scope(|| {
3767 0 : warn!("request failed with {:?}: {}", status.code(), status.message());
3768 0 : });
3769 : page_api::GetPageResponse::try_from_status(status, req_id)?.into()
3770 : }
3771 : }
3772 : }
3773 : };
3774 :
3775 0 : Ok(tonic::Response::new(Box::pin(resps)))
3776 0 : }
3777 :
3778 : #[instrument(skip_all, fields(rel, lsn, allow_missing))]
3779 : async fn get_rel_size(
3780 : &self,
3781 : req: tonic::Request<proto::GetRelSizeRequest>,
3782 0 : ) -> Result<tonic::Response<proto::GetRelSizeResponse>, tonic::Status> {
3783 0 : let received_at = extract::<ReceivedAt>(&req).0;
3784 0 : let timeline = self.get_request_timeline(&req).await?;
3785 0 : let ctx = self.ctx.with_scope_page_service_pagestream(&timeline);
3786 :
3787 : // Validate the request, decorate the span, and convert it to a Pagestream request.
3788 0 : Self::ensure_shard_zero(&timeline)?;
3789 0 : let req: page_api::GetRelSizeRequest = req.into_inner().try_into()?;
3790 0 : let allow_missing = req.allow_missing;
3791 :
3792 0 : span_record!(rel=%req.rel, lsn=%req.read_lsn, allow_missing=%req.allow_missing);
3793 :
3794 0 : let req = PagestreamNblocksRequest {
3795 0 : hdr: Self::make_hdr(req.read_lsn, None),
3796 0 : rel: req.rel,
3797 0 : };
3798 :
3799 : // Execute the request and convert the response.
3800 0 : let _timer = Self::record_op_start_and_throttle(
3801 0 : &timeline,
3802 0 : metrics::SmgrQueryType::GetRelSize,
3803 0 : received_at,
3804 0 : )
3805 0 : .await?;
3806 :
3807 0 : let resp =
3808 0 : PageServerHandler::handle_get_nblocks_request(&timeline, &req, allow_missing, &ctx)
3809 0 : .await?;
3810 0 : let resp: page_api::GetRelSizeResponse = resp.map(|resp| resp.n_blocks);
3811 :
3812 0 : Ok(tonic::Response::new(resp.into()))
3813 0 : }
3814 :
3815 : #[instrument(skip_all, fields(kind, segno, lsn))]
3816 : async fn get_slru_segment(
3817 : &self,
3818 : req: tonic::Request<proto::GetSlruSegmentRequest>,
3819 0 : ) -> Result<tonic::Response<proto::GetSlruSegmentResponse>, tonic::Status> {
3820 0 : let received_at = extract::<ReceivedAt>(&req).0;
3821 0 : let timeline = self.get_request_timeline(&req).await?;
3822 0 : let ctx = self.ctx.with_scope_page_service_pagestream(&timeline);
3823 :
3824 : // Validate the request, decorate the span, and convert it to a Pagestream request.
3825 0 : Self::ensure_shard_zero(&timeline)?;
3826 0 : let req: page_api::GetSlruSegmentRequest = req.into_inner().try_into()?;
3827 :
3828 0 : span_record!(kind=%req.kind, segno=%req.segno, lsn=%req.read_lsn);
3829 :
3830 0 : let req = PagestreamGetSlruSegmentRequest {
3831 0 : hdr: Self::make_hdr(req.read_lsn, None),
3832 0 : kind: req.kind as u8,
3833 0 : segno: req.segno,
3834 0 : };
3835 :
3836 : // Execute the request and convert the response.
3837 0 : let _timer = Self::record_op_start_and_throttle(
3838 0 : &timeline,
3839 0 : metrics::SmgrQueryType::GetSlruSegment,
3840 0 : received_at,
3841 0 : )
3842 0 : .await?;
3843 :
3844 0 : let resp =
3845 0 : PageServerHandler::handle_get_slru_segment_request(&timeline, &req, &ctx).await?;
3846 0 : let resp: page_api::GetSlruSegmentResponse = resp.segment;
3847 0 : Ok(tonic::Response::new(resp.into()))
3848 0 : }
3849 :
3850 : #[instrument(skip_all, fields(lsn))]
3851 : async fn lease_lsn(
3852 : &self,
3853 : req: tonic::Request<proto::LeaseLsnRequest>,
3854 0 : ) -> Result<tonic::Response<proto::LeaseLsnResponse>, tonic::Status> {
3855 0 : let timeline = self.get_request_timeline(&req).await?;
3856 0 : let ctx = self.ctx.with_scope_timeline(&timeline);
3857 :
3858 : // Validate and convert the request, and decorate the span.
3859 0 : let req: page_api::LeaseLsnRequest = req.into_inner().try_into()?;
3860 :
3861 0 : span_record!(lsn=%req.lsn);
3862 :
3863 : // Attempt to acquire a lease. Return FailedPrecondition if the lease could not be granted.
3864 0 : let lease_length = timeline.get_lsn_lease_length();
3865 0 : let expires = match timeline.renew_lsn_lease(req.lsn, lease_length, &ctx) {
3866 0 : Ok(lease) => lease.valid_until,
3867 0 : Err(err) => return Err(tonic::Status::failed_precondition(format!("{err}"))),
3868 : };
3869 :
3870 : // TODO: is this spammy? Move it compute-side?
3871 0 : info!(
3872 0 : "acquired lease for {} until {}",
3873 : req.lsn,
3874 0 : chrono::DateTime::<Utc>::from(expires).to_rfc3339()
3875 : );
3876 :
3877 0 : Ok(tonic::Response::new(expires.into()))
3878 0 : }
3879 : }
3880 :
3881 : /// gRPC middleware layer that handles observability concerns:
3882 : ///
3883 : /// * Creates and enters a tracing span.
3884 : /// * Records the request start time as a ReceivedAt request extension.
3885 : ///
3886 : /// TODO: add perf tracing.
3887 : /// TODO: add timing and metrics.
3888 : /// TODO: add logging.
3889 : #[derive(Clone)]
3890 : struct ObservabilityLayer;
3891 :
3892 : impl<S: tonic::server::NamedService> tower::Layer<S> for ObservabilityLayer {
3893 : type Service = ObservabilityLayerService<S>;
3894 :
3895 0 : fn layer(&self, inner: S) -> Self::Service {
3896 0 : Self::Service { inner }
3897 0 : }
3898 : }
3899 :
3900 : #[derive(Clone)]
3901 : struct ObservabilityLayerService<S> {
3902 : inner: S,
3903 : }
3904 :
3905 : #[derive(Clone, Copy)]
3906 : struct ReceivedAt(Instant);
3907 :
3908 : impl<S: tonic::server::NamedService> tonic::server::NamedService for ObservabilityLayerService<S> {
3909 : const NAME: &'static str = S::NAME; // propagate inner service name
3910 : }
3911 :
3912 : impl<S, Req, Resp> tower::Service<http::Request<Req>> for ObservabilityLayerService<S>
3913 : where
3914 : S: tower::Service<http::Request<Req>, Response = http::Response<Resp>> + Send,
3915 : S::Future: Send + 'static,
3916 : {
3917 : type Response = S::Response;
3918 : type Error = S::Error;
3919 : type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
3920 :
3921 0 : fn call(&mut self, mut req: http::Request<Req>) -> Self::Future {
3922 : // Record the request start time as a request extension.
3923 : //
3924 : // TODO: we should start a timer here instead, but it currently requires a timeline handle
3925 : // and SmgrQueryType, which we don't have yet. Refactor it to provide it later.
3926 0 : req.extensions_mut().insert(ReceivedAt(Instant::now()));
3927 :
3928 : // Extract the peer address and gRPC method.
3929 0 : let peer = req
3930 0 : .extensions()
3931 0 : .get::<TcpConnectInfo>()
3932 0 : .and_then(|info| info.remote_addr())
3933 0 : .map(|addr| addr.to_string())
3934 0 : .unwrap_or_default();
3935 :
3936 0 : let method = req
3937 0 : .uri()
3938 0 : .path()
3939 0 : .split('/')
3940 0 : .nth(2)
3941 0 : .unwrap_or(req.uri().path())
3942 0 : .to_string();
3943 :
3944 : // Create a basic tracing span.
3945 : //
3946 : // Enter the span for the current thread and instrument the future. It is not sufficient to
3947 : // only instrument the future, since it only takes effect after the future is returned and
3948 : // polled, not when the inner service is called below (e.g. during interceptor execution).
3949 0 : let span = info_span!(
3950 : "grpc:pageservice",
3951 : // These will be populated by TenantMetadataInterceptor.
3952 : tenant_id = field::Empty,
3953 : timeline_id = field::Empty,
3954 : shard_id = field::Empty,
3955 : // NB: empty fields must be listed first above. Otherwise, the field names will be
3956 : // clobbered when the empty fields are populated. They will be output last regardless.
3957 : %peer,
3958 : %method,
3959 : );
3960 0 : let _guard = span.enter();
3961 :
3962 : // Construct a future for calling the inner service, but don't await it. This avoids having
3963 : // to clone the inner service into the future below.
3964 0 : let call = self.inner.call(req);
3965 :
3966 0 : async move {
3967 : // Await the inner service call.
3968 0 : let result = call.await;
3969 :
3970 : // Log gRPC error statuses. This won't include request info from handler spans, but it
3971 : // will catch all errors (even those emitted before handler spans are constructed). Only
3972 : // unary request errors are logged here, not streaming response errors.
3973 0 : if let Ok(ref resp) = result
3974 0 : && let Some(status) = tonic::Status::from_header_map(resp.headers())
3975 0 : && status.code() != tonic::Code::Ok
3976 : {
3977 : // TODO: it would be nice if we could propagate the handler span's request fields
3978 : // here. This could e.g. be done by attaching the request fields to
3979 : // tonic::Status::metadata via a proc macro.
3980 0 : warn!(
3981 0 : "request failed with {:?}: {}",
3982 0 : status.code(),
3983 0 : status.message()
3984 : );
3985 0 : }
3986 :
3987 0 : result
3988 0 : }
3989 0 : .instrument(span.clone())
3990 0 : .boxed()
3991 0 : }
3992 :
3993 0 : fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
3994 0 : self.inner.poll_ready(cx)
3995 0 : }
3996 : }
3997 :
3998 : /// gRPC interceptor that decodes tenant metadata and stores it as request extensions of type
3999 : /// TenantTimelineId and ShardIndex.
4000 : #[derive(Clone)]
4001 : struct TenantMetadataInterceptor;
4002 :
4003 : impl tonic::service::Interceptor for TenantMetadataInterceptor {
4004 0 : fn call(&mut self, mut req: tonic::Request<()>) -> Result<tonic::Request<()>, tonic::Status> {
4005 : // Decode the tenant ID.
4006 0 : let tenant_id = req
4007 0 : .metadata()
4008 0 : .get("neon-tenant-id")
4009 0 : .ok_or_else(|| tonic::Status::invalid_argument("missing neon-tenant-id"))?
4010 0 : .to_str()
4011 0 : .map_err(|_| tonic::Status::invalid_argument("invalid neon-tenant-id"))?;
4012 0 : let tenant_id = TenantId::from_str(tenant_id)
4013 0 : .map_err(|_| tonic::Status::invalid_argument("invalid neon-tenant-id"))?;
4014 :
4015 : // Decode the timeline ID.
4016 0 : let timeline_id = req
4017 0 : .metadata()
4018 0 : .get("neon-timeline-id")
4019 0 : .ok_or_else(|| tonic::Status::invalid_argument("missing neon-timeline-id"))?
4020 0 : .to_str()
4021 0 : .map_err(|_| tonic::Status::invalid_argument("invalid neon-timeline-id"))?;
4022 0 : let timeline_id = TimelineId::from_str(timeline_id)
4023 0 : .map_err(|_| tonic::Status::invalid_argument("invalid neon-timeline-id"))?;
4024 :
4025 : // Decode the shard ID.
4026 0 : let shard_id = req
4027 0 : .metadata()
4028 0 : .get("neon-shard-id")
4029 0 : .ok_or_else(|| tonic::Status::invalid_argument("missing neon-shard-id"))?
4030 0 : .to_str()
4031 0 : .map_err(|_| tonic::Status::invalid_argument("invalid neon-shard-id"))?;
4032 0 : let shard_id = ShardIndex::from_str(shard_id)
4033 0 : .map_err(|_| tonic::Status::invalid_argument("invalid neon-shard-id"))?;
4034 :
4035 : // Stash them in the request.
4036 0 : let extensions = req.extensions_mut();
4037 0 : extensions.insert(TenantTimelineId::new(tenant_id, timeline_id));
4038 0 : extensions.insert(shard_id);
4039 :
4040 : // Decorate the tracing span.
4041 0 : span_record!(%tenant_id, %timeline_id, %shard_id);
4042 :
4043 0 : Ok(req)
4044 0 : }
4045 : }
4046 :
4047 : /// Authenticates gRPC page service requests.
4048 : #[derive(Clone)]
4049 : struct TenantAuthInterceptor {
4050 : auth: Option<Arc<SwappableJwtAuth>>,
4051 : }
4052 :
4053 : impl TenantAuthInterceptor {
4054 0 : fn new(auth: Option<Arc<SwappableJwtAuth>>) -> Self {
4055 0 : Self { auth }
4056 0 : }
4057 : }
4058 :
4059 : impl tonic::service::Interceptor for TenantAuthInterceptor {
4060 0 : fn call(&mut self, req: tonic::Request<()>) -> Result<tonic::Request<()>, tonic::Status> {
4061 : // Do nothing if auth is disabled.
4062 0 : let Some(auth) = self.auth.as_ref() else {
4063 0 : return Ok(req);
4064 : };
4065 :
4066 : // Fetch the tenant ID from the request extensions (set by TenantMetadataInterceptor).
4067 0 : let TenantTimelineId { tenant_id, .. } = *extract::<TenantTimelineId>(&req);
4068 :
4069 : // Fetch and decode the JWT token.
4070 0 : let jwt = req
4071 0 : .metadata()
4072 0 : .get("authorization")
4073 0 : .ok_or_else(|| tonic::Status::unauthenticated("no authorization header"))?
4074 0 : .to_str()
4075 0 : .map_err(|_| tonic::Status::invalid_argument("invalid authorization header"))?
4076 0 : .strip_prefix("Bearer ")
4077 0 : .ok_or_else(|| tonic::Status::invalid_argument("invalid authorization header"))?
4078 0 : .trim();
4079 0 : let jwtdata: TokenData<Claims> = auth
4080 0 : .decode(jwt)
4081 0 : .map_err(|err| tonic::Status::invalid_argument(format!("invalid JWT token: {err}")))?;
4082 0 : let claims = jwtdata.claims;
4083 :
4084 : // Check if the token is valid for this tenant.
4085 0 : check_permission(&claims, Some(tenant_id))
4086 0 : .map_err(|err| tonic::Status::permission_denied(err.to_string()))?;
4087 :
4088 : // TODO: consider stashing the claims in the request extensions, if needed.
4089 :
4090 0 : Ok(req)
4091 0 : }
4092 : }
4093 :
4094 : /// Extracts the given type from the request extensions, or panics if it is missing.
4095 0 : fn extract<T: Send + Sync + 'static>(req: &tonic::Request<impl Any>) -> &T {
4096 0 : extract_from(req.extensions())
4097 0 : }
4098 :
4099 : /// Extract the given type from the request extensions, or panics if it is missing. This variant
4100 : /// can extract both from a tonic::Request and http::Request.
4101 0 : fn extract_from<T: Send + Sync + 'static>(ext: &http::Extensions) -> &T {
4102 0 : let Some(value) = ext.get::<T>() else {
4103 0 : let name = std::any::type_name::<T>();
4104 0 : panic!("extension {name} should be set by middleware");
4105 : };
4106 0 : value
4107 0 : }
4108 :
4109 : #[derive(Debug, thiserror::Error)]
4110 : pub(crate) enum GetActiveTimelineError {
4111 : #[error(transparent)]
4112 : Tenant(GetActiveTenantError),
4113 : #[error(transparent)]
4114 : Timeline(#[from] GetTimelineError),
4115 : }
4116 :
4117 : impl From<GetActiveTimelineError> for QueryError {
4118 0 : fn from(e: GetActiveTimelineError) -> Self {
4119 0 : match e {
4120 0 : GetActiveTimelineError::Tenant(GetActiveTenantError::Cancelled) => QueryError::Shutdown,
4121 0 : GetActiveTimelineError::Tenant(e) => e.into(),
4122 0 : GetActiveTimelineError::Timeline(e) => QueryError::NotFound(format!("{e}").into()),
4123 : }
4124 0 : }
4125 : }
4126 :
4127 : impl From<GetActiveTimelineError> for tonic::Status {
4128 0 : fn from(err: GetActiveTimelineError) -> Self {
4129 0 : let message = err.to_string();
4130 0 : let code = match err {
4131 0 : GetActiveTimelineError::Tenant(err) => tonic::Status::from(err).code(),
4132 0 : GetActiveTimelineError::Timeline(err) => tonic::Status::from(err).code(),
4133 : };
4134 0 : tonic::Status::new(code, message)
4135 0 : }
4136 : }
4137 :
4138 : impl From<GetTimelineError> for tonic::Status {
4139 0 : fn from(err: GetTimelineError) -> Self {
4140 : use tonic::Code;
4141 0 : let code = match &err {
4142 0 : GetTimelineError::NotFound { .. } => Code::NotFound,
4143 0 : GetTimelineError::NotActive { .. } => Code::Unavailable,
4144 0 : GetTimelineError::ShuttingDown => Code::Unavailable,
4145 : };
4146 0 : tonic::Status::new(code, err.to_string())
4147 0 : }
4148 : }
4149 :
4150 : impl From<GetActiveTenantError> for QueryError {
4151 0 : fn from(e: GetActiveTenantError) -> Self {
4152 0 : match e {
4153 0 : GetActiveTenantError::WaitForActiveTimeout { .. } => QueryError::Disconnected(
4154 0 : ConnectionError::Io(io::Error::new(io::ErrorKind::TimedOut, e.to_string())),
4155 0 : ),
4156 : GetActiveTenantError::Cancelled
4157 : | GetActiveTenantError::WillNotBecomeActive(TenantState::Stopping { .. }) => {
4158 0 : QueryError::Shutdown
4159 : }
4160 0 : e @ GetActiveTenantError::NotFound(_) => QueryError::NotFound(format!("{e}").into()),
4161 0 : e => QueryError::Other(anyhow::anyhow!(e)),
4162 : }
4163 0 : }
4164 : }
4165 :
4166 : impl From<GetActiveTenantError> for tonic::Status {
4167 0 : fn from(err: GetActiveTenantError) -> Self {
4168 : use tonic::Code;
4169 0 : let code = match &err {
4170 0 : GetActiveTenantError::Broken(_) => Code::Internal,
4171 0 : GetActiveTenantError::Cancelled => Code::Unavailable,
4172 0 : GetActiveTenantError::NotFound(_) => Code::NotFound,
4173 0 : GetActiveTenantError::SwitchedTenant => Code::Unavailable,
4174 0 : GetActiveTenantError::WaitForActiveTimeout { .. } => Code::Unavailable,
4175 0 : GetActiveTenantError::WillNotBecomeActive(_) => Code::Unavailable,
4176 : };
4177 0 : tonic::Status::new(code, err.to_string())
4178 0 : }
4179 : }
4180 :
4181 : impl From<HandleUpgradeError> for QueryError {
4182 0 : fn from(e: HandleUpgradeError) -> Self {
4183 0 : match e {
4184 0 : HandleUpgradeError::ShutDown => QueryError::Shutdown,
4185 : }
4186 0 : }
4187 : }
4188 :
4189 : impl From<HandleUpgradeError> for tonic::Status {
4190 0 : fn from(err: HandleUpgradeError) -> Self {
4191 0 : match err {
4192 0 : HandleUpgradeError::ShutDown => tonic::Status::unavailable("timeline is shutting down"),
4193 : }
4194 0 : }
4195 : }
4196 :
4197 0 : fn set_tracing_field_shard_id(timeline: &Timeline) {
4198 0 : debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
4199 0 : tracing::Span::current().record(
4200 0 : "shard_id",
4201 0 : tracing::field::display(timeline.tenant_shard_id.shard_slug()),
4202 : );
4203 0 : debug_assert_current_span_has_tenant_and_timeline_id();
4204 0 : }
4205 :
4206 : struct WaitedForLsn(Lsn);
4207 : impl From<WaitedForLsn> for Lsn {
4208 0 : fn from(WaitedForLsn(lsn): WaitedForLsn) -> Self {
4209 0 : lsn
4210 0 : }
4211 : }
4212 :
4213 : #[cfg(test)]
4214 : mod tests {
4215 : use utils::shard::ShardCount;
4216 :
4217 : use super::*;
4218 :
4219 : #[test]
4220 1 : fn pageservice_cmd_parse() {
4221 1 : let tenant_id = TenantId::generate();
4222 1 : let timeline_id = TimelineId::generate();
4223 1 : let cmd =
4224 1 : PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id} {timeline_id}")).unwrap();
4225 1 : assert_eq!(
4226 : cmd,
4227 1 : PageServiceCmd::PageStream(PageStreamCmd {
4228 1 : tenant_id,
4229 1 : timeline_id,
4230 1 : protocol_version: PagestreamProtocolVersion::V2,
4231 1 : })
4232 : );
4233 1 : let cmd = PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id}")).unwrap();
4234 1 : assert_eq!(
4235 : cmd,
4236 1 : PageServiceCmd::BaseBackup(BaseBackupCmd {
4237 1 : tenant_id,
4238 1 : timeline_id,
4239 1 : lsn: None,
4240 1 : gzip: false,
4241 1 : replica: false
4242 1 : })
4243 : );
4244 1 : let cmd =
4245 1 : PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} --gzip")).unwrap();
4246 1 : assert_eq!(
4247 : cmd,
4248 1 : PageServiceCmd::BaseBackup(BaseBackupCmd {
4249 1 : tenant_id,
4250 1 : timeline_id,
4251 1 : lsn: None,
4252 1 : gzip: true,
4253 1 : replica: false
4254 1 : })
4255 : );
4256 1 : let cmd =
4257 1 : PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} latest")).unwrap();
4258 1 : assert_eq!(
4259 : cmd,
4260 1 : PageServiceCmd::BaseBackup(BaseBackupCmd {
4261 1 : tenant_id,
4262 1 : timeline_id,
4263 1 : lsn: None,
4264 1 : gzip: false,
4265 1 : replica: false
4266 1 : })
4267 : );
4268 1 : let cmd = PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} 0/16ABCDE"))
4269 1 : .unwrap();
4270 1 : assert_eq!(
4271 : cmd,
4272 1 : PageServiceCmd::BaseBackup(BaseBackupCmd {
4273 1 : tenant_id,
4274 1 : timeline_id,
4275 1 : lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
4276 1 : gzip: false,
4277 1 : replica: false
4278 1 : })
4279 : );
4280 1 : let cmd = PageServiceCmd::parse(&format!(
4281 1 : "basebackup {tenant_id} {timeline_id} --replica --gzip"
4282 1 : ))
4283 1 : .unwrap();
4284 1 : assert_eq!(
4285 : cmd,
4286 1 : PageServiceCmd::BaseBackup(BaseBackupCmd {
4287 1 : tenant_id,
4288 1 : timeline_id,
4289 1 : lsn: None,
4290 1 : gzip: true,
4291 1 : replica: true
4292 1 : })
4293 : );
4294 1 : let cmd = PageServiceCmd::parse(&format!(
4295 1 : "basebackup {tenant_id} {timeline_id} 0/16ABCDE --replica --gzip"
4296 1 : ))
4297 1 : .unwrap();
4298 1 : assert_eq!(
4299 : cmd,
4300 1 : PageServiceCmd::BaseBackup(BaseBackupCmd {
4301 1 : tenant_id,
4302 1 : timeline_id,
4303 1 : lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
4304 1 : gzip: true,
4305 1 : replica: true
4306 1 : })
4307 : );
4308 1 : let cmd = PageServiceCmd::parse(&format!("fullbackup {tenant_id} {timeline_id}")).unwrap();
4309 1 : assert_eq!(
4310 : cmd,
4311 1 : PageServiceCmd::FullBackup(FullBackupCmd {
4312 1 : tenant_id,
4313 1 : timeline_id,
4314 1 : lsn: None,
4315 1 : prev_lsn: None
4316 1 : })
4317 : );
4318 1 : let cmd = PageServiceCmd::parse(&format!(
4319 1 : "fullbackup {tenant_id} {timeline_id} 0/16ABCDE 0/16ABCDF"
4320 1 : ))
4321 1 : .unwrap();
4322 1 : assert_eq!(
4323 : cmd,
4324 1 : PageServiceCmd::FullBackup(FullBackupCmd {
4325 1 : tenant_id,
4326 1 : timeline_id,
4327 1 : lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
4328 1 : prev_lsn: Some(Lsn::from_str("0/16ABCDF").unwrap()),
4329 1 : })
4330 : );
4331 1 : let tenant_shard_id = TenantShardId::unsharded(tenant_id);
4332 1 : let cmd = PageServiceCmd::parse(&format!(
4333 1 : "lease lsn {tenant_shard_id} {timeline_id} 0/16ABCDE"
4334 1 : ))
4335 1 : .unwrap();
4336 1 : assert_eq!(
4337 : cmd,
4338 1 : PageServiceCmd::LeaseLsn(LeaseLsnCmd {
4339 1 : tenant_shard_id,
4340 1 : timeline_id,
4341 1 : lsn: Lsn::from_str("0/16ABCDE").unwrap(),
4342 1 : })
4343 : );
4344 1 : let tenant_shard_id = TenantShardId::split(&tenant_shard_id, ShardCount(8))[1];
4345 1 : let cmd = PageServiceCmd::parse(&format!(
4346 1 : "lease lsn {tenant_shard_id} {timeline_id} 0/16ABCDE"
4347 1 : ))
4348 1 : .unwrap();
4349 1 : assert_eq!(
4350 : cmd,
4351 1 : PageServiceCmd::LeaseLsn(LeaseLsnCmd {
4352 1 : tenant_shard_id,
4353 1 : timeline_id,
4354 1 : lsn: Lsn::from_str("0/16ABCDE").unwrap(),
4355 1 : })
4356 : );
4357 1 : let cmd = PageServiceCmd::parse("set a = b").unwrap();
4358 1 : assert_eq!(cmd, PageServiceCmd::Set);
4359 1 : let cmd = PageServiceCmd::parse("SET foo").unwrap();
4360 1 : assert_eq!(cmd, PageServiceCmd::Set);
4361 1 : }
4362 :
4363 : #[test]
4364 1 : fn pageservice_cmd_err_handling() {
4365 1 : let tenant_id = TenantId::generate();
4366 1 : let timeline_id = TimelineId::generate();
4367 1 : let cmd = PageServiceCmd::parse("unknown_command");
4368 1 : assert!(cmd.is_err());
4369 1 : let cmd = PageServiceCmd::parse("pagestream_v2");
4370 1 : assert!(cmd.is_err());
4371 1 : let cmd = PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id}xxx"));
4372 1 : assert!(cmd.is_err());
4373 1 : let cmd = PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id}xxx {timeline_id}xxx"));
4374 1 : assert!(cmd.is_err());
4375 1 : let cmd = PageServiceCmd::parse(&format!(
4376 1 : "basebackup {tenant_id} {timeline_id} --gzip --gzip"
4377 1 : ));
4378 1 : assert!(cmd.is_err());
4379 1 : let cmd = PageServiceCmd::parse(&format!(
4380 1 : "basebackup {tenant_id} {timeline_id} --gzip --unknown"
4381 1 : ));
4382 1 : assert!(cmd.is_err());
4383 1 : let cmd = PageServiceCmd::parse(&format!(
4384 1 : "basebackup {tenant_id} {timeline_id} --gzip 0/16ABCDE"
4385 1 : ));
4386 1 : assert!(cmd.is_err());
4387 1 : let cmd = PageServiceCmd::parse(&format!("lease {tenant_id} {timeline_id} gzip 0/16ABCDE"));
4388 1 : assert!(cmd.is_err());
4389 1 : }
4390 :
4391 : #[test]
4392 1 : fn test_parse_options() {
4393 1 : let (config, has_error) = parse_options(" -c neon.compute_mode=primary ");
4394 1 : assert!(!has_error);
4395 1 : assert_eq!(
4396 : config,
4397 1 : vec![("neon.compute_mode".to_string(), "primary".to_string())]
4398 : );
4399 :
4400 1 : let (config, has_error) = parse_options(" -c neon.compute_mode=primary -c foo=bar ");
4401 1 : assert!(!has_error);
4402 1 : assert_eq!(
4403 : config,
4404 1 : vec![
4405 1 : ("neon.compute_mode".to_string(), "primary".to_string()),
4406 1 : ("foo".to_string(), "bar".to_string()),
4407 : ]
4408 : );
4409 :
4410 1 : let (config, has_error) = parse_options(" -c neon.compute_mode=primary -cfoo=bar");
4411 1 : assert!(!has_error);
4412 1 : assert_eq!(
4413 : config,
4414 1 : vec![
4415 1 : ("neon.compute_mode".to_string(), "primary".to_string()),
4416 1 : ("foo".to_string(), "bar".to_string()),
4417 : ]
4418 : );
4419 :
4420 1 : let (_, has_error) = parse_options("-c");
4421 1 : assert!(has_error);
4422 :
4423 1 : let (_, has_error) = parse_options("-c foo=bar -c -c");
4424 1 : assert!(has_error);
4425 :
4426 1 : let (_, has_error) = parse_options(" ");
4427 1 : assert!(!has_error);
4428 :
4429 1 : let (_, has_error) = parse_options(" -c neon.compute_mode");
4430 1 : assert!(has_error);
4431 1 : }
4432 : }
|