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