Line data Source code
1 : //! Connection request monitoring contexts
2 :
3 : use std::net::IpAddr;
4 :
5 : use chrono::Utc;
6 : use once_cell::sync::OnceCell;
7 : use pq_proto::StartupMessageParams;
8 : use smol_str::SmolStr;
9 : use tokio::sync::mpsc;
10 : use tracing::field::display;
11 : use tracing::{debug, info, info_span, Span};
12 : use try_lock::TryLock;
13 : use uuid::Uuid;
14 :
15 : use self::parquet::RequestData;
16 : use crate::control_plane::messages::{ColdStartInfo, MetricsAuxInfo};
17 : use crate::error::ErrorKind;
18 : use crate::intern::{BranchIdInt, ProjectIdInt};
19 : use crate::metrics::{
20 : ConnectOutcome, InvalidEndpointsGroup, LatencyTimer, Metrics, Protocol, Waiting,
21 : };
22 : use crate::protocol2::ConnectionInfo;
23 : use crate::types::{DbName, EndpointId, RoleName};
24 :
25 : pub mod parquet;
26 :
27 : pub(crate) static LOG_CHAN: OnceCell<mpsc::WeakUnboundedSender<RequestData>> = OnceCell::new();
28 : pub(crate) static LOG_CHAN_DISCONNECT: OnceCell<mpsc::WeakUnboundedSender<RequestData>> =
29 : OnceCell::new();
30 :
31 : /// Context data for a single request to connect to a database.
32 : ///
33 : /// This data should **not** be used for connection logic, only for observability and limiting purposes.
34 : /// All connection logic should instead use strongly typed state machines, not a bunch of Options.
35 : pub struct RequestMonitoring(
36 : /// To allow easier use of the ctx object, we have interior mutability.
37 : /// I would typically use a RefCell but that would break the `Send` requirements
38 : /// so we need something with thread-safety. `TryLock` is a cheap alternative
39 : /// that offers similar semantics to a `RefCell` but with synchronisation.
40 : TryLock<RequestMonitoringInner>,
41 : );
42 :
43 : struct RequestMonitoringInner {
44 : pub(crate) conn_info: ConnectionInfo,
45 : pub(crate) session_id: Uuid,
46 : pub(crate) protocol: Protocol,
47 : first_packet: chrono::DateTime<Utc>,
48 : region: &'static str,
49 : pub(crate) span: Span,
50 :
51 : // filled in as they are discovered
52 : project: Option<ProjectIdInt>,
53 : branch: Option<BranchIdInt>,
54 : endpoint_id: Option<EndpointId>,
55 : dbname: Option<DbName>,
56 : user: Option<RoleName>,
57 : application: Option<SmolStr>,
58 : error_kind: Option<ErrorKind>,
59 : pub(crate) auth_method: Option<AuthMethod>,
60 : success: bool,
61 : pub(crate) cold_start_info: ColdStartInfo,
62 : pg_options: Option<StartupMessageParams>,
63 :
64 : // extra
65 : // This sender is here to keep the request monitoring channel open while requests are taking place.
66 : sender: Option<mpsc::UnboundedSender<RequestData>>,
67 : // This sender is only used to log the length of session in case of success.
68 : disconnect_sender: Option<mpsc::UnboundedSender<RequestData>>,
69 : pub(crate) latency_timer: LatencyTimer,
70 : // Whether proxy decided that it's not a valid endpoint end rejected it before going to cplane.
71 : rejected: Option<bool>,
72 : disconnect_timestamp: Option<chrono::DateTime<Utc>>,
73 : }
74 :
75 : #[derive(Clone, Debug)]
76 : pub(crate) enum AuthMethod {
77 : // aka passwordless, fka link
78 : ConsoleRedirect,
79 : ScramSha256,
80 : ScramSha256Plus,
81 : Cleartext,
82 : }
83 :
84 : impl Clone for RequestMonitoring {
85 0 : fn clone(&self) -> Self {
86 0 : let inner = self.0.try_lock().expect("should not deadlock");
87 0 : let new = RequestMonitoringInner {
88 0 : conn_info: inner.conn_info.clone(),
89 0 : session_id: inner.session_id,
90 0 : protocol: inner.protocol,
91 0 : first_packet: inner.first_packet,
92 0 : region: inner.region,
93 0 : span: info_span!("background_task"),
94 :
95 0 : project: inner.project,
96 0 : branch: inner.branch,
97 0 : endpoint_id: inner.endpoint_id.clone(),
98 0 : dbname: inner.dbname.clone(),
99 0 : user: inner.user.clone(),
100 0 : application: inner.application.clone(),
101 0 : error_kind: inner.error_kind,
102 0 : auth_method: inner.auth_method.clone(),
103 0 : success: inner.success,
104 0 : rejected: inner.rejected,
105 0 : cold_start_info: inner.cold_start_info,
106 0 : pg_options: inner.pg_options.clone(),
107 0 :
108 0 : sender: None,
109 0 : disconnect_sender: None,
110 0 : latency_timer: LatencyTimer::noop(inner.protocol),
111 0 : disconnect_timestamp: inner.disconnect_timestamp,
112 0 : };
113 0 :
114 0 : Self(TryLock::new(new))
115 0 : }
116 : }
117 :
118 : impl RequestMonitoring {
119 70 : pub fn new(
120 70 : session_id: Uuid,
121 70 : conn_info: ConnectionInfo,
122 70 : protocol: Protocol,
123 70 : region: &'static str,
124 70 : ) -> Self {
125 70 : let span = info_span!(
126 70 : "connect_request",
127 70 : %protocol,
128 70 : ?session_id,
129 70 : %conn_info,
130 70 : ep = tracing::field::Empty,
131 70 : role = tracing::field::Empty,
132 70 : );
133 :
134 70 : let inner = RequestMonitoringInner {
135 70 : conn_info,
136 70 : session_id,
137 70 : protocol,
138 70 : first_packet: Utc::now(),
139 70 : region,
140 70 : span,
141 70 :
142 70 : project: None,
143 70 : branch: None,
144 70 : endpoint_id: None,
145 70 : dbname: None,
146 70 : user: None,
147 70 : application: None,
148 70 : error_kind: None,
149 70 : auth_method: None,
150 70 : success: false,
151 70 : rejected: None,
152 70 : cold_start_info: ColdStartInfo::Unknown,
153 70 : pg_options: None,
154 70 :
155 70 : sender: LOG_CHAN.get().and_then(|tx| tx.upgrade()),
156 70 : disconnect_sender: LOG_CHAN_DISCONNECT.get().and_then(|tx| tx.upgrade()),
157 70 : latency_timer: LatencyTimer::new(protocol),
158 70 : disconnect_timestamp: None,
159 70 : };
160 70 :
161 70 : Self(TryLock::new(inner))
162 70 : }
163 :
164 : #[cfg(test)]
165 70 : pub(crate) fn test() -> Self {
166 : use std::net::SocketAddr;
167 70 : let ip = IpAddr::from([127, 0, 0, 1]);
168 70 : let addr = SocketAddr::new(ip, 5432);
169 70 : let conn_info = ConnectionInfo { addr, extra: None };
170 70 : RequestMonitoring::new(Uuid::now_v7(), conn_info, Protocol::Tcp, "test")
171 70 : }
172 :
173 0 : pub(crate) fn console_application_name(&self) -> String {
174 0 : let this = self.0.try_lock().expect("should not deadlock");
175 0 : format!(
176 0 : "{}/{}",
177 0 : this.application.as_deref().unwrap_or_default(),
178 0 : this.protocol
179 0 : )
180 0 : }
181 :
182 0 : pub(crate) fn set_rejected(&self, rejected: bool) {
183 0 : let mut this = self.0.try_lock().expect("should not deadlock");
184 0 : this.rejected = Some(rejected);
185 0 : }
186 :
187 0 : pub(crate) fn set_cold_start_info(&self, info: ColdStartInfo) {
188 0 : self.0
189 0 : .try_lock()
190 0 : .expect("should not deadlock")
191 0 : .set_cold_start_info(info);
192 0 : }
193 :
194 0 : pub(crate) fn set_db_options(&self, options: StartupMessageParams) {
195 0 : let mut this = self.0.try_lock().expect("should not deadlock");
196 0 : this.set_application(options.get("application_name").map(SmolStr::from));
197 0 : if let Some(user) = options.get("user") {
198 0 : this.set_user(user.into());
199 0 : }
200 0 : if let Some(dbname) = options.get("database") {
201 0 : this.set_dbname(dbname.into());
202 0 : }
203 :
204 0 : this.pg_options = Some(options);
205 0 : }
206 :
207 0 : pub(crate) fn set_project(&self, x: MetricsAuxInfo) {
208 0 : let mut this = self.0.try_lock().expect("should not deadlock");
209 0 : if this.endpoint_id.is_none() {
210 0 : this.set_endpoint_id(x.endpoint_id.as_str().into());
211 0 : }
212 0 : this.branch = Some(x.branch_id);
213 0 : this.project = Some(x.project_id);
214 0 : this.set_cold_start_info(x.cold_start_info);
215 0 : }
216 :
217 0 : pub(crate) fn set_project_id(&self, project_id: ProjectIdInt) {
218 0 : let mut this = self.0.try_lock().expect("should not deadlock");
219 0 : this.project = Some(project_id);
220 0 : }
221 :
222 28 : pub(crate) fn set_endpoint_id(&self, endpoint_id: EndpointId) {
223 28 : self.0
224 28 : .try_lock()
225 28 : .expect("should not deadlock")
226 28 : .set_endpoint_id(endpoint_id);
227 28 : }
228 :
229 0 : pub(crate) fn set_dbname(&self, dbname: DbName) {
230 0 : self.0
231 0 : .try_lock()
232 0 : .expect("should not deadlock")
233 0 : .set_dbname(dbname);
234 0 : }
235 :
236 0 : pub(crate) fn set_user(&self, user: RoleName) {
237 0 : self.0
238 0 : .try_lock()
239 0 : .expect("should not deadlock")
240 0 : .set_user(user);
241 0 : }
242 :
243 15 : pub(crate) fn set_auth_method(&self, auth_method: AuthMethod) {
244 15 : let mut this = self.0.try_lock().expect("should not deadlock");
245 15 : this.auth_method = Some(auth_method);
246 15 : }
247 :
248 0 : pub fn has_private_peer_addr(&self) -> bool {
249 0 : self.0
250 0 : .try_lock()
251 0 : .expect("should not deadlock")
252 0 : .has_private_peer_addr()
253 0 : }
254 :
255 0 : pub(crate) fn set_error_kind(&self, kind: ErrorKind) {
256 0 : let mut this = self.0.try_lock().expect("should not deadlock");
257 0 : // Do not record errors from the private address to metrics.
258 0 : if !this.has_private_peer_addr() {
259 0 : Metrics::get().proxy.errors_total.inc(kind);
260 0 : }
261 0 : if let Some(ep) = &this.endpoint_id {
262 0 : let metric = &Metrics::get().proxy.endpoints_affected_by_errors;
263 0 : let label = metric.with_labels(kind);
264 0 : metric.get_metric(label).measure(ep);
265 0 : }
266 0 : this.error_kind = Some(kind);
267 0 : }
268 :
269 0 : pub fn set_success(&self) {
270 0 : let mut this = self.0.try_lock().expect("should not deadlock");
271 0 : this.success = true;
272 0 : }
273 :
274 0 : pub fn log_connect(&self) {
275 0 : self.0
276 0 : .try_lock()
277 0 : .expect("should not deadlock")
278 0 : .log_connect();
279 0 : }
280 :
281 0 : pub(crate) fn protocol(&self) -> Protocol {
282 0 : self.0.try_lock().expect("should not deadlock").protocol
283 0 : }
284 :
285 0 : pub(crate) fn span(&self) -> Span {
286 0 : self.0.try_lock().expect("should not deadlock").span.clone()
287 0 : }
288 :
289 0 : pub(crate) fn session_id(&self) -> Uuid {
290 0 : self.0.try_lock().expect("should not deadlock").session_id
291 0 : }
292 :
293 6 : pub(crate) fn peer_addr(&self) -> IpAddr {
294 6 : self.0
295 6 : .try_lock()
296 6 : .expect("should not deadlock")
297 6 : .conn_info
298 6 : .addr
299 6 : .ip()
300 6 : }
301 :
302 0 : pub(crate) fn cold_start_info(&self) -> ColdStartInfo {
303 0 : self.0
304 0 : .try_lock()
305 0 : .expect("should not deadlock")
306 0 : .cold_start_info
307 0 : }
308 :
309 28 : pub(crate) fn latency_timer_pause(&self, waiting_for: Waiting) -> LatencyTimerPause<'_> {
310 28 : LatencyTimerPause {
311 28 : ctx: self,
312 28 : start: tokio::time::Instant::now(),
313 28 : waiting_for,
314 28 : }
315 28 : }
316 :
317 4 : pub(crate) fn success(&self) {
318 4 : self.0
319 4 : .try_lock()
320 4 : .expect("should not deadlock")
321 4 : .latency_timer
322 4 : .success();
323 4 : }
324 : }
325 :
326 : pub(crate) struct LatencyTimerPause<'a> {
327 : ctx: &'a RequestMonitoring,
328 : start: tokio::time::Instant,
329 : waiting_for: Waiting,
330 : }
331 :
332 : impl Drop for LatencyTimerPause<'_> {
333 28 : fn drop(&mut self) {
334 28 : self.ctx
335 28 : .0
336 28 : .try_lock()
337 28 : .expect("should not deadlock")
338 28 : .latency_timer
339 28 : .unpause(self.start, self.waiting_for);
340 28 : }
341 : }
342 :
343 : impl RequestMonitoringInner {
344 0 : fn set_cold_start_info(&mut self, info: ColdStartInfo) {
345 0 : self.cold_start_info = info;
346 0 : self.latency_timer.cold_start_info(info);
347 0 : }
348 :
349 28 : fn set_endpoint_id(&mut self, endpoint_id: EndpointId) {
350 28 : if self.endpoint_id.is_none() {
351 28 : self.span.record("ep", display(&endpoint_id));
352 28 : let metric = &Metrics::get().proxy.connecting_endpoints;
353 28 : let label = metric.with_labels(self.protocol);
354 28 : metric.get_metric(label).measure(&endpoint_id);
355 28 : self.endpoint_id = Some(endpoint_id);
356 28 : }
357 28 : }
358 :
359 0 : fn set_application(&mut self, app: Option<SmolStr>) {
360 0 : if let Some(app) = app {
361 0 : self.application = Some(app);
362 0 : }
363 0 : }
364 :
365 0 : fn set_dbname(&mut self, dbname: DbName) {
366 0 : self.dbname = Some(dbname);
367 0 : }
368 :
369 0 : fn set_user(&mut self, user: RoleName) {
370 0 : self.span.record("role", display(&user));
371 0 : self.user = Some(user);
372 0 : }
373 :
374 0 : fn has_private_peer_addr(&self) -> bool {
375 0 : match self.conn_info.addr.ip() {
376 0 : IpAddr::V4(ip) => ip.is_private(),
377 0 : IpAddr::V6(_) => false,
378 : }
379 0 : }
380 :
381 0 : fn log_connect(&mut self) {
382 0 : let outcome = if self.success {
383 0 : ConnectOutcome::Success
384 : } else {
385 0 : ConnectOutcome::Failed
386 : };
387 0 : if let Some(rejected) = self.rejected {
388 0 : let ep = self
389 0 : .endpoint_id
390 0 : .as_ref()
391 0 : .map(|x| x.as_str())
392 0 : .unwrap_or_default();
393 0 : // This makes sense only if cache is disabled
394 0 : info!(
395 : ?outcome,
396 : ?rejected,
397 : ?ep,
398 0 : "check endpoint is valid with outcome"
399 : );
400 0 : Metrics::get()
401 0 : .proxy
402 0 : .invalid_endpoints_total
403 0 : .inc(InvalidEndpointsGroup {
404 0 : protocol: self.protocol,
405 0 : rejected: rejected.into(),
406 0 : outcome,
407 0 : });
408 0 : }
409 0 : if let Some(tx) = self.sender.take() {
410 0 : tx.send(RequestData::from(&*self))
411 0 : .inspect_err(|e| debug!("tx send failed: {e}"))
412 0 : .ok();
413 0 : }
414 0 : }
415 :
416 70 : fn log_disconnect(&mut self) {
417 70 : // If we are here, it's guaranteed that the user successfully connected to the endpoint.
418 70 : // Here we log the length of the session.
419 70 : self.disconnect_timestamp = Some(Utc::now());
420 70 : if let Some(tx) = self.disconnect_sender.take() {
421 0 : tx.send(RequestData::from(&*self))
422 0 : .inspect_err(|e| debug!("tx send failed: {e}"))
423 0 : .ok();
424 70 : }
425 70 : }
426 : }
427 :
428 : impl Drop for RequestMonitoringInner {
429 70 : fn drop(&mut self) {
430 70 : if self.sender.is_some() {
431 0 : self.log_connect();
432 70 : } else {
433 70 : self.log_disconnect();
434 70 : }
435 70 : }
436 : }
|