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