Line data Source code
1 : //! Part of Safekeeper pretending to be Postgres, i.e. handling Postgres
2 : //! protocol commands.
3 :
4 : use std::future::Future;
5 : use std::str::{self, FromStr};
6 : use std::sync::Arc;
7 :
8 : use anyhow::Context;
9 : use jsonwebtoken::TokenData;
10 : use pageserver_api::models::ShardParameters;
11 : use pageserver_api::shard::{ShardIdentity, ShardStripeSize};
12 : use postgres_backend::{PostgresBackend, QueryError};
13 : use postgres_ffi::PG_TLI;
14 : use pq_proto::{BeMessage, FeStartupPacket, INT4_OID, RowDescriptor, TEXT_OID};
15 : use regex::Regex;
16 : use safekeeper_api::Term;
17 : use safekeeper_api::models::ConnectionId;
18 : use tokio::io::{AsyncRead, AsyncWrite};
19 : use tracing::{Instrument, debug, info, info_span};
20 : use utils::auth::{Claims, JwtAuth, Scope};
21 : use utils::id::{TenantId, TenantTimelineId, TimelineId};
22 : use utils::lsn::Lsn;
23 : use utils::postgres_client::PostgresClientProtocol;
24 : use utils::shard::{ShardCount, ShardNumber};
25 :
26 : use crate::auth::check_permission;
27 : use crate::metrics::{PG_QUERIES_GAUGE, TrafficMetrics};
28 : use crate::timeline::TimelineError;
29 : use crate::{GlobalTimelines, SafeKeeperConf};
30 :
31 : /// Safekeeper handler of postgres commands
32 : pub struct SafekeeperPostgresHandler {
33 : pub conf: Arc<SafeKeeperConf>,
34 : /// assigned application name
35 : pub appname: Option<String>,
36 : pub tenant_id: Option<TenantId>,
37 : pub timeline_id: Option<TimelineId>,
38 : pub ttid: TenantTimelineId,
39 : pub shard: Option<ShardIdentity>,
40 : pub protocol: Option<PostgresClientProtocol>,
41 : /// Unique connection id is logged in spans for observability.
42 : pub conn_id: ConnectionId,
43 : pub global_timelines: Arc<GlobalTimelines>,
44 : /// Auth scope allowed on the connections and public key used to check auth tokens. None if auth is not configured.
45 : auth: Option<(Scope, Arc<JwtAuth>)>,
46 : claims: Option<Claims>,
47 : io_metrics: Option<TrafficMetrics>,
48 : }
49 :
50 : /// Parsed Postgres command.
51 : enum SafekeeperPostgresCommand {
52 : StartWalPush {
53 : proto_version: u32,
54 : // Eventually timelines will be always created explicitly by storcon.
55 : // This option allows legacy behaviour for compute to do that until we
56 : // fully migrate.
57 : allow_timeline_creation: bool,
58 : },
59 : StartReplication {
60 : start_lsn: Lsn,
61 : term: Option<Term>,
62 : },
63 : IdentifySystem,
64 : TimelineStatus,
65 : }
66 :
67 2 : fn parse_cmd(cmd: &str) -> anyhow::Result<SafekeeperPostgresCommand> {
68 2 : if cmd.starts_with("START_WAL_PUSH") {
69 : // Allow additional options in postgres START_REPLICATION style like
70 : // START_WAL_PUSH (proto_version '3', allow_timeline_creation 'false').
71 : // Parsing here is very naive and breaks in case of commas or
72 : // whitespaces in values, but enough for our purposes.
73 2 : let re = Regex::new(r"START_WAL_PUSH(\s+?\((.*)\))?").unwrap();
74 2 : let caps = re
75 2 : .captures(cmd)
76 2 : .context(format!("failed to parse START_WAL_PUSH command {cmd}"))?;
77 : // capture () content
78 2 : let options = caps.get(2).map(|m| m.as_str()).unwrap_or("");
79 : // default values
80 2 : let mut proto_version = 2;
81 2 : let mut allow_timeline_creation = true;
82 4 : for kvstr in options.split(",") {
83 4 : if kvstr.is_empty() {
84 1 : continue;
85 3 : }
86 3 : let mut kvit = kvstr.split_whitespace();
87 3 : let key = kvit.next().context(format!(
88 3 : "failed to parse key in kv {kvstr} in command {cmd}"
89 0 : ))?;
90 3 : let value = kvit.next().context(format!(
91 3 : "failed to parse value in kv {kvstr} in command {cmd}"
92 0 : ))?;
93 3 : let value_trimmed = value.trim_matches('\'');
94 3 : if key == "proto_version" {
95 1 : proto_version = value_trimmed.parse::<u32>().context(format!(
96 1 : "failed to parse proto_version value {value} in command {cmd}"
97 0 : ))?;
98 2 : }
99 3 : if key == "allow_timeline_creation" {
100 1 : allow_timeline_creation = value_trimmed.parse::<bool>().context(format!(
101 1 : "failed to parse allow_timeline_creation value {value} in command {cmd}"
102 0 : ))?;
103 2 : }
104 : }
105 2 : Ok(SafekeeperPostgresCommand::StartWalPush {
106 2 : proto_version,
107 2 : allow_timeline_creation,
108 2 : })
109 0 : } else if cmd.starts_with("START_REPLICATION") {
110 0 : let re = Regex::new(
111 : // We follow postgres START_REPLICATION LOGICAL options to pass term.
112 0 : r"START_REPLICATION(?: SLOT [^ ]+)?(?: PHYSICAL)? ([[:xdigit:]]+/[[:xdigit:]]+)(?: \(term='(\d+)'\))?",
113 : )
114 0 : .unwrap();
115 0 : let caps = re
116 0 : .captures(cmd)
117 0 : .context(format!("failed to parse START_REPLICATION command {cmd}"))?;
118 0 : let start_lsn =
119 0 : Lsn::from_str(&caps[1]).context("parse start LSN from START_REPLICATION command")?;
120 0 : let term = if let Some(m) = caps.get(2) {
121 0 : Some(m.as_str().parse::<u64>().context("invalid term")?)
122 : } else {
123 0 : None
124 : };
125 0 : Ok(SafekeeperPostgresCommand::StartReplication { start_lsn, term })
126 0 : } else if cmd.starts_with("IDENTIFY_SYSTEM") {
127 0 : Ok(SafekeeperPostgresCommand::IdentifySystem)
128 0 : } else if cmd.starts_with("TIMELINE_STATUS") {
129 0 : Ok(SafekeeperPostgresCommand::TimelineStatus)
130 : } else {
131 0 : anyhow::bail!("unsupported command {cmd}");
132 : }
133 2 : }
134 :
135 0 : fn cmd_to_string(cmd: &SafekeeperPostgresCommand) -> &str {
136 0 : match cmd {
137 0 : SafekeeperPostgresCommand::StartWalPush { .. } => "START_WAL_PUSH",
138 0 : SafekeeperPostgresCommand::StartReplication { .. } => "START_REPLICATION",
139 0 : SafekeeperPostgresCommand::TimelineStatus => "TIMELINE_STATUS",
140 0 : SafekeeperPostgresCommand::IdentifySystem => "IDENTIFY_SYSTEM",
141 : }
142 0 : }
143 :
144 : impl<IO: AsyncRead + AsyncWrite + Unpin + Send> postgres_backend::Handler<IO>
145 : for SafekeeperPostgresHandler
146 : {
147 : // tenant_id and timeline_id are passed in connection string params
148 0 : fn startup(
149 0 : &mut self,
150 0 : _pgb: &mut PostgresBackend<IO>,
151 0 : sm: &FeStartupPacket,
152 0 : ) -> Result<(), QueryError> {
153 0 : if let FeStartupPacket::StartupMessage { params, .. } = sm {
154 0 : if let Some(options) = params.options_raw() {
155 0 : let mut shard_count: Option<u8> = None;
156 0 : let mut shard_number: Option<u8> = None;
157 0 : let mut shard_stripe_size: Option<u32> = None;
158 :
159 0 : for opt in options {
160 : // FIXME `ztenantid` and `ztimelineid` left for compatibility during deploy,
161 : // remove these after the PR gets deployed:
162 : // https://github.com/neondatabase/neon/pull/2433#discussion_r970005064
163 0 : match opt.split_once('=') {
164 0 : Some(("protocol", value)) => {
165 : self.protocol =
166 0 : Some(serde_json::from_str(value).with_context(|| {
167 0 : format!("Failed to parse {value} as protocol")
168 0 : })?);
169 : }
170 0 : Some(("ztenantid", value)) | Some(("tenant_id", value)) => {
171 0 : self.tenant_id = Some(value.parse().with_context(|| {
172 0 : format!("Failed to parse {value} as tenant id")
173 0 : })?);
174 : }
175 0 : Some(("ztimelineid", value)) | Some(("timeline_id", value)) => {
176 0 : self.timeline_id = Some(value.parse().with_context(|| {
177 0 : format!("Failed to parse {value} as timeline id")
178 0 : })?);
179 : }
180 0 : Some(("availability_zone", client_az)) => {
181 0 : if let Some(metrics) = self.io_metrics.as_ref() {
182 0 : metrics.set_client_az(client_az)
183 0 : }
184 : }
185 0 : Some(("shard_count", value)) => {
186 0 : shard_count = Some(value.parse::<u8>().with_context(|| {
187 0 : format!("Failed to parse {value} as shard count")
188 0 : })?);
189 : }
190 0 : Some(("shard_number", value)) => {
191 0 : shard_number = Some(value.parse::<u8>().with_context(|| {
192 0 : format!("Failed to parse {value} as shard number")
193 0 : })?);
194 : }
195 0 : Some(("shard_stripe_size", value)) => {
196 0 : shard_stripe_size = Some(value.parse::<u32>().with_context(|| {
197 0 : format!("Failed to parse {value} as shard stripe size")
198 0 : })?);
199 : }
200 0 : _ => continue,
201 : }
202 : }
203 :
204 0 : match self.protocol() {
205 : PostgresClientProtocol::Vanilla => {
206 0 : if shard_count.is_some()
207 0 : || shard_number.is_some()
208 0 : || shard_stripe_size.is_some()
209 : {
210 0 : return Err(QueryError::Other(anyhow::anyhow!(
211 0 : "Shard params specified for vanilla protocol"
212 0 : )));
213 0 : }
214 : }
215 : PostgresClientProtocol::Interpreted { .. } => {
216 0 : match (shard_count, shard_number, shard_stripe_size) {
217 0 : (Some(count), Some(number), Some(stripe_size)) => {
218 0 : let params = ShardParameters {
219 0 : count: ShardCount(count),
220 0 : stripe_size: ShardStripeSize(stripe_size),
221 0 : };
222 0 : self.shard =
223 0 : Some(ShardIdentity::from_params(ShardNumber(number), params));
224 0 : }
225 : _ => {
226 0 : return Err(QueryError::Other(anyhow::anyhow!(
227 0 : "Shard params were not specified"
228 0 : )));
229 : }
230 : }
231 : }
232 : }
233 0 : }
234 :
235 0 : if let Some(app_name) = params.get("application_name") {
236 0 : self.appname = Some(app_name.to_owned());
237 0 : if let Some(metrics) = self.io_metrics.as_ref() {
238 0 : metrics.set_app_name(app_name)
239 0 : }
240 0 : }
241 :
242 0 : let ttid = TenantTimelineId::new(
243 0 : self.tenant_id.unwrap_or(TenantId::from([0u8; 16])),
244 0 : self.timeline_id.unwrap_or(TimelineId::from([0u8; 16])),
245 : );
246 0 : tracing::Span::current()
247 0 : .record("ttid", tracing::field::display(ttid))
248 0 : .record(
249 0 : "application_name",
250 0 : tracing::field::debug(self.appname.clone()),
251 : );
252 :
253 0 : if let Some(shard) = self.shard.as_ref() {
254 0 : if let Some(slug) = shard.shard_slug().strip_prefix("-") {
255 0 : tracing::Span::current().record("shard", tracing::field::display(slug));
256 0 : }
257 0 : }
258 :
259 0 : Ok(())
260 : } else {
261 0 : Err(QueryError::Other(anyhow::anyhow!(
262 0 : "Safekeeper received unexpected initial message: {sm:?}"
263 0 : )))
264 : }
265 0 : }
266 :
267 0 : fn check_auth_jwt(
268 0 : &mut self,
269 0 : _pgb: &mut PostgresBackend<IO>,
270 0 : jwt_response: &[u8],
271 0 : ) -> Result<(), QueryError> {
272 : // this unwrap is never triggered, because check_auth_jwt only called when auth_type is NeonJWT
273 : // which requires auth to be present
274 0 : let (allowed_auth_scope, auth) = self
275 0 : .auth
276 0 : .as_ref()
277 0 : .expect("auth_type is configured but .auth of handler is missing");
278 0 : let data: TokenData<Claims> = auth
279 0 : .decode(str::from_utf8(jwt_response).context("jwt response is not UTF-8")?)
280 0 : .map_err(|e| QueryError::Unauthorized(e.0))?;
281 :
282 : // The handler might be configured to allow only tenant scope tokens.
283 0 : if matches!(allowed_auth_scope, Scope::Tenant)
284 0 : && !matches!(data.claims.scope, Scope::Tenant)
285 : {
286 0 : return Err(QueryError::Unauthorized(
287 0 : "passed JWT token is for full access, but only tenant scope is allowed".into(),
288 0 : ));
289 0 : }
290 :
291 0 : if matches!(data.claims.scope, Scope::Tenant) && data.claims.tenant_id.is_none() {
292 0 : return Err(QueryError::Unauthorized(
293 0 : "jwt token scope is Tenant, but tenant id is missing".into(),
294 0 : ));
295 0 : }
296 :
297 0 : debug!(
298 0 : "jwt scope check succeeded for scope: {:#?} by tenant id: {:?}",
299 : data.claims.scope, data.claims.tenant_id,
300 : );
301 :
302 0 : self.claims = Some(data.claims);
303 0 : Ok(())
304 0 : }
305 :
306 0 : fn process_query(
307 0 : &mut self,
308 0 : pgb: &mut PostgresBackend<IO>,
309 0 : query_string: &str,
310 0 : ) -> impl Future<Output = Result<(), QueryError>> {
311 0 : Box::pin(async move {
312 0 : if query_string
313 0 : .to_ascii_lowercase()
314 0 : .starts_with("set datestyle to ")
315 : {
316 : // important for debug because psycopg2 executes "SET datestyle TO 'ISO'" on connect
317 0 : pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
318 0 : return Ok(());
319 0 : }
320 :
321 0 : let cmd = parse_cmd(query_string)?;
322 0 : let cmd_str = cmd_to_string(&cmd);
323 :
324 0 : let _guard = PG_QUERIES_GAUGE.with_label_values(&[cmd_str]).guard();
325 :
326 0 : info!("got query {:?}", query_string);
327 :
328 0 : let tenant_id = self.tenant_id.context("tenantid is required")?;
329 0 : let timeline_id = self.timeline_id.context("timelineid is required")?;
330 0 : self.check_permission(Some(tenant_id))?;
331 0 : self.ttid = TenantTimelineId::new(tenant_id, timeline_id);
332 :
333 0 : match cmd {
334 : SafekeeperPostgresCommand::StartWalPush {
335 0 : proto_version,
336 0 : allow_timeline_creation,
337 : } => {
338 0 : self.handle_start_wal_push(pgb, proto_version, allow_timeline_creation)
339 0 : .instrument(info_span!("WAL receiver"))
340 0 : .await
341 : }
342 0 : SafekeeperPostgresCommand::StartReplication { start_lsn, term } => {
343 0 : self.handle_start_replication(pgb, start_lsn, term)
344 0 : .instrument(info_span!("WAL sender"))
345 0 : .await
346 : }
347 0 : SafekeeperPostgresCommand::IdentifySystem => self.handle_identify_system(pgb).await,
348 0 : SafekeeperPostgresCommand::TimelineStatus => self.handle_timeline_status(pgb).await,
349 : }
350 0 : })
351 0 : }
352 : }
353 :
354 : impl SafekeeperPostgresHandler {
355 0 : pub fn new(
356 0 : conf: Arc<SafeKeeperConf>,
357 0 : conn_id: u32,
358 0 : io_metrics: Option<TrafficMetrics>,
359 0 : auth: Option<(Scope, Arc<JwtAuth>)>,
360 0 : global_timelines: Arc<GlobalTimelines>,
361 0 : ) -> Self {
362 0 : SafekeeperPostgresHandler {
363 0 : conf,
364 0 : appname: None,
365 0 : tenant_id: None,
366 0 : timeline_id: None,
367 0 : ttid: TenantTimelineId::empty(),
368 0 : shard: None,
369 0 : protocol: None,
370 0 : conn_id,
371 0 : claims: None,
372 0 : auth,
373 0 : io_metrics,
374 0 : global_timelines,
375 0 : }
376 0 : }
377 :
378 0 : pub fn protocol(&self) -> PostgresClientProtocol {
379 0 : self.protocol.unwrap_or(PostgresClientProtocol::Vanilla)
380 0 : }
381 :
382 : // when accessing management api supply None as an argument
383 : // when using to authorize tenant pass corresponding tenant id
384 0 : fn check_permission(&self, tenant_id: Option<TenantId>) -> Result<(), QueryError> {
385 0 : if self.auth.is_none() {
386 : // auth is set to Trust, nothing to check so just return ok
387 0 : return Ok(());
388 0 : }
389 : // auth is some, just checked above, when auth is some
390 : // then claims are always present because of checks during connection init
391 : // so this expect won't trigger
392 0 : let claims = self
393 0 : .claims
394 0 : .as_ref()
395 0 : .expect("claims presence already checked");
396 0 : check_permission(claims, tenant_id).map_err(|e| QueryError::Unauthorized(e.0))
397 0 : }
398 :
399 0 : async fn handle_timeline_status<IO: AsyncRead + AsyncWrite + Unpin>(
400 0 : &mut self,
401 0 : pgb: &mut PostgresBackend<IO>,
402 0 : ) -> Result<(), QueryError> {
403 : // Get timeline, handling "not found" error
404 0 : let tli = match self.global_timelines.get(self.ttid) {
405 0 : Ok(tli) => Ok(Some(tli)),
406 0 : Err(TimelineError::NotFound(_)) => Ok(None),
407 0 : Err(e) => Err(QueryError::Other(e.into())),
408 0 : }?;
409 :
410 : // Write row description
411 0 : pgb.write_message_noflush(&BeMessage::RowDescription(&[
412 0 : RowDescriptor::text_col(b"flush_lsn"),
413 0 : RowDescriptor::text_col(b"commit_lsn"),
414 0 : ]))?;
415 :
416 : // Write row if timeline exists
417 0 : if let Some(tli) = tli {
418 0 : let (inmem, _state) = tli.get_state().await;
419 0 : let flush_lsn = tli.get_flush_lsn().await;
420 0 : let commit_lsn = inmem.commit_lsn;
421 0 : pgb.write_message_noflush(&BeMessage::DataRow(&[
422 0 : Some(flush_lsn.to_string().as_bytes()),
423 0 : Some(commit_lsn.to_string().as_bytes()),
424 0 : ]))?;
425 0 : }
426 :
427 0 : pgb.write_message_noflush(&BeMessage::CommandComplete(b"TIMELINE_STATUS"))?;
428 0 : Ok(())
429 0 : }
430 :
431 : ///
432 : /// Handle IDENTIFY_SYSTEM replication command
433 : ///
434 0 : async fn handle_identify_system<IO: AsyncRead + AsyncWrite + Unpin>(
435 0 : &mut self,
436 0 : pgb: &mut PostgresBackend<IO>,
437 0 : ) -> Result<(), QueryError> {
438 0 : let tli = self
439 0 : .global_timelines
440 0 : .get(self.ttid)
441 0 : .map_err(|e| QueryError::Other(e.into()))?;
442 :
443 0 : let lsn = if self.is_walproposer_recovery() {
444 : // walproposer should get all local WAL until flush_lsn
445 0 : tli.get_flush_lsn().await
446 : } else {
447 : // other clients shouldn't get any uncommitted WAL
448 0 : tli.get_state().await.0.commit_lsn
449 : }
450 0 : .to_string();
451 :
452 0 : let sysid = tli.get_state().await.1.server.system_id.to_string();
453 0 : let lsn_bytes = lsn.as_bytes();
454 0 : let tli = PG_TLI.to_string();
455 0 : let tli_bytes = tli.as_bytes();
456 0 : let sysid_bytes = sysid.as_bytes();
457 :
458 0 : pgb.write_message_noflush(&BeMessage::RowDescription(&[
459 0 : RowDescriptor {
460 0 : name: b"systemid",
461 0 : typoid: TEXT_OID,
462 0 : typlen: -1,
463 0 : ..Default::default()
464 0 : },
465 0 : RowDescriptor {
466 0 : name: b"timeline",
467 0 : typoid: INT4_OID,
468 0 : typlen: 4,
469 0 : ..Default::default()
470 0 : },
471 0 : RowDescriptor {
472 0 : name: b"xlogpos",
473 0 : typoid: TEXT_OID,
474 0 : typlen: -1,
475 0 : ..Default::default()
476 0 : },
477 0 : RowDescriptor {
478 0 : name: b"dbname",
479 0 : typoid: TEXT_OID,
480 0 : typlen: -1,
481 0 : ..Default::default()
482 0 : },
483 0 : ]))?
484 0 : .write_message_noflush(&BeMessage::DataRow(&[
485 0 : Some(sysid_bytes),
486 0 : Some(tli_bytes),
487 0 : Some(lsn_bytes),
488 0 : None,
489 0 : ]))?
490 0 : .write_message_noflush(&BeMessage::CommandComplete(b"IDENTIFY_SYSTEM"))?;
491 0 : Ok(())
492 0 : }
493 :
494 : /// Returns true if current connection is a replication connection, originating
495 : /// from a walproposer recovery function. This connection gets a special handling:
496 : /// safekeeper must stream all local WAL till the flush_lsn, whether committed or not.
497 0 : pub fn is_walproposer_recovery(&self) -> bool {
498 0 : match &self.appname {
499 0 : None => false,
500 0 : Some(appname) => {
501 0 : appname == "wal_proposer_recovery" ||
502 : // set by safekeeper peer recovery
503 0 : appname.starts_with("safekeeper")
504 : }
505 : }
506 0 : }
507 : }
508 :
509 : #[cfg(test)]
510 : mod tests {
511 : use super::SafekeeperPostgresCommand;
512 :
513 : /// Test parsing of START_WAL_PUSH command
514 : #[test]
515 1 : fn test_start_wal_push_parse() {
516 1 : let cmd = "START_WAL_PUSH";
517 1 : let parsed = super::parse_cmd(cmd).expect("failed to parse");
518 1 : match parsed {
519 : SafekeeperPostgresCommand::StartWalPush {
520 1 : proto_version,
521 1 : allow_timeline_creation,
522 : } => {
523 1 : assert_eq!(proto_version, 2);
524 1 : assert!(allow_timeline_creation);
525 : }
526 0 : _ => panic!("unexpected command"),
527 : }
528 :
529 1 : let cmd =
530 1 : "START_WAL_PUSH (proto_version '3', allow_timeline_creation 'false', unknown 'hoho')";
531 1 : let parsed = super::parse_cmd(cmd).expect("failed to parse");
532 1 : match parsed {
533 : SafekeeperPostgresCommand::StartWalPush {
534 1 : proto_version,
535 1 : allow_timeline_creation,
536 : } => {
537 1 : assert_eq!(proto_version, 3);
538 1 : assert!(!allow_timeline_creation);
539 : }
540 0 : _ => panic!("unexpected command"),
541 : }
542 1 : }
543 : }
|