LCOV - code coverage report
Current view: top level - safekeeper/src - wal_service.rs (source / functions) Coverage Total Hit
Test: 09e7485004805bd42b53a0c369170b3228136512.info Lines: 0.0 % 69 0
Test Date: 2024-11-21 18:36:18 Functions: 0.0 % 9 0

            Line data    Source code
       1              : //!
       2              : //!   WAL service listens for client connections and
       3              : //!   receive WAL from wal_proposer and send it to WAL receivers
       4              : //!
       5              : use anyhow::{Context, Result};
       6              : use postgres_backend::QueryError;
       7              : use std::time::Duration;
       8              : use tokio::net::TcpStream;
       9              : use tokio_io_timeout::TimeoutReader;
      10              : use tokio_util::sync::CancellationToken;
      11              : use tracing::*;
      12              : use utils::{auth::Scope, measured_stream::MeasuredStream};
      13              : 
      14              : use crate::handler::SafekeeperPostgresHandler;
      15              : use crate::metrics::TrafficMetrics;
      16              : use crate::SafeKeeperConf;
      17              : use postgres_backend::{AuthType, PostgresBackend};
      18              : 
      19              : /// Accept incoming TCP connections and spawn them into a background thread.
      20              : ///
      21              : /// allowed_auth_scope is either SafekeeperData (wide JWT tokens giving access
      22              : /// to any tenant are allowed) or Tenant (only tokens giving access to specific
      23              : /// tenant are allowed). Doesn't matter if auth is disabled in conf.
      24            0 : pub async fn task_main(
      25            0 :     conf: SafeKeeperConf,
      26            0 :     pg_listener: std::net::TcpListener,
      27            0 :     allowed_auth_scope: Scope,
      28            0 : ) -> anyhow::Result<()> {
      29            0 :     // Tokio's from_std won't do this for us, per its comment.
      30            0 :     pg_listener.set_nonblocking(true)?;
      31              : 
      32            0 :     let listener = tokio::net::TcpListener::from_std(pg_listener)?;
      33            0 :     let mut connection_count: ConnectionCount = 0;
      34              : 
      35              :     loop {
      36            0 :         let (socket, peer_addr) = listener.accept().await.context("accept")?;
      37            0 :         debug!("accepted connection from {}", peer_addr);
      38            0 :         let conf = conf.clone();
      39            0 :         let conn_id = issue_connection_id(&mut connection_count);
      40              : 
      41            0 :         tokio::spawn(
      42            0 :             async move {
      43            0 :                 if let Err(err) = handle_socket(socket, conf, conn_id, allowed_auth_scope).await {
      44            0 :                     error!("connection handler exited: {}", err);
      45            0 :                 }
      46            0 :             }
      47            0 :             .instrument(info_span!("", cid = %conn_id, ttid = field::Empty, application_name = field::Empty)),
      48              :         );
      49              :     }
      50            0 : }
      51              : 
      52              : /// This is run by `task_main` above, inside a background thread.
      53              : ///
      54            0 : async fn handle_socket(
      55            0 :     socket: TcpStream,
      56            0 :     conf: SafeKeeperConf,
      57            0 :     conn_id: ConnectionId,
      58            0 :     allowed_auth_scope: Scope,
      59            0 : ) -> Result<(), QueryError> {
      60            0 :     socket.set_nodelay(true)?;
      61            0 :     let peer_addr = socket.peer_addr()?;
      62              : 
      63              :     // Set timeout on reading from the socket. It prevents hanged up connection
      64              :     // if client suddenly disappears. Note that TCP_KEEPALIVE is not enabled by
      65              :     // default, and tokio doesn't provide ability to set it out of the box.
      66            0 :     let mut socket = TimeoutReader::new(socket);
      67            0 :     let wal_service_timeout = Duration::from_secs(60 * 10);
      68            0 :     socket.set_timeout(Some(wal_service_timeout));
      69            0 :     // pin! is here because TimeoutReader (due to storing sleep future inside)
      70            0 :     // is not Unpin, and all pgbackend/framed/tokio dependencies require stream
      71            0 :     // to be Unpin. Which is reasonable, as indeed something like TimeoutReader
      72            0 :     // shouldn't be moved.
      73            0 :     let socket = std::pin::pin!(socket);
      74            0 : 
      75            0 :     let traffic_metrics = TrafficMetrics::new();
      76            0 :     if let Some(current_az) = conf.availability_zone.as_deref() {
      77            0 :         traffic_metrics.set_sk_az(current_az);
      78            0 :     }
      79              : 
      80            0 :     let socket = MeasuredStream::new(
      81            0 :         socket,
      82            0 :         |cnt| {
      83            0 :             traffic_metrics.observe_read(cnt);
      84            0 :         },
      85            0 :         |cnt| {
      86            0 :             traffic_metrics.observe_write(cnt);
      87            0 :         },
      88            0 :     );
      89              : 
      90            0 :     let auth_key = match allowed_auth_scope {
      91            0 :         Scope::Tenant => conf.pg_tenant_only_auth.clone(),
      92            0 :         _ => conf.pg_auth.clone(),
      93              :     };
      94            0 :     let auth_type = match auth_key {
      95            0 :         None => AuthType::Trust,
      96            0 :         Some(_) => AuthType::NeonJWT,
      97              :     };
      98            0 :     let auth_pair = auth_key.map(|key| (allowed_auth_scope, key));
      99            0 :     let mut conn_handler =
     100            0 :         SafekeeperPostgresHandler::new(conf, conn_id, Some(traffic_metrics.clone()), auth_pair);
     101            0 :     let pgbackend = PostgresBackend::new_from_io(socket, peer_addr, auth_type, None)?;
     102              :     // libpq protocol between safekeeper and walproposer / pageserver
     103              :     // We don't use shutdown.
     104            0 :     pgbackend
     105            0 :         .run(&mut conn_handler, &CancellationToken::new())
     106            0 :         .await
     107            0 : }
     108              : 
     109              : /// Unique WAL service connection ids are logged in spans for observability.
     110              : pub type ConnectionId = u32;
     111              : pub type ConnectionCount = u32;
     112              : 
     113            0 : pub fn issue_connection_id(count: &mut ConnectionCount) -> ConnectionId {
     114            0 :     *count = count.wrapping_add(1);
     115            0 :     *count
     116            0 : }
        

Generated by: LCOV version 2.1-beta