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